/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

Merge from Björn.

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
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 */
71
72
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
72
73
                                */
73
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
 
                                   getuid(), getgid(), setuid(),
75
 
                                   setgid() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
75
                                   getuid(), getgid(), seteuid(),
 
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,
80
81
                                   argp_parse(), ARGP_KEY_ARG,
81
82
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
82
83
#include <signal.h>             /* sigemptyset(), sigaddset(),
83
 
                                   sigaction(), SIGTERM, sigaction,
84
 
                                   sig_atomic_t */
 
84
                                   sigaction(), SIGTERM, sig_atomic_t,
 
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() */
125
128
static const char mandos_protocol_version[] = "1";
126
129
const char *argp_program_version = "mandos-client " VERSION;
127
130
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;
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
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
 
162
227
/* 
163
228
 * Initialize GPGME.
164
229
 */
165
230
static bool init_gpgme(const char *seckey,
166
231
                       const char *pubkey, const char *tempdir){
167
 
  int ret;
168
232
  gpgme_error_t rc;
169
233
  gpgme_engine_info_t engine_info;
170
234
  
173
237
   * Helper function to insert pub and seckey to the engine keyring.
174
238
   */
175
239
  bool import_key(const char *filename){
 
240
    int ret;
176
241
    int fd;
177
242
    gpgme_data_t pgp_data;
178
243
    
179
244
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
180
245
    if(fd == -1){
181
 
      perror("open");
 
246
      perror_plus("open");
182
247
      return false;
183
248
    }
184
249
    
198
263
    
199
264
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
200
265
    if(ret == -1){
201
 
      perror("close");
 
266
      perror_plus("close");
202
267
    }
203
268
    gpgme_data_release(pgp_data);
204
269
    return true;
249
314
    return false;
250
315
  }
251
316
  
252
 
  return true; 
 
317
  return true;
253
318
}
254
319
 
255
320
/* 
329
394
  
330
395
  /* Seek back to the beginning of the GPGME plaintext data buffer */
331
396
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
332
 
    perror("gpgme_data_seek");
 
397
    perror_plus("gpgme_data_seek");
333
398
    plaintext_length = -1;
334
399
    goto decrypt_end;
335
400
  }
340
405
                                      (size_t)plaintext_length,
341
406
                                      plaintext_capacity);
342
407
    if(plaintext_capacity == 0){
343
 
        perror("incbuffer");
 
408
        perror_plus("incbuffer");
344
409
        plaintext_length = -1;
345
410
        goto decrypt_end;
346
411
    }
353
418
      break;
354
419
    }
355
420
    if(ret < 0){
356
 
      perror("gpgme_data_read");
 
421
      perror_plus("gpgme_data_read");
357
422
      plaintext_length = -1;
358
423
      goto decrypt_end;
359
424
    }
416
481
  }
417
482
  
418
483
  /* OpenPGP credentials */
419
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
484
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
420
485
  if(ret != GNUTLS_E_SUCCESS){
421
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
422
 
                                                    from
423
 
                                                    -Wunreachable-code
424
 
                                                 */
 
486
    fprintf(stderr, "GnuTLS memory error: %s\n",
425
487
            safer_gnutls_strerror(ret));
426
488
    gnutls_global_deinit();
427
489
    return -1;
474
536
static int init_gnutls_session(gnutls_session_t *session){
475
537
  int ret;
476
538
  /* GnuTLS session creation */
477
 
  ret = gnutls_init(session, GNUTLS_SERVER);
 
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);
478
545
  if(ret != GNUTLS_E_SUCCESS){
479
546
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
480
547
            safer_gnutls_strerror(ret));
482
549
  
483
550
  {
484
551
    const char *err;
485
 
    ret = gnutls_priority_set_direct(*session, mc.priority, &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);
486
559
    if(ret != GNUTLS_E_SUCCESS){
487
560
      fprintf(stderr, "Syntax error at: %s\n", err);
488
561
      fprintf(stderr, "GnuTLS error: %s\n",
492
565
    }
493
566
  }
494
567
  
495
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
496
 
                               mc.cred);
 
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);
497
576
  if(ret != GNUTLS_E_SUCCESS){
498
577
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
499
578
            safer_gnutls_strerror(ret));
502
581
  }
503
582
  
504
583
  /* ignore client certificate if any. */
505
 
  gnutls_certificate_server_set_request(*session,
506
 
                                        GNUTLS_CERT_IGNORE);
 
584
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
507
585
  
508
586
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
509
587
  
