/mandos/release

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

« back to all changes in this revision

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

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

* initramfs-tools-script: Removed erroneous comment.

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

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

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

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

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008,2009 Teddy Hogeborn
 
13
 * Copyright © 2008,2009 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
43
43
                                   stdout, ferror(), remove() */
44
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
 
                                   strtof(), abort() */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
 
47
                                   srand(), strtof() */
48
48
#include <stdbool.h>            /* bool, false, true */
49
49
#include <string.h>             /* memset(), strcmp(), strlen(),
50
50
                                   strerror(), asprintf(), strcpy() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno,
66
 
                                   program_invocation_short_name */
67
 
#include <time.h>               /* nanosleep(), time(), sleep() */
 
65
#include <errno.h>              /* perror(), errno */
 
66
#include <time.h>               /* nanosleep(), time() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
70
69
                                   if_nametoindex(), IF_NAMESIZE */
73
72
                                */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
75
                                   setgid() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
79
                                   argp_state, struct argp,
83
82
#include <signal.h>             /* sigemptyset(), sigaddset(),
84
83
                                   sigaction(), SIGTERM, sig_atomic_t,
85
84
                                   raise() */
86
 
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
 
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
85
 
89
86
#ifdef __linux__
90
87
#include <sys/klog.h>           /* klogctl() */
123
120
#define PATHDIR "/conf/conf.d/mandos"
124
121
#define SECKEY "seckey.txt"
125
122
#define PUBKEY "pubkey.txt"
126
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
127
123
 
128
124
bool debug = false;
129
125
static const char mandos_protocol_version[] = "1";
130
126
const char *argp_program_version = "mandos-client " VERSION;
131
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
132
 
static const char sys_class_net[] = "/sys/class/net";
133
 
char *connect_to = NULL;
134
 
 
135
 
/* Doubly linked list that need to be circularly linked when used */
136
 
typedef struct server{
137
 
  const char *ip;
138
 
  uint16_t port;
139
 
  AvahiIfIndex if_index;
140
 
  int af;
141
 
  struct timespec last_seen;
142
 
  struct server *next;
143
 
  struct server *prev;
144
 
} server;
 
127
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
145
128
 
146
129
/* Used for passing in values through the Avahi callback functions */
147
130
typedef struct {
152
135
  gnutls_dh_params_t dh_params;
153
136
  const char *priority;
154
137
  gpgme_ctx_t ctx;
155
 
  server *current_server;
156
138
} mandos_context;
157
139
 
158
140
/* global context so signal handler can reach it*/
159
141
mandos_context mc = { .simple_poll = NULL, .server = NULL,
160
142
                      .dh_bits = 1024, .priority = "SECURE256"
161
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
162
 
                      .current_server = NULL };
163
 
 
164
 
sig_atomic_t quit_now = 0;
165
 
int signal_received = 0;
166
 
 
167
 
/* Function to use when printing errors */
168
 
void perror_plus(const char *print_text){
169
 
  fprintf(stderr, "Mandos plugin %s: ",
170
 
          program_invocation_short_name);
171
 
  perror(print_text);
172
 
}
173
 
 
174
 
int fprintf_plus(FILE *stream, const char *format, ...){
175
 
  va_list ap;
176
 
  va_start (ap, format);
177
 
  
178
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", program_invocation_short_name));
179
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
180
 
}
 
143
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
181
144
 
182
145
/*
183
146
 * Make additional room in "buffer" for at least BUFFER_SIZE more
196
159
  return buffer_capacity;
197
160
}
198
161
 
199
 
/* Add server to set of servers to retry periodically */
200
 
int add_server(const char *ip, uint16_t port,
201
 
                 AvahiIfIndex if_index,
202
 
                 int af){
203
 
  int ret;
204
 
  server *new_server = malloc(sizeof(server));
205
 
  if(new_server == NULL){
206
 
    perror_plus("malloc");
207
 
    return -1;
208
 
  }
209
 
  *new_server = (server){ .ip = strdup(ip),
210
 
                         .port = port,
211
 
                         .if_index = if_index,
212
 
                         .af = af };
213
 
  if(new_server->ip == NULL){
214
 
    perror_plus("strdup");
215
 
    return -1;
216
 
  }
217
 
  /* Special case of first server */
218
 
  if (mc.current_server == NULL){
219
 
    new_server->next = new_server;
220
 
    new_server->prev = new_server;
221
 
    mc.current_server = new_server;
222
 
  /* Place the new server last in the list */
223
 
  } else {
224
 
    new_server->next = mc.current_server;
225
 
    new_server->prev = mc.current_server->prev;
226
 
    new_server->prev->next = new_server;
227
 
    mc.current_server->prev = new_server;
228
 
  }
229
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
230
 
  if(ret == -1){
231
 
    perror_plus("clock_gettime");
232
 
    return -1;
233
 
  }
234
 
  return 0;
235
 
}
236
 
 
237
162
/* 
238
163
 * Initialize GPGME.
239
164
 */
253
178
    
254
179
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
255
180
    if(fd == -1){
256
 
      perror_plus("open");
 
181
      perror("open");
257
182
      return false;
258
183
    }
259
184
    
273
198
    
274
199
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
275
200
    if(ret == -1){
276
 
      perror_plus("close");
 
201
      perror("close");
277
202
    }
278
203
    gpgme_data_release(pgp_data);
279
204
    return true;
292
217
    return false;
293
218
  }
294
219
  
295
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
220
    /* Set GPGME home directory for the OpenPGP engine only */
296
221
  rc = gpgme_get_engine_info(&engine_info);
297
222
  if(rc != GPG_ERR_NO_ERROR){
298
223
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
404
329
  
405
330
  /* Seek back to the beginning of the GPGME plaintext data buffer */
406
331
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
407
 
    perror_plus("gpgme_data_seek");
 
332
    perror("gpgme_data_seek");
408
333
    plaintext_length = -1;
409
334
    goto decrypt_end;
410
335
  }
415
340
                                      (size_t)plaintext_length,
416
341
                                      plaintext_capacity);
417
342
    if(plaintext_capacity == 0){
418
 
        perror_plus("incbuffer");
 
343
        perror("incbuffer");
419
344
        plaintext_length = -1;
420
345
        goto decrypt_end;
421
346
    }
428
353
      break;
429
354
    }
430
355
    if(ret < 0){
431
 
      perror_plus("gpgme_data_read");
 
356
      perror("gpgme_data_read");
432
357
      plaintext_length = -1;
433
358
      goto decrypt_end;
434
359
    }
491
416
  }
492
417
  
493
418
  /* OpenPGP credentials */
494
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
419
  gnutls_certificate_allocate_credentials(&mc.cred);
495
420
  if(ret != GNUTLS_E_SUCCESS){
496
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
421
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
422
                                                    from
 
423
                                                    -Wunreachable-code
 
424
                                                 */
497
425
            safer_gnutls_strerror(ret));
498
426
    gnutls_global_deinit();
499
427
    return -1;
548
476
  /* GnuTLS session creation */
