/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2009-09-05 17:39:34 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090905173934-gs0r858omhudc71m
* plugin-runner.c (main): Move variables "tmpmax" and "tmp" into
                          the innermost scope possible.

Show diffs side-by-side

added added

removed removed

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