518
596
static int start_mandos_communication(const char *ip, uint16_t port,
519
597
                                      AvahiIfIndex if_index,
520
598
                                      int af){
521
 
  int ret, tcp_sd;
 
599
  int ret, tcp_sd = -1;
522
600
  ssize_t sret;
523
601
  union {
524
602
    struct sockaddr_in in;
525
603
    struct sockaddr_in6 in6;
526
604
  } to;
527
605
  char *buffer = NULL;
528
 
  char *decrypted_buffer;
 
606
  char *decrypted_buffer = NULL;
529
607
  size_t buffer_length = 0;
530
608
  size_t buffer_capacity = 0;
531
 
  ssize_t decrypted_buffer_size;
532
609
  size_t written;
533
 
  int retval = 0;
 
610
  int retval = -1;
534
611
  gnutls_session_t session;
535
612
  int pf;                       /* Protocol family */
536
613
  
 
614
  errno = 0;
 
615
  
 
616
  if(quit_now){
 
617
    errno = EINTR;
 
618
    return -1;
 
619
  }
 
620
  
537
621
  switch(af){
538
622
  case AF_INET6:
539
623
    pf = PF_INET6;
543
627
    break;
544
628
  default:
545
629
    fprintf(stderr, "Bad address family: %d\n", af);
 
630
    errno = EINVAL;
546
631
    return -1;
547
632
  }
548
633
  
558
643
  
559
644
  tcp_sd = socket(pf, SOCK_STREAM, 0);
560
645
  if(tcp_sd < 0){
561
 
    perror("socket");
562
 
    return -1;
 
646
    int e = errno;
 
647
    perror_plus("socket");
 
648
    errno = e;
 
649
    goto mandos_end;
 
650
  }
 
651
  
 
652
  if(quit_now){
 
653
    errno = EINTR;
 
654
    goto mandos_end;
563
655
  }
564
656
  
565
657
  memset(&to, 0, sizeof(to));
571
663
    ret = inet_pton(af, ip, &to.in.sin_addr);
572
664
  }
573
665
  if(ret < 0 ){
574
 
    perror("inet_pton");
575
 
    return -1;
 
666
    int e = errno;
 
667
    perror_plus("inet_pton");
 
668
    errno = e;
 
669
    goto mandos_end;
576
670
  }
577
671
  if(ret == 0){
 
672
    int e = errno;
578
673
    fprintf(stderr, "Bad address: %s\n", ip);
579
 
    return -1;
 
674
    errno = e;
 
675
    goto mandos_end;
580
676
  }
581
677
  if(af == AF_INET6){
582
678
    to.in6.sin6_port = htons(port); /* Spurious warnings from
589
685
      if(if_index == AVAHI_IF_UNSPEC){
590
686
        fprintf(stderr, "An IPv6 link-local address is incomplete"
591
687
                " without a network interface\n");
592
 
        return -1;
 
688
        errno = EINVAL;
 
689
        goto mandos_end;
593
690
      }
594
691
      /* Set the network interface number as scope */
595
692
      to.in6.sin6_scope_id = (uint32_t)if_index;
600
697
                                     -Wunreachable-code */
601
698
  }
602
699
  
 
700
  if(quit_now){
 
701
    errno = EINTR;
 
702
    goto mandos_end;
 
703
  }
 
704
  
603
705
  if(debug){
604
706
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
605
707
      char interface[IF_NAMESIZE];
606
708
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
607
 
        perror("if_indextoname");
 
709
        perror_plus("if_indextoname");
608
710
      } else {
609
711
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
610
712
                ip, interface, port);
624
726
                        sizeof(addrstr));
625
727
    }
626
728
    if(pcret == NULL){
627
 
      perror("inet_ntop");
 
729
      perror_plus("inet_ntop");
628
730
    } else {
629
731
      if(strcmp(addrstr, ip) != 0){
630
732
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
632
734
    }
633
735
  }
634
736
  
 
737
  if(quit_now){
 
738
    errno = EINTR;
 
739
    goto mandos_end;
 
740
  }
 
741
  
635
742
  if(af == AF_INET6){
636
743
    ret = connect(tcp_sd, &to.in6, sizeof(to));
637
744
  } else {
638
745
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
639
746
  }
640
747
  if(ret < 0){
641
 
    perror("connect");
642
 
    return -1;
 
748
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
749
      int e = errno;
 
750
      perror_plus("connect");
 
751
      errno = e;
 
752
    }
 
753
    goto mandos_end;
 
754
  }
 
755
  
 
756
  if(quit_now){
 
757
    errno = EINTR;
 
758
    goto mandos_end;
643
759
  }
644
760
  
645
761
  const char *out = mandos_protocol_version;
649
765
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
650
766
                                   out_size - written));
651
767
    if(ret == -1){
652
 
      perror("write");
653
 
      retval = -1;
 
768
      int e = errno;
 
769
      perror_plus("write");
 
770
      errno = e;
654
771
      goto mandos_end;
655
772
    }
656
773
    written += (size_t)ret;
664
781
        break;
665
782
      }
666
783
    }
 
784
  
 
785
    if(quit_now){
 
786
      errno = EINTR;
 
787
      goto mandos_end;
 
788
    }
667
789
  }
668
790
  
669
791
  if(debug){
670
792
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
671
793
  }
672
794
  
 
795
  if(quit_now){
 
796
    errno = EINTR;
 
797
    goto mandos_end;
 
798
  }
 
799
  
 
800
  /* Spurious warning from -Wint-to-pointer-cast */
673
801
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
674
802
  