549
477
  do {
550
478
    ret = gnutls_init(session, GNUTLS_SERVER);
551
 
    if(quit_now){
552
 
      return -1;
553
 
    }
554
479
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
555
480
  if(ret != GNUTLS_E_SUCCESS){
556
481
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
561
486
    const char *err;
562
487
    do {
563
488
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
564
 
      if(quit_now){
565
 
        gnutls_deinit(*session);
566
 
        return -1;
567
 
      }
568
489
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
569
490
    if(ret != GNUTLS_E_SUCCESS){
570
491
      fprintf(stderr, "Syntax error at: %s\n", err);
578
499
  do {
579
500
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
580
501
                                 mc.cred);
581
 
    if(quit_now){
582
 
      gnutls_deinit(*session);
583
 
      return -1;
584
 
    }
585
502
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
586
503
  if(ret != GNUTLS_E_SUCCESS){
587
504
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
602
519
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
603
520
                      __attribute__((unused)) const char *txt){}
604
521
 
 
522
sig_atomic_t quit_now = 0;
 
523
int signal_received = 0;
 
524
 
605
525
/* Called when a Mandos server is found */
606
526
static int start_mandos_communication(const char *ip, uint16_t port,
607
527
                                      AvahiIfIndex if_index,
613
533
    struct sockaddr_in6 in6;
614
534
  } to;
615
535
  char *buffer = NULL;
616
 
  char *decrypted_buffer = NULL;
 
536
  char *decrypted_buffer;
617
537
  size_t buffer_length = 0;
618
538
  size_t buffer_capacity = 0;
619
539
  size_t written;
620
 
  int retval = -1;
 
540
  int retval = 0;
621
541
  gnutls_session_t session;
622
542
  int pf;                       /* Protocol family */
623
543
  
624
 
  errno = 0;
625
 
  
626
544
  if(quit_now){
627
 
    errno = EINTR;
628
545
    return -1;
629
546
  }
630
547
  
637
554
    break;
638
555
  default:
639
556
    fprintf(stderr, "Bad address family: %d\n", af);
640
 
    errno = EINVAL;
641
557
    return -1;
642
558
  }
643
559
  
653
569
  
654
570
  tcp_sd = socket(pf, SOCK_STREAM, 0);
655
571
  if(tcp_sd < 0){
656
 
    int e = errno;
657
 
    perror_plus("socket");
658
 
    errno = e;
 
572
    perror("socket");
 
573
    retval = -1;
659
574
    goto mandos_end;
660
575
  }
661
576
  
662
577
  if(quit_now){
663
 
    errno = EINTR;
664
578
    goto mandos_end;
665
579
  }
666
580
  
673
587
    ret = inet_pton(af, ip, &to.in.sin_addr);
674
588
  }
675
589
  if(ret < 0 ){
676
 
    int e = errno;
677
 
    perror_plus("inet_pton");
678
 
    errno = e;
 
590
    perror("inet_pton");
 
591
    retval = -1;
679
592
    goto mandos_end;
680
593
  }
681
594
  if(ret == 0){
682
 
    int e = errno;
683
595
    fprintf(stderr, "Bad address: %s\n", ip);
684
 
    errno = e;
 
596
    retval = -1;
685
597
    goto mandos_end;
686
598
  }
687
599
  if(af == AF_INET6){
695
607
      if(if_index == AVAHI_IF_UNSPEC){
696
608
        fprintf(stderr, "An IPv6 link-local address is incomplete"
697
609
                " without a network interface\n");
698
 
        errno = EINVAL;
 
610
        retval = -1;
699
611
        goto mandos_end;
700
612
      }
701
613
      /* Set the network interface number as scope */
708
620
  }
709
621
  
710
622
  if(quit_now){
711
 
    errno = EINTR;
712
623
    goto mandos_end;
713
624
  }
714
625
  
716
627
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
717
628
      char interface[IF_NAMESIZE];
718
629
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
719
 
        perror_plus("if_indextoname");
 
630
        perror("if_indextoname");
720
631
      } else {
721
632
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
722
633
                ip, interface, port);
736
647
                        sizeof(addrstr));
737
648
    }
738
649
    if(pcret == NULL){
739
 
      perror_plus("inet_ntop");
 
650
      perror("inet_ntop");
740
651
    } else {
741
652
      if(strcmp(addrstr, ip) != 0){
742
653
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
745
656
  }
746
657
  
747
658
  if(quit_now){
748
 
    errno = EINTR;
749
659
    goto mandos_end;
750
660
  }
751
661
  
755
665
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
756
666
  }
757
667
  if(ret < 0){
758
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
759
 
      int e = errno;
760
 
      perror_plus("connect");
761
 
      errno = e;
762
 
    }
 
668
    perror("connect");
 
669
    retval = -1;
763
670
    goto mandos_end;
764
671
  }
765
672
  
766
673
  if(quit_now){
767
 
    errno = EINTR;
768
674
    goto mandos_end;
769
675
  }
770
676
  
775
681
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
776
682
                                   out_size - written));
777
683
    if(ret == -1){
778
 
      int e = errno;
779
 
      perror_plus("write");
780
 
      errno = e;
 
684
      perror("write");
 
685
      retval = -1;
781
686
      goto mandos_end;
782
687
    }
783
688
    written += (size_t)ret;
793
698
    }
794
699
  
795
700
    if(quit_now){
796
 
      errno = EINTR;
797
701
      goto mandos_end;
798
702
    }
799
703
  }
803
707
  }
804
708
  
805
709
  if(quit_now){
806
 
    errno = EINTR;
807
710
    goto mandos_end;
808
711
  }
809
712
  
810
 
  /* Spurious warning from -Wint-to-pointer-cast */
811
713
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
812
714
  
813
715
  if(quit_now){
814
 
    errno = EINTR;
815
716
    goto mandos_end;
816
717
  }
817
718
  
818
719
  do {
819
720
    ret = gnutls_handshake(session);
820
721
    if(quit_now){
821
 
      errno = EINTR;
822
722
      goto mandos_end;
823
723
    }
824
724
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
828
728
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
829
729
      gnutls_perror(ret);
830
730
    }
831
 
    errno = EPROTO;
 
731
    retval = -1;
832
732
    goto mandos_end;
833
733
  }
834
734
  
842
742
  while(true){
843
743
    
844
744
    if(quit_now){
845
 
      errno = EINTR;
846
745
      goto mandos_end;
847
746
    }
848
747
    
849
748
    buffer_capacity = incbuffer(&buffer, buffer_length,
850
749
                                   buffer_capacity);
851
750
    if(buffer_capacity == 0){
852
 
      int e = errno;
853
 
      perror_plus("incbuffer");
854
 
      errno = e;
 
751
      perror("incbuffer");
 
752
      retval = -1;
855
753
      goto mandos_end;
856
754
    }
857
755
    
858
756
    if(quit_now){
859
 
      errno = EINTR;
860
757
      goto mandos_end;
861
758
    }
862
759
    
875
772
          ret = gnutls_handshake(session);
876
773
          
877
774
          if(quit_now){
878
 
            errno = EINTR;
879
775
            goto mandos_end;
880
776
          }
881
777
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
882
778
        if(ret < 0){
883
779
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
884
780
          gnutls_perror(ret);
885
 
          errno = EPROTO;
 
781
          retval = -1;
886
782
          goto mandos_end;
887
783
        }
888
784
        break;
889
785
      default:
890
786
        fprintf(stderr, "Unknown error while reading data from"
891
787
                " encrypted session with Mandos server\n");
 
788
        retval = -1;
892
789
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
893
 
        errno = EIO;
894
790
        goto mandos_end;
895
791
      }
896
792
    } else {
903
799
  }
904
800
  
905
801
  if(quit_now){
906
 
    errno = EINTR;
907
 
    goto mandos_end;
908
 
  }
909
 
  
910
 
  do {
911
 
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
912
 
    if(quit_now){
913
 
      errno = EINTR;
914
 
      goto mandos_end;
915
 
    }
916
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
 
802
    goto mandos_end;
 
803
  }
 
804
  
 
805
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
806
  
 
807
  if(quit_now){
 
808
    goto mandos_end;
 
809
  }
917
810
  
918
811
  if(buffer_length > 0){
919
812
    ssize_t decrypted_buffer_size;
925
818
      written = 0;
926
819
      while(written < (size_t) decrypted_buffer_size){
927
820
        if(quit_now){
928
 
          errno = EINTR;
929
821
          goto mandos_end;
930
822
        }
931
823
        
933
825
                          (size_t)decrypted_buffer_size - written,
934
826
                          stdout);
935
827
        if(ret == 0 and ferror(stdout)){
936
 
          int e = errno;
937
828
          if(debug){
938
829
            fprintf(stderr, "Error writing encrypted data: %s\n",
939
830
                    strerror(errno));
940
831
          }
941
 
          errno = e;
942
 
          goto mandos_end;
 
832
          retval = -1;
 
833
          break;
943
834
        }
944
835
        written += (size_t)ret;
945
836
      }
946
 
      retval = 0;
 
837
      free(decrypted_buffer);
 
838
    } else {
 
839
      retval = -1;
947
840
    }
 
841
  } else {
 
842
    retval = -1;
948
843
  }
949
844
  
950
845
  /* Shutdown procedure */
951
846
  
952
847
 mandos_end:
953
 
  {
954
 
    int e = errno;
955
 
    free(decrypted_buffer);
956
 
    free(buffer);
957
 
    if(tcp_sd >= 0){
958
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
959
 
    }
960
 
    if(ret == -1){
961
 
      if(e == 0){
962
 
        e = errno;
963
 
      }
964
 
      perror_plus("close");
965
 
    }
966
 
    gnutls_deinit(session);
967
 
    errno = e;
968
 
    if(quit_now){
969
 
      errno = EINTR;
970
 
      retval = -1;
971
 
    }
 
848
  free(buffer);
 
849
  if(tcp_sd >= 0){
 
850
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
851
  }
 
852
  if(ret == -1){
 
853
    perror("close");
 
854
  }
 
855
  gnutls_deinit(session);
 
856
  if(quit_now){
 
857
    retval = -1;
972
858
  }
973
859
  return retval;
974
860
}
1017
903
                                           avahi_proto_to_af(proto));
1018
904
      if(ret == 0){
1019
905
        avahi_simple_poll_quit(mc.simple_poll);
1020
 
      } else {
1021
 
        ret = add_server(ip, port, interface,
1022
 
                         avahi_proto_to_af(proto));
1023
906
      }
1024
907
    }
1025
908
  }
1079
962
  }
1080
963
}
1081
964
 
1082
 
/* Signal handler that stops main loop after SIGTERM */
 
965
/* stop main loop after sigterm has been called */
1083
966
static void handle_sigterm(int sig){
1084
967
  if(quit_now){
1085
968
    return;
1087
970
  quit_now = 1;
1088
971
  signal_received = sig;
1089
972
  int old_errno = errno;
1090
 
  /* set main loop to exit */
1091
973
  if(mc.simple_poll != NULL){
1092
974
    avahi_simple_poll_quit(mc.simple_poll);
1093
975
  }
1094
976
  errno = old_errno;
1095
977
}
1096
978
 
1097
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1098
 
  int ret;
1099
 
  
1100
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1101
 
  if(s < 0){
1102
 
    perror_plus("socket");
1103
 
    return false;
1104
 
  }
1105
 
  strcpy(ifr->ifr_name, ifname);
1106
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1107
 
  if(ret == -1){
1108
 
    if(debug){
1109
 
      perror_plus("ioctl SIOCGIFFLAGS");
1110
 
    }
1111
 
    return false;
1112
 
  }
1113
 
  return true;
1114
 
}
1115
 
 
1116
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1117
 
  
1118
 
  /* Reject the loopback device */
1119
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
1120
 
    if(debug){
1121
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1122
 
              ifname);
1123
 
    }
1124
 
    return false;
1125
 
  }
1126
 
  /* Accept point-to-point devices only if connect_to is specified */
1127
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1128
 
    if(debug){
1129
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1130
 
              ifname);
1131
 
    }
1132
 
    return true;
1133
 
  }
1134
 
  /* Otherwise, reject non-broadcast-capable devices */
1135
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1136
 
    if(debug){
1137
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1138
 
              ifname);
1139
 
    }
1140
 
    return false;
1141
 
  }
1142
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1143
 
  if(ifr->ifr_flags & IFF_NOARP){
1144
 
    if(debug){
1145
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
1146
 
    }
1147
 
    return false;
1148
 
  }
1149
 
  
1150
 
  /* Accept this device */
1151
 
  if(debug){
1152
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
1153
 
  }
1154
 
  return true;
1155
 
}
1156
 
 
1157
 
/* 
1158
 
 * This function determines if a directory entry in /sys/class/net
1159
 
 * corresponds to an acceptable network device.
1160
 
 * (This function is passed to scandir(3) as a filter function.)
1161
 
 */
1162
 
int good_interface(const struct dirent *if_entry){
1163
 
  int ret;
1164
 
  if(if_entry->d_name[0] == '.'){
1165
 
    return 0;
1166
 
  }
1167
 
  struct ifreq ifr;
1168
 
 
1169
 
  if(not get_flags(if_entry->d_name, &ifr)){
1170
 
    return 0;
1171
 
  }
1172
 
  
1173
 
  if(not good_flags(if_entry->d_name, &ifr)){
1174
 
    return 0;
1175
 
  }
1176
 
  return 1;
1177
 
}
1178
 
 
1179
 
/* 
1180
 
 * This function determines if a directory entry in /sys/class/net
1181
 
 * corresponds to an acceptable network device which is up.
1182
 
 * (This function is passed to scandir(3) as a filter function.)
1183
 
 */
1184
 
int up_interface(const struct dirent *if_entry){
1185
 
  ssize_t ssret;
1186
 
  char *flagname = NULL;
1187
 
  if(if_entry->d_name[0] == '.'){
1188
 
    return 0;
1189
 
  }
1190
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1191
 
                     if_entry->d_name);
1192
 
  if(ret < 0){
1193
 
    perror_plus("asprintf");
1194
 
    return 0;
1195
 
  }
1196
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1197
 
  if(flags_fd == -1){
1198
 
    perror_plus("open");
1199
 
    free(flagname);
1200
 
    return 0;
1201
 
  }
1202
 
  free(flagname);
1203
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1204
 
  /* read line from flags_fd */
1205
 
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
1206
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1207
 
  flagstring[(size_t)to_read] = '\0';
1208
 
  if(flagstring == NULL){
1209
 
    perror_plus("malloc");
1210
 
    close(flags_fd);
1211
 
    return 0;
1212
 
  }
1213
 
  while(to_read > 0){
1214
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1215
 
                                             (size_t)to_read));