675
 
  do{
 
803
  if(quit_now){
 
804
    errno = EINTR;
 
805
    goto mandos_end;
 
806
  }
 
807
  
 
808
  do {
676
809
    ret = gnutls_handshake(session);
 
810
    if(quit_now){
 
811
      errno = EINTR;
 
812
      goto mandos_end;
 
813
    }
677
814
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
678
815
  
679
816
  if(ret != GNUTLS_E_SUCCESS){
681
818
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
682
819
      gnutls_perror(ret);
683
820
    }
684
 
    retval = -1;
 
821
    errno = EPROTO;
685
822
    goto mandos_end;
686
823
  }
687
824
  
693
830
  }
694
831
  
695
832
  while(true){
 
833
    
 
834
    if(quit_now){
 
835
      errno = EINTR;
 
836
      goto mandos_end;
 
837
    }
 
838
    
696
839
    buffer_capacity = incbuffer(&buffer, buffer_length,
697
840
                                   buffer_capacity);
698
841
    if(buffer_capacity == 0){
699
 
      perror("incbuffer");
700
 
      retval = -1;
 
842
      int e = errno;
 
843
      perror_plus("incbuffer");
 
844
      errno = e;
 
845
      goto mandos_end;
 
846
    }
 
847
    
 
848
    if(quit_now){
 
849
      errno = EINTR;
701
850
      goto mandos_end;
702
851
    }
703
852
    
712
861
      case GNUTLS_E_AGAIN:
713
862
        break;
714
863
      case GNUTLS_E_REHANDSHAKE:
715
 
        do{
 
864
        do {
716
865
          ret = gnutls_handshake(session);
 
866
          
 
867
          if(quit_now){
 
868
            errno = EINTR;
 
869
            goto mandos_end;
 
870
          }
717
871
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
718
872
        if(ret < 0){
719
873
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
720
874
          gnutls_perror(ret);
721
 
          retval = -1;
 
875
          errno = EPROTO;
722
876
          goto mandos_end;
723
877
        }
724
878
        break;
725
879
      default:
726
880
        fprintf(stderr, "Unknown error while reading data from"
727
881
                " encrypted session with Mandos server\n");
728
 
        retval = -1;
729
882
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
883
        errno = EIO;
730
884
        goto mandos_end;
731
885
      }
732
886
    } else {
738
892
    fprintf(stderr, "Closing TLS session\n");
739
893
  }
740
894
  
741
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
895
  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);
742
907
  
743
908
  if(buffer_length > 0){
 
909
    ssize_t decrypted_buffer_size;
744
910
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
745
911
                                               buffer_length,
746
912
                                               &decrypted_buffer);
747
913
    if(decrypted_buffer_size >= 0){
 
914
      
748
915
      written = 0;
749
916
      while(written < (size_t) decrypted_buffer_size){
 
917
        if(quit_now){
 
918
          errno = EINTR;
 
919
          goto mandos_end;
 
920
        }
 
921
        
750
922
        ret = (int)fwrite(decrypted_buffer + written, 1,
751
923
                          (size_t)decrypted_buffer_size - written,
752
924
                          stdout);
753
925
        if(ret == 0 and ferror(stdout)){
 
926
          int e = errno;
754
927
          if(debug){
755
928
            fprintf(stderr, "Error writing encrypted data: %s\n",
756
929
                    strerror(errno));
757
930
          }
758
 
          retval = -1;
759
 
          break;
 
931
          errno = e;
 
932
          goto mandos_end;
760
933
        }
761
934
        written += (size_t)ret;
762
935
      }
763
 
      free(decrypted_buffer);
764
 
    } else {
765
 
      retval = -1;
 
936
      retval = 0;
766
937
    }
767
 
  } else {
768
 
    retval = -1;
769
938
  }
770
939
  
771
940
  /* Shutdown procedure */
772
941
  
773
942
 mandos_end:
774
 
  free(buffer);
775
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
776
 
  if(ret == -1){
777
 
    perror("close");
 
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
    }
778
962
  }
779
 
  gnutls_deinit(session);
780
963
  return retval;
781
964
}
782
965
 
799
982
  /* Called whenever a service has been resolved successfully or
800
983
     timed out */
801
984
  
 
985
  if(quit_now){
 
986
    return;
 
987
  }
 
988
  
802
989
  switch(event){
803
990
  default:
804
991
  case AVAHI_RESOLVER_FAILURE:
820
1007
                                           avahi_proto_to_af(proto));
821
1008
      if(ret == 0){
822
1009
        avahi_simple_poll_quit(mc.simple_poll);
 
1010
      } else {
 
1011
        ret = add_server(ip, port, interface,
 
1012
                         avahi_proto_to_af(proto));
823
1013
      }
824
1014
    }
825
1015
  }
841
1031
  /* Called whenever a new services becomes available on the LAN or
842
1032
     is removed from the LAN */
843
1033
  
 
1034
  if(quit_now){
 
1035
    return;
 
1036
  }
 
1037
  
844
1038
  switch(event){
845
1039
  default:
846
1040
  case AVAHI_BROWSER_FAILURE:
875
1069
  }
876
1070
}
877
1071
 
878
 
sig_atomic_t quit_now = 0;
879
 
 
880
 
/* stop main loop after sigterm has been called */
881
 
static void handle_sigterm(__attribute__((unused)) int sig){
 
1072
/* Signal handler that stops main loop after SIGTERM */
 
1073
static void handle_sigterm(int sig){
882
1074
  if(quit_now){
883
1075
    return;
884
1076
  }
885
1077
  quit_now = 1;
 
1078
  signal_received = sig;
886
1079
  int old_errno = errno;
 
1080
  /* set main loop to exit */
887
1081
  if(mc.simple_poll != NULL){
888
1082
    avahi_simple_poll_quit(mc.simple_poll);
889
1083
  }
890
1084
  errno = old_errno;
891
1085
}
892
1086
 
 
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
 
893
1274
int main(int argc, char *argv[]){
894
1275
  AvahiSServiceBrowser *sb = NULL;
895
1276
  int error;
897
1278
  intmax_t tmpmax;
898
1279
  char *tmp;
899
1280
  int exitcode = EXIT_SUCCESS;
900
 
  const char *interface = "eth0";
 
1281
  const char *interface = "";
901
1282
  struct ifreq network;
902
1283
  int sd = -1;
903
 
  bool interface_taken_up = false;
 
1284
  bool take_down_interface = false;
904
1285
  uid_t uid;
905
1286
  gid_t gid;
906
 
  char *connect_to = NULL;
907
1287
  char tempdir[] = "/tmp/mandosXXXXXX";
908
1288
  bool tempdir_created = false;
909
1289
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
913
1293
  bool gnutls_initialized = false;
914
1294
  bool gpgme_initialized = false;
915
1295
  float delay = 2.5f;
 
1296
  double retry_interval = 10; /* 10s between trying a server and
 
1297
                                 retrying the same server again */
916
1298
  
917
 
  struct sigaction old_sigterm_action;
 
1299
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
918
1300
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
919
1301
  
 
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
  
920
1323
  {
921
1324
    struct argp_option options[] = {
922
1325
      { .name = "debug", .key = 128,
951
1354
        .arg = "SECONDS",
952
1355
        .doc = "Maximum delay to wait for interface startup",
953
1356
        .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 },
954
1370
      { .name = NULL }
955
1371
    };
956
1372
    
957
1373
    error_t parse_opt(int key, char *arg,
958
1374
                      struct argp_state *state){
 
1375
      errno = 0;
959
1376
      switch(key){
960
1377
      case 128:                 /* --debug */
961
1378
        debug = true;
977
1394
        tmpmax = strtoimax(arg, &tmp, 10);
978
1395
        if(errno != 0 or tmp == arg or *tmp != '\0'
979
1396
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
980
 
          fprintf(stderr, "Bad number of DH bits\n");
981
 
          exit(EXIT_FAILURE);
 
1397
          argp_error(state, "Bad number of DH bits");
982
1398
        }
983
1399
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
984
1400
        break;
989
1405
        errno = 0;
990
1406
        delay = strtof(arg, &tmp);
991
1407
        if(errno != 0 or tmp == arg or *tmp != '\0'){
992
 
          fprintf(stderr, "Bad delay\n");
993
 
          exit(EXIT_FAILURE);
 
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");
994
1416
        }
995
1417
        break;
996
 
      case ARGP_KEY_ARG:
997
 
        argp_usage(state);
998
 
      case ARGP_KEY_END:
 
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);
999
1431
        break;
1000
1432
      default:
1001
1433
        return ARGP_ERR_UNKNOWN;
1002
1434
      }
1003
 
      return 0;
 
1435
      return errno;
1004
1436
    }
1005
1437
    
1006
1438
    struct argp argp = { .options = options, .parser = parse_opt,
1007
1439
                         .args_doc = "",
1008
1440
                         .doc = "Mandos client -- Get and decrypt"
1009
1441
                         " passwords from a Mandos server" };
1010
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
1011
 
    if(ret == ARGP_ERR_UNKNOWN){
1012
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
1013
 
      exitcode = EXIT_FAILURE;
 
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;
1014
1455
      goto end;
1015
1456
    }
1016
1457
  }
1018
1459
  if(not debug){
1019
1460
    avahi_set_log_function(empty_log);
1020
1461
  }
 
1462
 
 
1463
  if(interface[0] == '\0'){
 
1464
    struct dirent **direntries;
 
1465
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1466
                  alphasort);
 
1467
    if(ret >= 1){
 
1468
      /* Pick the first good interface */
 
1469
      interface = strdup(direntries[0]->d_name);
 
1470
      if(debug){
 
1471
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1472
      }
 
1473
      if(interface == NULL){
 
1474
        perror_plus("malloc");
 
1475
        free(direntries);
 
1476
        exitcode = EXIT_FAILURE;
 
1477
        goto end;
 
1478
      }
 
1479
      free(direntries);
 
1480
    } else {
 
1481
      free(direntries);
 
1482
      fprintf(stderr, "Could not find a network interface\n");
 
1483
      exitcode = EXIT_FAILURE;
 
1484
      goto end;
 
1485
    }
 
1486
  }
1021
1487
  
1022
1488
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1023
1489
     from the signal handler */
1026
1492
  mc.simple_poll = avahi_simple_poll_new();