1216
 
    if(ssret == -1){
1217
 
      perror_plus("read");
1218
 
      free(flagstring);
1219
 
      close(flags_fd);
1220
 
      return 0;
1221
 
    }
1222
 
    to_read -= ssret;
1223
 
    if(ssret == 0){
1224
 
      break;
1225
 
    }
1226
 
  }
1227
 
  close(flags_fd);
1228
 
  intmax_t tmpmax;
1229
 
  char *tmp;
1230
 
  errno = 0;
1231
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1232
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1233
 
                                         and not (isspace(*tmp)))
1234
 
     or tmpmax != (ifreq_flags)tmpmax){
1235
 
    if(debug){
1236
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1237
 
              flagstring, if_entry->d_name);
1238
 
    }
1239
 
    free(flagstring);
1240
 
    return 0;
1241
 
  }
1242
 
  free(flagstring);
1243
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
1244
 
  /* Reject the loopback device */
1245
 
  if(flags & IFF_LOOPBACK){
1246
 
    if(debug){
1247
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1248
 
              if_entry->d_name);
1249
 
    }
1250
 
    return 0;
1251
 
  }
1252
 
 
1253
 
  /* Reject down interfaces */
1254
 
  if(not (flags & IFF_UP)){
1255
 
    return 0;
1256
 
  }
1257
 
  
1258
 
  /* Accept point-to-point devices only if connect_to is specified */
1259
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1260
 
    if(debug){
1261
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1262
 
              if_entry->d_name);
1263
 
    }
1264
 
    return 1;
1265
 
  }
1266
 
  /* Otherwise, reject non-broadcast-capable devices */
1267
 
  if(not (flags & IFF_BROADCAST)){
1268
 
    if(debug){
1269
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1270
 
              if_entry->d_name);
1271
 
    }
1272
 
    return 0;
1273
 
  }
1274
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1275
 
  if(flags & IFF_NOARP){
1276
 
    if(debug){
1277
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1278
 
              if_entry->d_name);
1279
 
    }
1280
 
    return 0;
1281
 
  }
1282
 
  /* Accept this device */
1283
 
  if(debug){
1284
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1285
 
            if_entry->d_name);
1286
 
  }
1287
 
  return 1;
1288
 
}
1289
 
 
1290
 
int notdotentries(const struct dirent *direntry){
1291
 
  /* Skip "." and ".." */
1292
 
  if(direntry->d_name[0] == '.'
1293
 
     and (direntry->d_name[1] == '\0'
1294
 
          or (direntry->d_name[1] == '.'
1295
 
              and direntry->d_name[2] == '\0'))){
1296
 
    return 0;
1297
 
  }
1298
 
  return 1;
1299
 
}
1300
 
 
1301
 
/* Is this directory entry a runnable program? */
1302
 
int runnable_hook(const struct dirent *direntry){
1303
 
  int ret;
1304
 
  struct stat st;
1305
 
  
1306
 
  if((direntry->d_name)[0] == '\0'){
1307
 
    /* Empty name? */
1308
 
    return 0;
1309
 
  }
1310
 
  
1311
 
  /* Save pointer to last character */
1312
 
  char *end = strchr(direntry->d_name, '\0')-1;
1313
 
  
1314
 
  if(*end == '~'){
1315
 
    /* Backup name~ */
1316
 
    return 0;
1317
 
  }
1318
 
  
1319
 
  if(((direntry->d_name)[0] == '#')
1320
 
     and (*end == '#')){
1321
 
    /* Temporary #name# */
1322
 
    return 0;
1323
 
  }
1324
 
  
1325
 
  /* XXX more rules here */
1326
 
  
1327
 
  ret = stat(direntry->d_name, &st);
1328
 
  if(ret == -1){
1329
 
    if(debug){
1330
 
      perror_plus("Could not stat plugin");
1331
 
    }
1332
 
    return 0;
1333
 
  }
1334
 
  if(not (st.st_mode & S_ISREG)){
1335
 
    /* Not a regular file */
1336
 
    return 0;
1337
 
  }
1338
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1339
 
    /* Not executable */
1340
 
    return 0;
1341
 
  }
1342
 
  return 1;
1343
 
}
1344
 
 
1345
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1346
 
  int ret;
1347
 
  struct timespec now;
1348
 
  struct timespec waited_time;
1349
 
  intmax_t block_time;
1350
 
  
1351
 
  while(true){
1352
 
    if(mc.current_server == NULL){
1353
 
      if (debug){
1354
 
        fprintf(stderr,
1355
 
                "Wait until first server is found. No timeout!\n");
1356
 
      }
1357
 
      ret = avahi_simple_poll_iterate(s, -1);
1358
 
    } else {
1359
 
      if (debug){
1360
 
        fprintf(stderr, "Check current_server if we should run it,"
1361
 
                " or wait\n");
1362
 
      }
1363
 
      /* the current time */
1364
 
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1365
 
      if(ret == -1){
1366
 
        perror_plus("clock_gettime");
1367
 
        return -1;
1368
 
      }
1369
 
      /* Calculating in ms how long time between now and server
1370
 
         who we visted longest time ago. Now - last seen.  */
1371
 
      waited_time.tv_sec = (now.tv_sec
1372
 
                            - mc.current_server->last_seen.tv_sec);
1373
 
      waited_time.tv_nsec = (now.tv_nsec
1374
 
                             - mc.current_server->last_seen.tv_nsec);
1375
 
      /* total time is 10s/10,000ms.
1376
 
         Converting to s from ms by dividing by 1,000,
1377
 
         and ns to ms by dividing by 1,000,000. */
1378
 
      block_time = ((retry_interval
1379
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1380
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1381
 
      
1382
 
      if (debug){
1383
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1384
 
      }
1385
 
      
1386
 
      if(block_time <= 0){
1387
 
        ret = start_mandos_communication(mc.current_server->ip,
1388
 
                                         mc.current_server->port,
1389
 
                                         mc.current_server->if_index,
1390
 
                                         mc.current_server->af);
1391
 
        if(ret == 0){
1392
 
          avahi_simple_poll_quit(mc.simple_poll);
1393
 
          return 0;
1394
 
        }
1395
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1396
 
                            &mc.current_server->last_seen);
1397
 
        if(ret == -1){
1398
 
          perror_plus("clock_gettime");
1399
 
          return -1;
1400
 
        }
1401
 
        mc.current_server = mc.current_server->next;
1402
 
        block_time = 0;         /* Call avahi to find new Mandos
1403
 
                                   servers, but don't block */
1404
 
      }
1405
 
      
1406
 
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1407
 
    }
1408
 
    if(ret != 0){
1409
 
      if (ret > 0 or errno != EINTR) {
1410
 
        return (ret != 1) ? ret : 0;
1411
 
      }
1412
 
    }
1413
 
  }
1414
 
}
1415
 
 
1416
979
int main(int argc, char *argv[]){
1417
980
  AvahiSServiceBrowser *sb = NULL;
1418
981
  int error;
1420
983
  intmax_t tmpmax;
1421
984
  char *tmp;
1422
985
  int exitcode = EXIT_SUCCESS;
1423
 
  const char *interface = "";
 
986
  const char *interface = "eth0";
1424
987
  struct ifreq network;
1425
988
  int sd = -1;
1426
989
  bool take_down_interface = false;
1427
990
  uid_t uid;
1428
991
  gid_t gid;
 
992
  char *connect_to = NULL;
1429
993
  char tempdir[] = "/tmp/mandosXXXXXX";
1430
994
  bool tempdir_created = false;
1431
995
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1435
999
  bool gnutls_initialized = false;
1436
1000
  bool gpgme_initialized = false;
1437
1001
  float delay = 2.5f;
1438
 
  double retry_interval = 10; /* 10s between trying a server and
1439
 
                                 retrying the same server again */
1440
1002
  
1441
1003
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1442
1004
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1448
1010
  errno = 0;
1449
1011
  ret = setgid(gid);
1450
1012
  if(ret == -1){
1451
 
    perror_plus("setgid");
 
1013
    perror("setgid");
1452
1014
  }
1453
1015
  
1454
1016
  /* Lower user privileges (temporarily) */
1455
1017
  errno = 0;
1456
1018
  ret = seteuid(uid);
1457
1019
  if(ret == -1){
1458
 
    perror_plus("seteuid");
 
1020
    perror("seteuid");
1459
1021
  }
1460
1022
  
1461
1023
  if(quit_now){
1496
1058
        .arg = "SECONDS",
1497
1059
        .doc = "Maximum delay to wait for interface startup",
1498
1060
        .group = 2 },
1499
 
      { .name = "retry", .key = 132,
1500
 
        .arg = "SECONDS",
1501
 
        .doc = "Retry interval used when denied by the mandos server",
1502
 
        .group = 2 },
1503
 
      /*
1504
 
       * These reproduce what we would get without ARGP_NO_HELP
1505
 
       */
1506
 
      { .name = "help", .key = '?',
1507
 
        .doc = "Give this help list", .group = -1 },
1508
 
      { .name = "usage", .key = -3,
1509
 
        .doc = "Give a short usage message", .group = -1 },
1510
 
      { .name = "version", .key = 'V',
1511
 
        .doc = "Print program version", .group = -1 },
1512
1061
      { .name = NULL }
1513
1062
    };