1027
1493
  if(mc.simple_poll == NULL){
1028
1494
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1029
 
    exitcode = EXIT_FAILURE;
 
1495
    exitcode = EX_UNAVAILABLE;
1030
1496
    goto end;
1031
1497
  }
1032
1498
  
1033
1499
  sigemptyset(&sigterm_action.sa_mask);
1034
1500
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1035
1501
  if(ret == -1){
1036
 
    perror("sigaddset");
1037
 
    exitcode = EXIT_FAILURE;
 
1502
    perror_plus("sigaddset");
 
1503
    exitcode = EX_OSERR;
1038
1504
    goto end;
1039
1505
  }
1040
1506
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1041
1507
  if(ret == -1){
1042
 
    perror("sigaddset");
1043
 
    exitcode = EXIT_FAILURE;
 
1508
    perror_plus("sigaddset");
 
1509
    exitcode = EX_OSERR;
1044
1510
    goto end;
1045
1511
  }
1046
1512
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1047
1513
  if(ret == -1){
1048
 
    perror("sigaddset");
1049
 
    exitcode = EXIT_FAILURE;
1050
 
    goto end;
1051
 
  }
1052
 
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
1053
 
  if(ret == -1){
1054
 
    perror("sigaction");
1055
 
    exitcode = EXIT_FAILURE;
1056
 
    goto end;
1057
 
  }  
 
1514
    perror_plus("sigaddset");
 
1515
    exitcode = EX_OSERR;
 
1516
    goto end;
 
1517
  }
 
1518
  /* Need to check if the handler is SIG_IGN before handling:
 
1519
     | [[info:libc:Initial Signal Actions]] |
 
1520
     | [[info:libc:Basic Signal Handling]]  |
 
1521
  */
 
1522
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
 
1523
  if(ret == -1){
 
1524
    perror_plus("sigaction");
 
1525
    return EX_OSERR;
 
1526
  }
 
1527
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1528
    ret = sigaction(SIGINT, &sigterm_action, NULL);
 
1529
    if(ret == -1){
 
1530
      perror_plus("sigaction");
 
1531
      exitcode = EX_OSERR;
 
1532
      goto end;
 
1533
    }
 
1534
  }
 
1535
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
 
1536
  if(ret == -1){
 
1537
    perror_plus("sigaction");
 
1538
    return EX_OSERR;
 
1539
  }
 
1540
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1541
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
 
1542
    if(ret == -1){
 
1543
      perror_plus("sigaction");
 
1544
      exitcode = EX_OSERR;
 
1545
      goto end;
 
1546
    }
 
1547
  }
 
1548
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
 
1549
  if(ret == -1){
 
1550
    perror_plus("sigaction");
 
1551
    return EX_OSERR;
 
1552
  }
 
1553
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1554
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
 
1555
    if(ret == -1){
 
1556
      perror_plus("sigaction");
 
1557
      exitcode = EX_OSERR;
 
1558
      goto end;
 
1559
    }
 
1560
  }
1058
1561
  
1059
1562
  /* If the interface is down, bring it up */
1060
 
  if(interface[0] != '\0'){
 
1563
  if(strcmp(interface, "none") != 0){
 
1564
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1565
    if(if_index == 0){
 
1566
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1567
      exitcode = EX_UNAVAILABLE;
 
1568
      goto end;
 
1569
    }
 
1570
    
 
1571
    if(quit_now){
 
1572
      goto end;
 
1573
    }
 
1574
    
 
1575
    /* Re-raise priviliges */
 
1576
    errno = 0;
 
1577
    ret = seteuid(0);
 
1578
    if(ret == -1){
 
1579
      perror_plus("seteuid");
 
1580
    }
 
1581
    
1061
1582
#ifdef __linux__
1062
1583
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1063
 
       messages to mess up the prompt */
 
1584
       messages about the network interface to mess up the prompt */
1064
1585
    ret = klogctl(8, NULL, 5);
1065
1586
    bool restore_loglevel = true;
1066
1587
    if(ret == -1){
1067
1588
      restore_loglevel = false;
1068
 
      perror("klogctl");
 
1589
      perror_plus("klogctl");
1069
1590
    }
1070
1591
#endif  /* __linux__ */
1071
1592
    
1072
1593
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1073
1594
    if(sd < 0){
1074
 
      perror("socket");
1075
 
      exitcode = EXIT_FAILURE;
 
1595
      perror_plus("socket");
 
1596
      exitcode = EX_OSERR;
1076
1597
#ifdef __linux__
1077
1598
      if(restore_loglevel){
1078
1599
        ret = klogctl(7, NULL, 0);
1079
1600
        if(ret == -1){
1080
 
          perror("klogctl");
 
1601
          perror_plus("klogctl");
1081
1602
        }
1082
1603
      }
1083
1604
#endif  /* __linux__ */
 
1605
      /* Lower privileges */
 
1606
      errno = 0;
 
1607
      ret = seteuid(uid);
 
1608
      if(ret == -1){
 
1609
        perror_plus("seteuid");
 
1610
      }
1084
1611
      goto end;
1085
1612
    }
1086
1613
    strcpy(network.ifr_name, interface);
1087
1614
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1088
1615
    if(ret == -1){
1089
 
      perror("ioctl SIOCGIFFLAGS");
 
1616
      perror_plus("ioctl SIOCGIFFLAGS");
1090
1617
#ifdef __linux__
1091
1618
      if(restore_loglevel){
1092
1619
        ret = klogctl(7, NULL, 0);
1093
1620
        if(ret == -1){
1094
 
          perror("klogctl");
 
1621
          perror_plus("klogctl");
1095
1622
        }
1096
1623
      }
1097
1624
#endif  /* __linux__ */
1098
 
      exitcode = EXIT_FAILURE;
 
1625
      exitcode = EX_OSERR;
 
1626
      /* Lower privileges */
 
1627
      errno = 0;
 
1628
      ret = seteuid(uid);
 
1629
      if(ret == -1){
 
1630
        perror_plus("seteuid");
 
1631
      }
1099
1632
      goto end;
1100
1633
    }
1101
1634
    if((network.ifr_flags & IFF_UP) == 0){
1102
1635
      network.ifr_flags |= IFF_UP;
 
1636
      take_down_interface = true;
1103
1637
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1104
1638
      if(ret == -1){
1105
 
        perror("ioctl SIOCSIFFLAGS");
1106
 
        exitcode = EXIT_FAILURE;
 
1639
        take_down_interface = false;
 
1640
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1641
        exitcode = EX_OSERR;
1107
1642
#ifdef __linux__
1108
1643
        if(restore_loglevel){
1109
1644
          ret = klogctl(7, NULL, 0);
1110
1645
          if(ret == -1){
1111
 
            perror("klogctl");
 
1646
            perror_plus("klogctl");
1112
1647
          }
1113
1648
        }
1114
1649
#endif  /* __linux__ */
 
1650
        /* Lower privileges */
 
1651
        errno = 0;
 
1652
        ret = seteuid(uid);
 
1653
        if(ret == -1){
 
1654
          perror_plus("seteuid");
 
1655
        }
1115
1656
        goto end;
1116
1657
      }
1117
 
      interface_taken_up = true;
1118
1658
    }
1119
 
    /* sleep checking until interface is running */
 
1659
    /* Sleep checking until interface is running.
 
1660
       Check every 0.25s, up to total time of delay */
1120
1661
    for(int i=0; i < delay * 4; i++){
1121
1662
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1122
1663
      if(ret == -1){
1123
 
        perror("ioctl SIOCGIFFLAGS");
 
1664
        perror_plus("ioctl SIOCGIFFLAGS");
1124
1665
      } else if(network.ifr_flags & IFF_RUNNING){
1125
1666
        break;
1126
1667
      }
1127
1668
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1128
1669
      ret = nanosleep(&sleeptime, NULL);
1129
1670
      if(ret == -1 and errno != EINTR){
1130
 
        perror("nanosleep");
 
1671
        perror_plus("nanosleep");
1131
1672
      }
1132
1673
    }
1133
 
    if(not interface_taken_up){
 
1674
    if(not take_down_interface){
 
1675
      /* We won't need the socket anymore */
1134
1676
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1135
1677
      if(ret == -1){
1136
 
        perror("close");
 
1678
        perror_plus("close");
1137
1679
      }
1138
1680
    }
1139
1681
#ifdef __linux__
1141
1683
      /* Restores kernel loglevel to default */
1142
1684
      ret = klogctl(7, NULL, 0);
1143
1685
      if(ret == -1){
1144
 
        perror("klogctl");
 
1686
        perror_plus("klogctl");
1145
1687
      }
1146
1688
    }
1147
1689
#endif  /* __linux__ */
1148
 
  }
1149
 
  
1150
 
  uid = getuid();
1151
 
  gid = getgid();
1152
 
  
1153
 
  errno = 0;
1154
 
  setgid(gid);
1155
 
  if(ret == -1){
1156
 
    perror("setgid");
1157
 
  }
1158
 
  
1159
 
  ret = setuid(uid);
1160
 
  if(ret == -1){
1161
 
    perror("setuid");
 
1690
    /* Lower privileges */
 
1691
    errno = 0;
 
1692
    if(take_down_interface){
 
1693
      /* Lower privileges */
 
1694
      ret = seteuid(uid);
 
1695
      if(ret == -1){
 
1696
        perror_plus("seteuid");
 
1697
      }
 
1698
    } else {
 
1699
      /* Lower privileges permanently */
 
1700
      ret = setuid(uid);
 
1701
      if(ret == -1){
 
1702
        perror_plus("setuid");
 
1703
      }
 
1704
    }
 
1705
  }
 
1706
  
 
1707
  if(quit_now){
 
1708
    goto end;
1162
1709
  }
1163
1710
  
1164
1711
  ret = init_gnutls_global(pubkey, seckey);
1165
1712
  if(ret == -1){
1166
1713
    fprintf(stderr, "init_gnutls_global failed\n");
1167
 
    exitcode = EXIT_FAILURE;
 
1714
    exitcode = EX_UNAVAILABLE;
1168
1715
    goto end;
1169
1716
  } else {
1170
1717
    gnutls_initialized = true;
1171
1718
  }
1172
1719
  
 
1720
  if(quit_now){
 
1721
    goto end;
 
1722
  }
 
1723
  
1173
1724
  if(mkdtemp(tempdir) == NULL){
1174
 
    perror("mkdtemp");
 
1725
    perror_plus("mkdtemp");
1175
1726
    goto end;
1176
1727
  }
1177
1728
  tempdir_created = true;
1178
1729
  
 
1730
  if(quit_now){
 
1731
    goto end;
 
1732
  }
 
1733
  
1179
1734
  if(not init_gpgme(pubkey, seckey, tempdir)){
1180
1735
    fprintf(stderr, "init_gpgme failed\n");
1181
 
    exitcode = EXIT_FAILURE;
 
1736
    exitcode = EX_UNAVAILABLE;
1182
1737
    goto end;
1183
1738
  } else {
1184
1739
    gpgme_initialized = true;
1185
1740
  }
1186
1741
  
1187
 
  if(interface[0] != '\0'){
1188
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1189
 
    if(if_index == 0){
1190
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1191
 
      exitcode = EXIT_FAILURE;
1192
 
      goto end;
1193
 
    }
 
1742
  if(quit_now){
 
1743
    goto end;
1194
1744
  }
1195
1745
  
1196
1746
  if(connect_to != NULL){
1199
1749
    char *address = strrchr(connect_to, ':');
1200
1750
    if(address == NULL){
1201
1751
      fprintf(stderr, "No colon in address\n");
1202
 
      exitcode = EXIT_FAILURE;
1203
 
      goto end;
1204
 
    }
 
1752
      exitcode = EX_USAGE;
 
1753
      goto end;
 
1754
    }
 
1755
    
 
1756
    if(quit_now){
 
1757
      goto end;
 
1758
    }
 
1759
    
1205
1760
    uint16_t port;
1206
1761
    errno = 0;
1207
1762
    tmpmax = strtoimax(address+1, &tmp, 10);
1208
1763
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1209
1764
       or tmpmax != (uint16_t)tmpmax){
1210
1765
      fprintf(stderr, "Bad port number\n");
1211
 
      exitcode = EXIT_FAILURE;
1212
 
      goto end;
1213
 
    }
 
1766
      exitcode = EX_USAGE;
 
1767
      goto end;
 
1768
    }
 