1514
1063
    
1515
1064
    error_t parse_opt(int key, char *arg,
1516
1065
                      struct argp_state *state){
1517
 
      errno = 0;
1518
1066
      switch(key){
1519
1067
      case 128:                 /* --debug */
1520
1068
        debug = true;
1536
1084
        tmpmax = strtoimax(arg, &tmp, 10);
1537
1085
        if(errno != 0 or tmp == arg or *tmp != '\0'
1538
1086
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1539
 
          argp_error(state, "Bad number of DH bits");
 
1087
          fprintf(stderr, "Bad number of DH bits\n");
 
1088
          exit(EXIT_FAILURE);
1540
1089
        }
1541
1090
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1542
1091
        break;
1547
1096
        errno = 0;
1548
1097
        delay = strtof(arg, &tmp);
1549
1098
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1550
 
          argp_error(state, "Bad delay");
1551
 
        }
1552
 
      case 132:                 /* --retry */
1553
 
        errno = 0;
1554
 
        retry_interval = strtod(arg, &tmp);
1555
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1556
 
           or (retry_interval * 1000) > INT_MAX
1557
 
           or retry_interval < 0){
1558
 
          argp_error(state, "Bad retry interval");
 
1099
          fprintf(stderr, "Bad delay\n");
 
1100
          exit(EXIT_FAILURE);
1559
1101
        }
1560
1102
        break;
1561
 
        /*
1562
 
         * These reproduce what we would get without ARGP_NO_HELP
1563
 
         */
1564
 
      case '?':                 /* --help */
1565
 
        argp_state_help(state, state->out_stream,
1566
 
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1567
 
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
1568
 
      case -3:                  /* --usage */
1569
 
        argp_state_help(state, state->out_stream,
1570
 
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1571
 
      case 'V':                 /* --version */
1572
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
1573
 
        exit(argp_err_exit_status);
 
1103
      case ARGP_KEY_ARG:
 
1104
        argp_usage(state);
 
1105
      case ARGP_KEY_END:
1574
1106
        break;
1575
1107
      default:
1576
1108
        return ARGP_ERR_UNKNOWN;
1577
1109
      }
1578
 
      return errno;
 
1110
      return 0;
1579
1111
    }
1580
1112
    
1581
1113
    struct argp argp = { .options = options, .parser = parse_opt,
1582
1114
                         .args_doc = "",
1583
1115
                         .doc = "Mandos client -- Get and decrypt"
1584
1116
                         " passwords from a Mandos server" };
1585
 
    ret = argp_parse(&argp, argc, argv,
1586
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1587
 
    switch(ret){
1588
 
    case 0:
1589
 
      break;
1590
 
    case ENOMEM:
1591
 
    default:
1592
 
      errno = ret;
1593
 
      perror_plus("argp_parse");
1594
 
      exitcode = EX_OSERR;
1595
 
      goto end;
1596
 
    case EINVAL:
1597
 
      exitcode = EX_USAGE;
1598
 
      goto end;
1599
 
    }
1600
 
  }
1601
 
    
1602
 
  {
1603
 
    /* Work around Debian bug #633582:
1604
 
       <http://bugs.debian.org/633582> */
1605
 
    struct stat st;
1606
 
    
1607
 
    /* Re-raise priviliges */
1608
 
    errno = 0;
1609
 
    ret = seteuid(0);
1610
 
    if(ret == -1){
1611
 
      perror_plus("seteuid");
1612
 
    }
1613
 
    
1614
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1615
 
      int seckey_fd = open(seckey, O_RDONLY);
1616
 
      if(seckey_fd == -1){
1617
 
        perror_plus("open");
1618
 
      } else {
1619
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1620
 
        if(ret == -1){
1621
 
          perror_plus("fstat");
1622
 
        } else {
1623
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1624
 
            ret = fchown(seckey_fd, uid, gid);
1625
 
            if(ret == -1){
1626
 
              perror_plus("fchown");
1627
 
            }
1628
 
          }
1629
 
        }
1630
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1631
 
      }
1632
 
    }
1633
 
    
1634
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1635
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1636
 
      if(pubkey_fd == -1){
1637
 
        perror_plus("open");
1638
 
      } else {
1639
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1640
 
        if(ret == -1){
1641
 
          perror_plus("fstat");
1642
 
        } else {
1643
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1644
 
            ret = fchown(pubkey_fd, uid, gid);
1645
 
            if(ret == -1){
1646
 
              perror_plus("fchown");
1647
 
            }
1648
 
          }
1649
 
        }
1650
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1651
 
      }
1652
 
    }
1653
 
    
1654
 
    /* Lower privileges */
1655
 
    errno = 0;
1656
 
    ret = seteuid(uid);
1657
 
    if(ret == -1){
1658
 
      perror_plus("seteuid");
1659
 
    }
1660
 
  }
1661
 
  
1662
 
  /* Find network hooks and run them */
1663
 
  {
1664
 
    struct dirent **direntries;
1665
 
    struct dirent *direntry;
1666
 
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
1667
 
                           alphasort);
1668
 
    int devnull = open("/dev/null", O_RDONLY);