1769
  
 
1770
    if(quit_now){
 
1771
      goto end;
 
1772
    }
 
1773
    
1214
1774
    port = (uint16_t)tmpmax;
1215
1775
    *address = '\0';
1216
1776
    address = connect_to;
1221
1781
    } else {
1222
1782
      af = AF_INET;
1223
1783
    }
1224
 
    ret = start_mandos_communication(address, port, if_index, af);
1225
 
    if(ret < 0){
1226
 
      exitcode = EXIT_FAILURE;
1227
 
    } else {
 
1784
    
 
1785
    if(quit_now){
 
1786
      goto end;
 
1787
    }
 
1788
 
 
1789
    while(not quit_now){
 
1790
      ret = start_mandos_communication(address, port, if_index, af);
 
1791
      if(quit_now or ret == 0){
 
1792
        break;
 
1793
      }
 
1794
      sleep((int)retry_interval or 1);
 
1795
    };
 
1796
 
 
1797
    if (not quit_now){
1228
1798
      exitcode = EXIT_SUCCESS;
1229
1799
    }
1230
 
    goto end;
1231
 
  }
1232
 
    
 
1800
 
 
1801
    goto end;
 
1802
  }
 
1803
  
 
1804
  if(quit_now){
 
1805
    goto end;
 
1806
  }
 
1807
  
1233
1808
  {
1234
1809
    AvahiServerConfig config;
1235
1810
    /* Do not publish any local Zeroconf records */
1252
1827
  if(mc.server == NULL){
1253
1828
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1254
1829
            avahi_strerror(error));
1255
 
    exitcode = EXIT_FAILURE;
 
1830
    exitcode = EX_UNAVAILABLE;
 
1831
    goto end;
 
1832
  }
 
1833
  
 
1834
  if(quit_now){
1256
1835
    goto end;
1257
1836
  }
1258
1837
  
1263
1842
  if(sb == NULL){
1264
1843
    fprintf(stderr, "Failed to create service browser: %s\n",
1265
1844
            avahi_strerror(avahi_server_errno(mc.server)));
1266
 
    exitcode = EXIT_FAILURE;
 
1845
    exitcode = EX_UNAVAILABLE;
 
1846
    goto end;
 
1847
  }
 
1848
  
 
1849
  if(quit_now){
1267
1850
    goto end;
1268
1851
  }
1269
1852
  
1272
1855
  if(debug){
1273
1856
    fprintf(stderr, "Starting Avahi loop search\n");
1274
1857
  }
1275
 
  
1276
 
  avahi_simple_poll_loop(mc.simple_poll);
 
1858
 
 
1859
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
1860
                                (int)(retry_interval * 1000));
 
1861
  if(debug){
 
1862
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1863
            (ret == 0) ? "successfully" : "with error");
 
1864
  }
1277
1865
  
1278
1866
 end:
1279
1867
  