1669
 
    for(int i = 0; i < numhooks; i++){
1670
 
      direntry = direntries[0];
1671
 
      char *fullname = NULL;
1672
 
      ret = asprintf(&fullname, "%s/%s", tempdir,
1673
 
                     direntry->d_name);
1674
 
      if(ret < 0){
1675
 
        perror_plus("asprintf");
1676
 
        continue;
1677
 
      }
1678
 
      pid_t hook_pid = fork();
1679
 
      if(hook_pid == 0){
1680
 
        /* Child */
1681
 
        dup2(devnull, STDIN_FILENO);
1682
 
        close(devnull);
1683
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1684
 
        setenv("DEVICE", interface, 1);
1685
 
        setenv("VERBOSE", debug ? "1" : "0", 1);
1686
 
        setenv("MODE", "start", 1);
1687
 
        /* setenv( XXX more here */
1688
 
        ret = execl(fullname, direntry->d_name, "start");
1689
 
        perror_plus("execl");
1690
 
      }
1691
 
      free(fullname);
1692
 
      if(quit_now){
1693
 
        goto end;
1694
 
      }
1695
 
    }
1696
 
    close(devnull);
 
1117
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
1118
    if(ret == ARGP_ERR_UNKNOWN){
 
1119
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1120
      exitcode = EXIT_FAILURE;
 
1121
      goto end;
 
1122
    }
1697
1123
  }
1698
1124
  
1699
1125
  if(not debug){
1700
1126
    avahi_set_log_function(empty_log);
1701
1127
  }
1702
1128
  
1703
 
  if(interface[0] == '\0'){
1704
 
    struct dirent **direntries;
1705
 
    ret = scandir(sys_class_net, &direntries, good_interface,
1706
 
                  alphasort);
1707
 
    if(ret >= 1){
1708
 
      /* Pick the first good interface */
1709
 
      interface = strdup(direntries[0]->d_name);
1710
 
      if(debug){
1711
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1712
 
      }
1713
 
      if(interface == NULL){
1714
 
        perror_plus("malloc");
1715
 
        free(direntries);
1716
 
        exitcode = EXIT_FAILURE;
1717
 
        goto end;
1718
 
      }
1719
 
      free(direntries);
1720
 
    } else {
1721
 
      free(direntries);
1722
 
      fprintf(stderr, "Could not find a network interface\n");
1723
 
      exitcode = EXIT_FAILURE;
1724
 
      goto end;
1725
 
    }
1726
 
  }
1727
 
  
1728
1129
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1729
1130
     from the signal handler */
1730
1131
  /* Initialize the pseudo-RNG for Avahi */
1732
1133
  mc.simple_poll = avahi_simple_poll_new();
1733
1134
  if(mc.simple_poll == NULL){
1734
1135
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1735
 
    exitcode = EX_UNAVAILABLE;
 
1136
    exitcode = EXIT_FAILURE;
1736
1137
    goto end;
1737
1138
  }
1738
1139
  
1739
1140
  sigemptyset(&sigterm_action.sa_mask);
1740
1141
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1741
1142
  if(ret == -1){
1742
 
    perror_plus("sigaddset");
1743
 
    exitcode = EX_OSERR;
 
1143
    perror("sigaddset");
 
1144
    exitcode = EXIT_FAILURE;
1744
1145
    goto end;
1745
1146
  }
1746
1147
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1747
1148
  if(ret == -1){
1748
 
    perror_plus("sigaddset");
1749
 
    exitcode = EX_OSERR;
 
1149
    perror("sigaddset");
 
1150
    exitcode = EXIT_FAILURE;
1750
1151
    goto end;
1751
1152
  }
1752
1153
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1753
1154
  if(ret == -1){
1754
 
    perror_plus("sigaddset");
1755
 
    exitcode = EX_OSERR;
 
1155
    perror("sigaddset");
 
1156
    exitcode = EXIT_FAILURE;
1756
1157
    goto end;
1757
1158
  }
1758
1159
  /* Need to check if the handler is SIG_IGN before handling:
1761
1162
  */
1762
1163
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1763
1164
  if(ret == -1){
1764
 
    perror_plus("sigaction");
1765
 
    return EX_OSERR;
 
1165
    perror("sigaction");
 
1166
    return EXIT_FAILURE;
1766
1167
  }
1767
1168
  if(old_sigterm_action.sa_handler != SIG_IGN){
1768
1169
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1769
1170
    if(ret == -1){
1770
 
      perror_plus("sigaction");
1771
 
      exitcode = EX_OSERR;
 
1171
      perror("sigaction");
 
1172
      exitcode = EXIT_FAILURE;
1772
1173
      goto end;
1773
1174
    }
1774
1175
  }
1775
1176
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1776
1177
  if(ret == -1){
1777
 
    perror_plus("sigaction");
1778
 
    return EX_OSERR;
 
1178
    perror("sigaction");
 
1179
    return EXIT_FAILURE;
1779
1180
  }
1780
1181
  if(old_sigterm_action.sa_handler != SIG_IGN){
1781
1182
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1782
1183
    if(ret == -1){
1783
 
      perror_plus("sigaction");
1784
 
      exitcode = EX_OSERR;
 
1184
      perror("sigaction");
 
1185
      exitcode = EXIT_FAILURE;
1785
1186
      goto end;
1786
1187
    }
1787
1188
  }
1788
1189
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1789
1190
  if(ret == -1){
1790
 
    perror_plus("sigaction");
1791
 
    return EX_OSERR;
 
1191
    perror("sigaction");
 
1192
    return EXIT_FAILURE;
1792
1193
  }
1793
1194
  if(old_sigterm_action.sa_handler != SIG_IGN){
1794
1195
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1795
1196
    if(ret == -1){
1796
 
      perror_plus("sigaction");
1797
 
      exitcode = EX_OSERR;
 
1197
      perror("sigaction");
 
1198
      exitcode = EXIT_FAILURE;
1798
1199
      goto end;
1799
1200
    }
1800
1201
  }
1801
1202
  
1802
1203
  /* If the interface is down, bring it up */
1803
 
  if(strcmp(interface, "none") != 0){
 
1204
  if(interface[0] != '\0'){
1804
1205
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1805
1206
    if(if_index == 0){
1806
1207
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1807
 
      exitcode = EX_UNAVAILABLE;
 
1208
      exitcode = EXIT_FAILURE;
1808
1209
      goto end;
1809
1210
    }
1810
1211
    
1816
1217
    errno = 0;
1817
1218
    ret = seteuid(0);
1818
1219
    if(ret == -1){
1819
 
      perror_plus("seteuid");
 
1220
      perror("seteuid");
1820
1221
    }
1821
1222
    
1822
1223
#ifdef __linux__
1823
1224
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1824
 
       messages about the network interface to mess up the prompt */
 
1225
       messages to mess up the prompt */
1825
1226
    ret = klogctl(8, NULL, 5);
1826
1227
    bool restore_loglevel = true;
1827
1228
    if(ret == -1){
1828
1229
      restore_loglevel = false;
1829
 
      perror_plus("klogctl");
 
1230
      perror("klogctl");
1830
1231
    }
1831
1232
#endif  /* __linux__ */
1832
1233
    
1833
1234
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1834
1235
    if(sd < 0){
1835
 
      perror_plus("socket");
1836
 
      exitcode = EX_OSERR;
 
1236
      perror("socket");
 
1237
      exitcode = EXIT_FAILURE;
1837
1238
#ifdef __linux__
1838
1239
      if(restore_loglevel){
1839
1240
        ret = klogctl(7, NULL, 0);
1840
1241
        if(ret == -1){
1841
 
          perror_plus("klogctl");
 
1242
          perror("klogctl");
1842
1243
        }
1843
1244
      }
1844
1245
#endif  /* __linux__ */
1846
1247
      errno = 0;
1847
1248
      ret = seteuid(uid);
1848
1249
      if(ret == -1){
1849
 
        perror_plus("seteuid");
 
1250
        perror("seteuid");
1850
1251
      }
1851
1252
      goto end;
1852
1253
    }
1853
1254
    strcpy(network.ifr_name, interface);
1854
1255
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1855
1256
    if(ret == -1){
1856
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1257
      perror("ioctl SIOCGIFFLAGS");
1857
1258
#ifdef __linux__
1858
1259
      if(restore_loglevel){
1859
1260
        ret = klogctl(7, NULL, 0);
1860
1261
        if(ret == -1){
1861
 
          perror_plus("klogctl");
 
1262
          perror("klogctl");
1862
1263
        }
1863
1264
      }
1864
1265
#endif  /* __linux__ */
1865
 
      exitcode = EX_OSERR;
 
1266
      exitcode = EXIT_FAILURE;
1866
1267
      /* Lower privileges */
1867
1268
      errno = 0;
1868
1269
      ret = seteuid(uid);
1869
1270
      if(ret == -1){
1870
 
        perror_plus("seteuid");
 
1271
        perror("seteuid");
1871
1272
      }
1872
1273
      goto end;
1873
1274
    }
1877
1278
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1878
1279
      if(ret == -1){
1879
1280
        take_down_interface = false;
1880
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1881
 
        exitcode = EX_OSERR;
 
1281
        perror("ioctl SIOCSIFFLAGS");
 
1282
        exitcode = EXIT_FAILURE;
1882
1283
#ifdef __linux__
1883
1284
        if(restore_loglevel){
1884
1285
          ret = klogctl(7, NULL, 0);
1885
1286
          if(ret == -1){
1886
 
            perror_plus("klogctl");
 
1287
            perror("klogctl");
1887
1288
          }
1888
1289
        }
1889
1290
#endif  /* __linux__ */
1891
1292
        errno = 0;
1892
1293
        ret = seteuid(uid);
1893
1294
        if(ret == -1){
1894
 
          perror_plus("seteuid");
 
1295
          perror("seteuid");
1895
1296
        }
1896
1297
        goto end;
1897
1298
      }
1898
1299
    }
1899
 
    /* Sleep checking until interface is running.
1900
 
       Check every 0.25s, up to total time of delay */
 
1300
    /* sleep checking until interface is running */
1901
1301
    for(int i=0; i < delay * 4; i++){
1902
1302
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1903
1303
      if(ret == -1){
1904
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1304
        perror("ioctl SIOCGIFFLAGS");
1905
1305
      } else if(network.ifr_flags & IFF_RUNNING){
1906
1306
        break;
1907
1307
      }
1908
1308
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1909
1309
      ret = nanosleep(&sleeptime, NULL);
1910
1310
      if(ret == -1 and errno != EINTR){
1911
 
        perror_plus("nanosleep");
 
1311
        perror("nanosleep");
1912
1312
      }
1913
1313
    }
1914
1314
    if(not take_down_interface){
1915
1315
      /* We won't need the socket anymore */
1916
1316
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1917
1317
      if(ret == -1){
1918
 
        perror_plus("close");
 
1318
        perror("close");
1919
1319
      }
1920
1320
    }
1921
1321
#ifdef __linux__
1923
1323
      /* Restores kernel loglevel to default */
1924
1324
      ret = klogctl(7, NULL, 0);
1925
1325
      if(ret == -1){
1926
 
        perror_plus("klogctl");
 
1326
        perror("klogctl");
1927
1327
      }
1928
1328
    }
1929
1329
#endif  /* __linux__ */
1933
1333
      /* Lower privileges */
1934
1334
      ret = seteuid(uid);
1935
1335
      if(ret == -1){
1936
 
        perror_plus("seteuid");
 
1336
        perror("seteuid");
1937
1337
      }
1938
1338
    } else {
1939
1339
      /* Lower privileges permanently */
1940
1340
      ret = setuid(uid);
1941
1341
      if(ret == -1){
1942
 
        perror_plus("setuid");
 
1342
        perror("setuid");
1943
1343
      }
1944
1344
    }
1945
1345
  }
1951
1351
  ret = init_gnutls_global(pubkey, seckey);
1952
1352
  if(ret == -1){
1953
1353
    fprintf(stderr, "init_gnutls_global failed\n");
1954
 
    exitcode = EX_UNAVAILABLE;
 
1354
    exitcode = EXIT_FAILURE;
1955
1355
    goto end;
1956
1356
  } else {
1957
1357
    gnutls_initialized = true;
1961
1361
    goto end;
1962
1362
  }
1963
1363
  
 
1364
  tempdir_created = true;
1964
1365
  if(mkdtemp(tempdir) == NULL){
1965
 
    perror_plus("mkdtemp");
 
1366
    tempdir_created = false;
 
1367
    perror("mkdtemp");
1966
1368
    goto end;
1967
1369
  }
1968
 
  tempdir_created = true;
1969
1370
  
1970
1371
  if(quit_now){
1971
1372
    goto end;
1973
1374
  
1974
1375
  if(not init_gpgme(pubkey, seckey, tempdir)){
1975
1376
    fprintf(stderr, "init_gpgme failed\n");
1976
 
    exitcode = EX_UNAVAILABLE;
 
1377
    exitcode = EXIT_FAILURE;
1977
1378
    goto end;
1978
1379
  } else {
1979
1380
    gpgme_initialized = true;
1989
1390
    char *address = strrchr(connect_to, ':');
1990
1391
    if(address == NULL){
1991
1392
      fprintf(stderr, "No colon in address\n");
1992
 
      exitcode = EX_USAGE;
 
1393
      exitcode = EXIT_FAILURE;
1993
1394
      goto end;
1994
1395
    }
1995
1396
    
2003
1404
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2004
1405
       or tmpmax != (uint16_t)tmpmax){
2005
1406
      fprintf(stderr, "Bad port number\n");
2006
 
      exitcode = EX_USAGE;
 
1407
      exitcode = EXIT_FAILURE;
2007
1408
      goto end;
2008
1409
    }
2009
1410
  
2013
1414
    
2014
1415
    port = (uint16_t)tmpmax;
2015
1416
    *address = '\0';
 
1417
    address = connect_to;
2016
1418
    /* Colon in address indicates IPv6 */
2017
1419
    int af;
2018
 
    if(strchr(connect_to, ':') != NULL){
 
1420
    if(strchr(address, ':') != NULL){
2019
1421
      af = AF_INET6;
2020
 
      /* Accept [] around IPv6 address - see RFC 5952 */
2021
 
      if(connect_to[0] == '[' and address[-1] == ']')
2022
 
        {
2023
 
          connect_to++;
2024
 
          address[-1] = '\0';
2025
 
        }
2026
1422
    } else {
2027
1423
      af = AF_INET;
2028
1424
    }
2029
 
    address = connect_to;
2030
1425
    
2031
1426
    if(quit_now){
2032
1427
      goto end;
2033
1428
    }
2034
1429
    
2035
 
    while(not quit_now){
2036
 
      ret = start_mandos_communication(address, port, if_index, af);
2037
 
      if(quit_now or ret == 0){
2038
 
        break;
2039
 
      }
2040
 
      if(debug){
2041
 
        fprintf(stderr, "Retrying in %d seconds\n",
2042
 
                (int)retry_interval);
2043
 
      }
2044
 
      sleep((int)retry_interval);
2045
 
    }
2046
 
    
2047
 
    if (not quit_now){
 
1430
    ret = start_mandos_communication(address, port, if_index, af);
 
1431
    if(ret < 0){
 
1432
      exitcode = EXIT_FAILURE;
 
1433
    } else {
2048
1434
      exitcode = EXIT_SUCCESS;
2049
1435
    }
2050
 
    
2051
1436
    goto end;
2052
1437
  }
2053
1438
  
2077
1462
  if(mc.server == NULL){
2078
1463
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2079
1464
            avahi_strerror(error));
2080
 
    exitcode = EX_UNAVAILABLE;
 
1465
    exitcode = EXIT_FAILURE;
2081
1466
    goto end;
2082
1467
  }
2083
1468
  
2092
1477
  if(sb == NULL){
2093
1478
    fprintf(stderr, "Failed to create service browser: %s\n",
2094
1479
            avahi_strerror(avahi_server_errno(mc.server)));
2095
 
    exitcode = EX_UNAVAILABLE;
 
1480
    exitcode = EXIT_FAILURE;
2096
1481
    goto end;
2097
1482
  }
2098
1483
  
2105
1490
  if(debug){
2106
1491
    fprintf(stderr, "Starting Avahi loop search\n");
2107
1492
  }
2108
 
 
2109
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2110
 
                                (int)(retry_interval * 1000));