1300
1888
  if(gpgme_initialized){
1301
1889
    gpgme_release(mc.ctx);
1302
1890
  }
 
1891
 
 
1892
  /* Cleans up the circular linked list of Mandos servers the client
 
1893
     has seen */
 
1894
  if(mc.current_server != NULL){
 
1895
    mc.current_server->prev->next = NULL;
 
1896
    while(mc.current_server != NULL){
 
1897
      server *next = mc.current_server->next;
 
1898
      free(mc.current_server);
 
1899
      mc.current_server = next;
 
1900
    }
 
1901
  }
1303
1902
  
1304
1903
  /* Take down the network interface */
1305
 
  if(interface_taken_up){
1306
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1904
  if(take_down_interface){
 
1905
    /* Re-raise priviliges */
 
1906
    errno = 0;
 
1907
    ret = seteuid(0);
1307
1908
    if(ret == -1){
1308
 
      perror("ioctl SIOCGIFFLAGS");
1309
 
    } else if(network.ifr_flags & IFF_UP) {
1310
 
      network.ifr_flags &= ~IFF_UP; /* clear flag */
1311
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1312
 
      if(ret == -1){
1313
 
        perror("ioctl SIOCSIFFLAGS");
1314
 
      }
 
1909
      perror_plus("seteuid");
1315
1910
    }
1316
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1317
 
    if(ret == -1){
1318
 
      perror("close");
 
1911
    if(geteuid() == 0){
 
1912
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1913
      if(ret == -1){
 
1914
        perror_plus("ioctl SIOCGIFFLAGS");
 
1915
      } else if(network.ifr_flags & IFF_UP) {
 
1916
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1917
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1918
        if(ret == -1){
 
1919
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1920
        }
 
1921
      }
 
1922
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1923
      if(ret == -1){
 
1924
        perror_plus("close");
 
1925
      }
 
1926
      /* Lower privileges permanently */
 
1927
      errno = 0;
 
1928
      ret = setuid(uid);
 
1929
      if(ret == -1){
 
1930
        perror_plus("setuid");
 
1931
      }
1319
1932
    }
1320
1933
  }
1321
1934
  
1322
 
  /* Removes the temp directory used by GPGME */
 
1935
  /* Removes the GPGME temp directory and all files inside */
1323
1936
  if(tempdir_created){
1324
 
    DIR *d;
1325
 
    struct dirent *direntry;
1326
 
    d = opendir(tempdir);
1327
 
    if(d == NULL){
1328
 
      if(errno != ENOENT){
1329
 
        perror("opendir");
1330
 
      }
1331
 
    } else {
1332
 
      while(true){
1333
 
        direntry = readdir(d);
1334
 
        if(direntry == NULL){
1335
 
          break;
1336
 
        }
1337
 
        /* Skip "." and ".." */
1338
 
        if(direntry->d_name[0] == '.'
1339
 
           and (direntry->d_name[1] == '\0'
1340
 
                or (direntry->d_name[1] == '.'
1341
 
                    and direntry->d_name[2] == '\0'))){
1342
 
          continue;
1343
 
        }
 
1937
    struct dirent **direntries = NULL;
 
1938
    struct dirent *direntry = NULL;
 
1939
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
 
1940
    if (ret > 0){
 
1941
      for(int i = 0; i < ret; i++){
 
1942
        direntry = direntries[i];
1344
1943
        char *fullname = NULL;
1345
1944
        ret = asprintf(&fullname, "%s/%s", tempdir,
1346
1945
                       direntry->d_name);
1347
1946
        if(ret < 0){
1348
 
          perror("asprintf");
 
1947
          perror_plus("asprintf");
1349
1948
          continue;
1350
1949
        }
1351
1950
        ret = remove(fullname);
1355
1954
        }
1356
1955
        free(fullname);
1357
1956
      }
1358
 
      closedir(d);
 
1957
    }
 
1958
 
 
1959
    /* need to be cleaned even if ret == 0 because man page doesn't
 
1960
       specify */
 
1961
    free(direntries);
 
1962
    if (ret == -1){
 
1963
      perror_plus("scandir");
1359
1964
    }
1360
1965
    ret = rmdir(tempdir);
1361
1966
    if(ret == -1 and errno != ENOENT){
1362
 
      perror("rmdir");
1363
 
    }
 
1967
      perror_plus("rmdir");
 
1968
    }
 
1969
  }
 
1970
  
 
1971
  if(quit_now){
 
1972
    sigemptyset(&old_sigterm_action.sa_mask);
 
1973
    old_sigterm_action.sa_handler = SIG_DFL;
 
1974
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
 
1975
                                            &old_sigterm_action,
 
1976
                                            NULL));
 
1977
    if(ret == -1){
 
1978
      perror_plus("sigaction");
 
1979
    }
 
1980
    do {
 
1981
      ret = raise(signal_received);
 
1982
    } while(ret != 0 and errno == EINTR);
 
1983
    if(ret != 0){
 
1984
      perror_plus("raise");
 
1985
      abort();
 
1986
    }
 
1987
    TEMP_FAILURE_RETRY(pause());
1364
1988
  }
1365
1989
  
1366
1990
  return exitcode;