2111
 
  if(debug){
2112
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2113
 
            (ret == 0) ? "successfully" : "with error");
2114
 
  }
 
1493
  
 
1494
  avahi_simple_poll_loop(mc.simple_poll);
2115
1495
  
2116
1496
 end:
2117
1497
  
2138
1518
  if(gpgme_initialized){
2139
1519
    gpgme_release(mc.ctx);
2140
1520
  }
2141
 
 
2142
 
  /* Cleans up the circular linked list of Mandos servers the client
2143
 
     has seen */
2144
 
  if(mc.current_server != NULL){
2145
 
    mc.current_server->prev->next = NULL;
2146
 
    while(mc.current_server != NULL){
2147
 
      server *next = mc.current_server->next;
2148
 
      free(mc.current_server);
2149
 
      mc.current_server = next;
2150
 
    }
2151
 
  }
2152
 
  
2153
 
  /* XXX run network hooks "stop" here  */
2154
1521
  
2155
1522
  /* Take down the network interface */
2156
1523
  if(take_down_interface){
2158
1525
    errno = 0;
2159
1526
    ret = seteuid(0);
2160
1527
    if(ret == -1){
2161
 
      perror_plus("seteuid");
 
1528
      perror("seteuid");
2162
1529
    }
2163
1530
    if(geteuid() == 0){
2164
1531
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2165
1532
      if(ret == -1){
2166
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1533
        perror("ioctl SIOCGIFFLAGS");
2167
1534
      } else if(network.ifr_flags & IFF_UP) {
2168
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1535
        network.ifr_flags &= ~IFF_UP; /* clear flag */
2169
1536
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2170
1537
        if(ret == -1){
2171
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1538
          perror("ioctl SIOCSIFFLAGS");
2172
1539
        }
2173
1540
      }
2174
1541
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2175
1542
      if(ret == -1){
2176
 
        perror_plus("close");
 
1543
        perror("close");
2177
1544
      }
2178
1545
      /* Lower privileges permanently */
2179
1546
      errno = 0;
2180
1547
      ret = setuid(uid);
2181
1548
      if(ret == -1){
2182
 
        perror_plus("setuid");
 
1549
        perror("setuid");
2183
1550
      }
2184
1551
    }
2185
1552
  }
2186
1553
  
2187
 
  /* Removes the GPGME temp directory and all files inside */
 
1554
  /* Removes the temp directory used by GPGME */
2188
1555
  if(tempdir_created){
2189
 
    struct dirent **direntries = NULL;
2190
 
    struct dirent *direntry = NULL;
2191
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2192
 
                             alphasort);
2193
 
    if (numentries > 0){
2194
 
      for(int i = 0; i < numentries; i++){
2195
 
        direntry = direntries[i];
 
1556
    DIR *d;
 
1557
    struct dirent *direntry;
 
1558
    d = opendir(tempdir);
 
1559
    if(d == NULL){
 
1560
      if(errno != ENOENT){
 
1561
        perror("opendir");
 
1562
      }
 
1563
    } else {
 
1564
      while(true){
 
1565
        direntry = readdir(d);
 
1566
        if(direntry == NULL){
 
1567
          break;
 
1568
        }
 
1569
        /* Skip "." and ".." */
 
1570
        if(direntry->d_name[0] == '.'
 
1571
           and (direntry->d_name[1] == '\0'
 
1572
                or (direntry->d_name[1] == '.'
 
1573
                    and direntry->d_name[2] == '\0'))){
 
1574
          continue;
 
1575
        }
2196
1576
        char *fullname = NULL;
2197
1577
        ret = asprintf(&fullname, "%s/%s", tempdir,
2198
1578
                       direntry->d_name);
2199
1579
        if(ret < 0){
2200
 
          perror_plus("asprintf");
 
1580
          perror("asprintf");
2201
1581
          continue;
2202
1582
        }
2203
1583
        ret = remove(fullname);
2207
1587
        }
2208
1588
        free(fullname);
2209
1589
      }
2210
 
    }
2211
 
 
2212
 
    /* need to clean even if 0 because man page doesn't specify */
2213
 
    free(direntries);
2214
 
    if (numentries == -1){
2215
 
      perror_plus("scandir");
 
1590
      closedir(d);
2216
1591
    }
2217
1592
    ret = rmdir(tempdir);
2218
1593
    if(ret == -1 and errno != ENOENT){
2219
 
      perror_plus("rmdir");
 
1594
      perror("rmdir");
2220
1595
    }
2221
1596
  }
2222
1597
  
2223
1598
  if(quit_now){
2224
1599
    sigemptyset(&old_sigterm_action.sa_mask);
2225
1600
    old_sigterm_action.sa_handler = SIG_DFL;
2226
 
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
2227
 
                                            &old_sigterm_action,
2228
 
                                            NULL));
 
1601
    ret = sigaction(signal_received, &old_sigterm_action, NULL);
2229
1602
    if(ret == -1){
2230
 
      perror_plus("sigaction");
2231
 
    }
2232
 
    do {
2233
 
      ret = raise(signal_received);
2234
 
    } while(ret != 0 and errno == EINTR);
2235
 
    if(ret != 0){
2236
 
      perror_plus("raise");
2237
 
      abort();
2238
 
    }
2239
 
    TEMP_FAILURE_RETRY(pause());
 
1603
      perror("sigaction");
 
1604
    }
 
1605
    raise(signal_received);
2240
1606
  }
2241
1607
  
2242
1608
  return exitcode;