/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-16 23:28:39 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090916232839-3o7i8qmcdcz5j1ya
* 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
 
}
 
143
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
173
144
 
174
145
/*
175
146
 * Make additional room in "buffer" for at least BUFFER_SIZE more
188
159
  return buffer_capacity;
189
160
}
190
161
 
191
 
/* Add server to set of servers to retry periodically */
192
 
int add_server(const char *ip, uint16_t port,
193
 
                 AvahiIfIndex if_index,
194
 
                 int af){
195
 
  int ret;
196
 
  server *new_server = malloc(sizeof(server));
197
 
  if(new_server == NULL){
198
 
    perror_plus("malloc");
199
 
    return -1;
200
 
  }
201
 
  *new_server = (server){ .ip = strdup(ip),
202
 
                         .port = port,
203
 
                         .if_index = if_index,
204
 
                         .af = af };
205
 
  if(new_server->ip == NULL){
206
 
    perror_plus("strdup");
207
 
    return -1;
208
 
  }
209
 
  /* Special case of first server */
210
 
  if (mc.current_server == NULL){
211
 
    new_server->next = new_server;
212
 
    new_server->prev = new_server;
213
 
    mc.current_server = new_server;
214
 
  /* Place the new server last in the list */
215
 
  } else {
216
 
    new_server->next = mc.current_server;
217
 
    new_server->prev = mc.current_server->prev;
218
 
    new_server->prev->next = new_server;
219
 
    mc.current_server->prev = new_server;
220
 
  }
221
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
222
 
  if(ret == -1){
223
 
    perror_plus("clock_gettime");
224
 
    return -1;
225
 
  }
226
 
  return 0;
227
 
}
228
 
 
229
162
/* 
230
163
 * Initialize GPGME.
231
164
 */
245
178
    
246
179
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
247
180
    if(fd == -1){
248
 
      perror_plus("open");
 
181
      perror("open");
249
182
      return false;
250
183
    }
251
184
    
265
198
    
266
199
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
267
200
    if(ret == -1){
268
 
      perror_plus("close");
 
201
      perror("close");
269
202
    }
270
203
    gpgme_data_release(pgp_data);
271
204
    return true;
284
217
    return false;
285
218
  }
286
219
  
287
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
220
    /* Set GPGME home directory for the OpenPGP engine only */
288
221
  rc = gpgme_get_engine_info(&engine_info);
289
222
  if(rc != GPG_ERR_NO_ERROR){
290
223
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
396
329
  
397
330
  /* Seek back to the beginning of the GPGME plaintext data buffer */
398
331
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
399
 
    perror_plus("gpgme_data_seek");
 
332
    perror("gpgme_data_seek");
400
333
    plaintext_length = -1;
401
334
    goto decrypt_end;
402
335
  }
407
340
                                      (size_t)plaintext_length,
408
341
                                      plaintext_capacity);
409
342
    if(plaintext_capacity == 0){
410
 
        perror_plus("incbuffer");
 
343
        perror("incbuffer");
411
344
        plaintext_length = -1;
412
345
        goto decrypt_end;
413
346
    }
420
353
      break;
421
354
    }
422
355
    if(ret < 0){
423
 
      perror_plus("gpgme_data_read");
 
356
      perror("gpgme_data_read");
424
357
      plaintext_length = -1;
425
358
      goto decrypt_end;
426
359
    }
483
416
  }
484
417
  
485
418
  /* OpenPGP credentials */
486
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
419
  gnutls_certificate_allocate_credentials(&mc.cred);
487
420
  if(ret != GNUTLS_E_SUCCESS){
488
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
421
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
422
                                                    from
 
423
                                                    -Wunreachable-code
 
424
                                                 */
489
425
            safer_gnutls_strerror(ret));
490
426
    gnutls_global_deinit();
491
427
    return -1;
540
476
  /* GnuTLS session creation */
541
477
  do {
542
478
    ret = gnutls_init(session, GNUTLS_SERVER);
543
 
    if(quit_now){
544
 
      return -1;
545
 
    }
546
479
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
547
480
  if(ret != GNUTLS_E_SUCCESS){
548
481
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
553
486
    const char *err;
554
487
    do {
555
488
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
556
 
      if(quit_now){
557
 
        gnutls_deinit(*session);
558
 
        return -1;
559
 
      }
560
489
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
561
490
    if(ret != GNUTLS_E_SUCCESS){
562
491
      fprintf(stderr, "Syntax error at: %s\n", err);
570
499
  do {
571
500
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
572
501
                                 mc.cred);
573
 
    if(quit_now){
574
 
      gnutls_deinit(*session);
575
 
      return -1;
576
 
    }
577
502
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
578
503
  if(ret != GNUTLS_E_SUCCESS){
579
504
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
594
519
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
595
520
                      __attribute__((unused)) const char *txt){}
596
521
 
 
522
sig_atomic_t quit_now = 0;
 
523
int signal_received = 0;
 
524
 
597
525
/* Called when a Mandos server is found */
598
526
static int start_mandos_communication(const char *ip, uint16_t port,
599
527
                                      AvahiIfIndex if_index,
605
533
    struct sockaddr_in6 in6;
606
534
  } to;
607
535
  char *buffer = NULL;
608
 
  char *decrypted_buffer = NULL;
 
536
  char *decrypted_buffer;
609
537
  size_t buffer_length = 0;
610
538
  size_t buffer_capacity = 0;
611
539
  size_t written;
612
 
  int retval = -1;
 
540
  int retval = 0;
613
541
  gnutls_session_t session;
614
542
  int pf;                       /* Protocol family */
615
543
  
616
 
  errno = 0;
617
 
  
618
544
  if(quit_now){
619
 
    errno = EINTR;
620
545
    return -1;
621
546
  }
622
547
  
629
554
    break;
630
555
  default:
631
556
    fprintf(stderr, "Bad address family: %d\n", af);
632
 
    errno = EINVAL;
633
557
    return -1;
634
558
  }
635
559
  
645
569
  
646
570
  tcp_sd = socket(pf, SOCK_STREAM, 0);
647
571
  if(tcp_sd < 0){
648
 
    int e = errno;
649
 
    perror_plus("socket");
650
 
    errno = e;
 
572
    perror("socket");
 
573
    retval = -1;
651
574
    goto mandos_end;
652
575
  }
653
576
  
654
577
  if(quit_now){
655
 
    errno = EINTR;
656
578
    goto mandos_end;
657
579
  }
658
580
  
665
587
    ret = inet_pton(af, ip, &to.in.sin_addr);
666
588
  }
667
589
  if(ret < 0 ){
668
 
    int e = errno;
669
 
    perror_plus("inet_pton");
670
 
    errno = e;
 
590
    perror("inet_pton");
 
591
    retval = -1;
671
592
    goto mandos_end;
672
593
  }
673
594
  if(ret == 0){
674
 
    int e = errno;
675
595
    fprintf(stderr, "Bad address: %s\n", ip);
676
 
    errno = e;
 
596
    retval = -1;
677
597
    goto mandos_end;
678
598
  }
679
599
  if(af == AF_INET6){
687
607
      if(if_index == AVAHI_IF_UNSPEC){
688
608
        fprintf(stderr, "An IPv6 link-local address is incomplete"
689
609
                " without a network interface\n");
690
 
        errno = EINVAL;
 
610
        retval = -1;
691
611
        goto mandos_end;
692
612
      }
693
613
      /* Set the network interface number as scope */
700
620
  }
701
621
  
702
622
  if(quit_now){
703
 
    errno = EINTR;
704
623
    goto mandos_end;
705
624
  }
706
625
  
708
627
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
709
628
      char interface[IF_NAMESIZE];
710
629
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
711
 
        perror_plus("if_indextoname");
 
630
        perror("if_indextoname");
712
631
      } else {
713
632
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
714
633
                ip, interface, port);
728
647
                        sizeof(addrstr));
729
648
    }
730
649
    if(pcret == NULL){
731
 
      perror_plus("inet_ntop");
 
650
      perror("inet_ntop");
732
651
    } else {
733
652
      if(strcmp(addrstr, ip) != 0){
734
653
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
737
656
  }
738
657
  
739
658
  if(quit_now){
740
 
    errno = EINTR;
741
659
    goto mandos_end;
742
660
  }
743
661
  
747
665
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
748
666
  }
749
667
  if(ret < 0){
750
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
751
 
      int e = errno;
752
 
      perror_plus("connect");
753
 
      errno = e;
754
 
    }
 
668
    perror("connect");
 
669
    retval = -1;
755
670
    goto mandos_end;
756
671
  }
757
672
  
758
673
  if(quit_now){
759
 
    errno = EINTR;
760
674
    goto mandos_end;
761
675
  }
762
676
  
767
681
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
768
682
                                   out_size - written));
769
683
    if(ret == -1){
770
 
      int e = errno;
771
 
      perror_plus("write");
772
 
      errno = e;
 
684
      perror("write");
 
685
      retval = -1;
773
686
      goto mandos_end;
774
687
    }
775
688
    written += (size_t)ret;
785
698
    }
786
699
  
787
700
    if(quit_now){
788
 
      errno = EINTR;
789
701
      goto mandos_end;
790
702
    }
791
703
  }
795
707
  }
796
708
  
797
709
  if(quit_now){
798
 
    errno = EINTR;
799
710
    goto mandos_end;
800
711
  }
801
712
  
802
 
  /* Spurious warning from -Wint-to-pointer-cast */
803
713
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
804
714
  
805
715
  if(quit_now){
806
 
    errno = EINTR;
807
716
    goto mandos_end;
808
717
  }
809
718
  
810
719
  do {
811
720
    ret = gnutls_handshake(session);
812
721
    if(quit_now){
813
 
      errno = EINTR;
814
722
      goto mandos_end;
815
723
    }
816
724
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
820
728
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
821
729
      gnutls_perror(ret);
822
730
    }
823
 
    errno = EPROTO;
 
731
    retval = -1;
824
732
    goto mandos_end;
825
733
  }
826
734
  
834
742
  while(true){
835
743
    
836
744
    if(quit_now){
837
 
      errno = EINTR;
838
745
      goto mandos_end;
839
746
    }
840
747
    
841
748
    buffer_capacity = incbuffer(&buffer, buffer_length,
842
749
                                   buffer_capacity);
843
750
    if(buffer_capacity == 0){
844
 
      int e = errno;
845
 
      perror_plus("incbuffer");
846
 
      errno = e;
 
751
      perror("incbuffer");
 
752
      retval = -1;
847
753
      goto mandos_end;
848
754
    }
849
755
    
850
756
    if(quit_now){
851
 
      errno = EINTR;
852
757
      goto mandos_end;
853
758
    }
854
759
    
867
772
          ret = gnutls_handshake(session);
868
773
          
869
774
          if(quit_now){
870
 
            errno = EINTR;
871
775
            goto mandos_end;
872
776
          }
873
777
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
874
778
        if(ret < 0){
875
779
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
876
780
          gnutls_perror(ret);
877
 
          errno = EPROTO;
 
781
          retval = -1;
878
782
          goto mandos_end;
879
783
        }
880
784
        break;
881
785
      default:
882
786
        fprintf(stderr, "Unknown error while reading data from"
883
787
                " encrypted session with Mandos server\n");
 
788
        retval = -1;
884
789
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
885
 
        errno = EIO;
886
790
        goto mandos_end;
887
791
      }
888
792
    } else {
895
799
  }
896
800
  
897
801
  if(quit_now){
898
 
    errno = EINTR;
899
 
    goto mandos_end;
900
 
  }
901
 
  
902
 
  do {
903
 
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
904
 
    if(quit_now){
905
 
      errno = EINTR;
906
 
      goto mandos_end;
907
 
    }
908
 
  } 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
  }
909
810
  
910
811
  if(buffer_length > 0){
911
812
    ssize_t decrypted_buffer_size;
917
818
      written = 0;
918
819
      while(written < (size_t) decrypted_buffer_size){
919
820
        if(quit_now){
920
 
          errno = EINTR;
921
821
          goto mandos_end;
922
822
        }
923
823
        
925
825
                          (size_t)decrypted_buffer_size - written,
926
826
                          stdout);
927
827
        if(ret == 0 and ferror(stdout)){
928
 
          int e = errno;
929
828
          if(debug){
930
829
            fprintf(stderr, "Error writing encrypted data: %s\n",
931
830
                    strerror(errno));
932
831
          }
933
 
          errno = e;
934
 
          goto mandos_end;
 
832
          retval = -1;
 
833
          break;
935
834
        }
936
835
        written += (size_t)ret;
937
836
      }
938
 
      retval = 0;
 
837
      free(decrypted_buffer);
 
838
    } else {
 
839
      retval = -1;
939
840
    }
 
841
  } else {
 
842
    retval = -1;
940
843
  }
941
844
  
942
845
  /* Shutdown procedure */
943
846
  
944
847
 mandos_end:
945
 
  {
946
 
    int e = errno;
947
 
    free(decrypted_buffer);
948
 
    free(buffer);
949
 
    if(tcp_sd >= 0){
950
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
951
 
    }
952
 
    if(ret == -1){
953
 
      if(e == 0){
954
 
        e = errno;
955
 
      }
956
 
      perror_plus("close");
957
 
    }
958
 
    gnutls_deinit(session);
959
 
    errno = e;
960
 
    if(quit_now){
961
 
      errno = EINTR;
962
 
      retval = -1;
963
 
    }
 
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;
964
858
  }
965
859
  return retval;
966
860
}
1009
903
                                           avahi_proto_to_af(proto));
1010
904
      if(ret == 0){
1011
905
        avahi_simple_poll_quit(mc.simple_poll);
1012
 
      } else {
1013
 
        ret = add_server(ip, port, interface,
1014
 
                         avahi_proto_to_af(proto));
1015
906
      }
1016
907
    }
1017
908
  }
1071
962
  }
1072
963
}
1073
964
 
1074
 
/* Signal handler that stops main loop after SIGTERM */
 
965
/* stop main loop after sigterm has been called */
1075
966
static void handle_sigterm(int sig){
1076
967
  if(quit_now){
1077
968
    return;
1079
970
  quit_now = 1;
1080
971
  signal_received = sig;
1081
972
  int old_errno = errno;
1082
 
  /* set main loop to exit */
1083
973
  if(mc.simple_poll != NULL){
1084
974
    avahi_simple_poll_quit(mc.simple_poll);
1085
975
  }
1086
976
  errno = old_errno;
1087
977
}
1088
978
 
1089
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1090
 
  int ret;
1091
 
  
1092
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1093
 
  if(s < 0){
1094
 
    perror_plus("socket");
1095
 
    return false;
1096
 
  }
1097
 
  strcpy(ifr->ifr_name, ifname);
1098
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1099
 
  if(ret == -1){
1100
 
    if(debug){
1101
 
      perror_plus("ioctl SIOCGIFFLAGS");
1102
 
    }
1103
 
    return false;
1104
 
  }
1105
 
  return true;
1106
 
}
1107
 
 
1108
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1109
 
  
1110
 
  /* Reject the loopback device */
1111
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
1112
 
    if(debug){
1113
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1114
 
              ifname);
1115
 
    }
1116
 
    return false;
1117
 
  }
1118
 
  /* Accept point-to-point devices only if connect_to is specified */
1119
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1120
 
    if(debug){
1121
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1122
 
              ifname);
1123
 
    }
1124
 
    return true;
1125
 
  }
1126
 
  /* Otherwise, reject non-broadcast-capable devices */
1127
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1128
 
    if(debug){
1129
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1130
 
              ifname);
1131
 
    }
1132
 
    return false;
1133
 
  }
1134
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1135
 
  if(ifr->ifr_flags & IFF_NOARP){
1136
 
    if(debug){
1137
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
1138
 
    }
1139
 
    return false;
1140
 
  }
1141
 
  
1142
 
  /* Accept this device */
1143
 
  if(debug){
1144
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
1145
 
  }
1146
 
  return true;
1147
 
}
1148
 
 
1149
 
/* 
1150
 
 * This function determines if a directory entry in /sys/class/net
1151
 
 * corresponds to an acceptable network device.
1152
 
 * (This function is passed to scandir(3) as a filter function.)
1153
 
 */
1154
 
int good_interface(const struct dirent *if_entry){
1155
 
  int ret;
1156
 
  if(if_entry->d_name[0] == '.'){
1157
 
    return 0;
1158
 
  }
1159
 
  struct ifreq ifr;
1160
 
 
1161
 
  if(not get_flags(if_entry->d_name, &ifr)){
1162
 
    return 0;
1163
 
  }
1164
 
  
1165
 
  if(not good_flags(if_entry->d_name, &ifr)){
1166
 
    return 0;
1167
 
  }
1168
 
  return 1;
1169
 
}
1170
 
 
1171
 
/* 
1172
 
 * This function determines if a directory entry in /sys/class/net
1173
 
 * corresponds to an acceptable network device which is up.
1174
 
 * (This function is passed to scandir(3) as a filter function.)
1175
 
 */
1176
 
int up_interface(const struct dirent *if_entry){
1177
 
  ssize_t ssret;
1178
 
  char *flagname = NULL;
1179
 
  if(if_entry->d_name[0] == '.'){
1180
 
    return 0;
1181
 
  }
1182
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1183
 
                     if_entry->d_name);
1184
 
  if(ret < 0){
1185
 
    perror_plus("asprintf");
1186
 
    return 0;
1187
 
  }
1188
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1189
 
  if(flags_fd == -1){
1190
 
    perror_plus("open");
1191
 
    free(flagname);
1192
 
    return 0;
1193
 
  }
1194
 
  free(flagname);
1195
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1196
 
  /* read line from flags_fd */
1197
 
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
1198
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1199
 
  flagstring[(size_t)to_read] = '\0';
1200
 
  if(flagstring == NULL){
1201
 
    perror_plus("malloc");
1202
 
    close(flags_fd);
1203
 
    return 0;
1204
 
  }
1205
 
  while(to_read > 0){
1206
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1207
 
                                             (size_t)to_read));
1208
 
    if(ssret == -1){
1209
 
      perror_plus("read");
1210
 
      free(flagstring);
1211
 
      close(flags_fd);
1212
 
      return 0;
1213
 
    }
1214
 
    to_read -= ssret;
1215
 
    if(ssret == 0){
1216
 
      break;
1217
 
    }
1218
 
  }
1219
 
  close(flags_fd);
1220
 
  intmax_t tmpmax;
1221
 
  char *tmp;
1222
 
  errno = 0;
1223
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1224
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1225
 
                                         and not (isspace(*tmp)))
1226
 
     or tmpmax != (ifreq_flags)tmpmax){
1227
 
    if(debug){
1228
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1229
 
              flagstring, if_entry->d_name);
1230
 
    }
1231
 
    free(flagstring);
1232
 
    return 0;
1233
 
  }
1234
 
  free(flagstring);
1235
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
1236
 
  /* Reject the loopback device */
1237
 
  if(flags & IFF_LOOPBACK){
1238
 
    if(debug){
1239
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1240
 
              if_entry->d_name);
1241
 
    }
1242
 
    return 0;
1243
 
  }
1244
 
 
1245
 
  /* Reject down interfaces */
1246
 
  if(not (flags & IFF_UP)){
1247
 
    return 0;
1248
 
  }
1249
 
  
1250
 
  /* Accept point-to-point devices only if connect_to is specified */
1251
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1252
 
    if(debug){
1253
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1254
 
              if_entry->d_name);
1255
 
    }
1256
 
    return 1;
1257
 
  }
1258
 
  /* Otherwise, reject non-broadcast-capable devices */
1259
 
  if(not (flags & IFF_BROADCAST)){
1260
 
    if(debug){
1261
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1262
 
              if_entry->d_name);
1263
 
    }
1264
 
    return 0;
1265
 
  }
1266
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1267
 
  if(flags & IFF_NOARP){
1268
 
    if(debug){
1269
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1270
 
              if_entry->d_name);
1271
 
    }
1272
 
    return 0;
1273
 
  }
1274
 
  /* Accept this device */
1275
 
  if(debug){
1276
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1277
 
            if_entry->d_name);
1278
 
  }
1279
 
  return 1;
1280
 
}
1281
 
 
1282
 
int notdotentries(const struct dirent *direntry){
1283
 
  /* Skip "." and ".." */
1284
 
  if(direntry->d_name[0] == '.'
1285
 
     and (direntry->d_name[1] == '\0'
1286
 
          or (direntry->d_name[1] == '.'
1287
 
              and direntry->d_name[2] == '\0'))){
1288
 
    return 0;
1289
 
  }
1290
 
  return 1;
1291
 
}
1292
 
 
1293
 
/* Is this directory entry a runnable program? */
1294
 
int runnable_hook(const struct dirent *direntry){
1295
 
  int ret;
1296
 
  struct stat st;
1297
 
  
1298
 
  if((direntry->d_name)[0] == '\0'){
1299
 
    /* Empty name? */
1300
 
    return 0;
1301
 
  }
1302
 
  
1303
 
  /* Save pointer to last character */
1304
 
  char *end = strchr(direntry->d_name, '\0')-1;
1305
 
  
1306
 
  if(*end == '~'){
1307
 
    /* Backup name~ */
1308
 
    return 0;
1309
 
  }
1310
 
  
1311
 
  if(((direntry->d_name)[0] == '#')
1312
 
     and (*end == '#')){
1313
 
    /* Temporary #name# */
1314
 
    return 0;
1315
 
  }
1316
 
  
1317
 
  /* XXX more rules here */
1318
 
  
1319
 
  ret = stat(direntry->d_name, &st);
1320
 
  if(ret == -1){
1321
 
    if(debug){
1322
 
      perror_plus("Could not stat plugin");
1323
 
    }
1324
 
    return 0;
1325
 
  }
1326
 
  if(not (st.st_mode & S_ISREG)){
1327
 
    /* Not a regular file */
1328
 
    return 0;
1329
 
  }
1330
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1331
 
    /* Not executable */
1332
 
    return 0;
1333
 
  }
1334
 
  return 1;
1335
 
}
1336
 
 
1337
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1338
 
  int ret;
1339
 
  struct timespec now;
1340
 
  struct timespec waited_time;
1341
 
  intmax_t block_time;
1342
 
  
1343
 
  while(true){
1344
 
    if(mc.current_server == NULL){
1345
 
      if (debug){
1346
 
        fprintf(stderr,
1347
 
                "Wait until first server is found. No timeout!\n");
1348
 
      }
1349
 
      ret = avahi_simple_poll_iterate(s, -1);
1350
 
    } else {
1351
 
      if (debug){
1352
 
        fprintf(stderr, "Check current_server if we should run it,"
1353
 
                " or wait\n");
1354
 
      }
1355
 
      /* the current time */
1356
 
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1357
 
      if(ret == -1){
1358
 
        perror_plus("clock_gettime");
1359
 
        return -1;
1360
 
      }
1361
 
      /* Calculating in ms how long time between now and server
1362
 
         who we visted longest time ago. Now - last seen.  */
1363
 
      waited_time.tv_sec = (now.tv_sec
1364
 
                            - mc.current_server->last_seen.tv_sec);
1365
 
      waited_time.tv_nsec = (now.tv_nsec
1366
 
                             - mc.current_server->last_seen.tv_nsec);
1367
 
      /* total time is 10s/10,000ms.
1368
 
         Converting to s from ms by dividing by 1,000,
1369
 
         and ns to ms by dividing by 1,000,000. */
1370
 
      block_time = ((retry_interval
1371
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1372
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1373
 
      
1374
 
      if (debug){
1375
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1376
 
      }
1377
 
      
1378
 
      if(block_time <= 0){
1379
 
        ret = start_mandos_communication(mc.current_server->ip,
1380
 
                                         mc.current_server->port,
1381
 
                                         mc.current_server->if_index,
1382
 
                                         mc.current_server->af);
1383
 
        if(ret == 0){
1384
 
          avahi_simple_poll_quit(mc.simple_poll);
1385
 
          return 0;
1386
 
        }
1387
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1388
 
                            &mc.current_server->last_seen);
1389
 
        if(ret == -1){
1390
 
          perror_plus("clock_gettime");
1391
 
          return -1;
1392
 
        }
1393
 
        mc.current_server = mc.current_server->next;
1394
 
        block_time = 0;         /* Call avahi to find new Mandos
1395
 
                                   servers, but don't block */
1396
 
      }
1397
 
      
1398
 
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1399
 
    }
1400
 
    if(ret != 0){
1401
 
      if (ret > 0 or errno != EINTR) {
1402
 
        return (ret != 1) ? ret : 0;
1403
 
      }
1404
 
    }
1405
 
  }
1406
 
}
1407
 
 
1408
979
int main(int argc, char *argv[]){
1409
980
  AvahiSServiceBrowser *sb = NULL;
1410
981
  int error;
1412
983
  intmax_t tmpmax;
1413
984
  char *tmp;
1414
985
  int exitcode = EXIT_SUCCESS;
1415
 
  const char *interface = "";
 
986
  const char *interface = "eth0";
1416
987
  struct ifreq network;
1417
988
  int sd = -1;
1418
989
  bool take_down_interface = false;
1419
990
  uid_t uid;
1420
991
  gid_t gid;
 
992
  char *connect_to = NULL;
1421
993
  char tempdir[] = "/tmp/mandosXXXXXX";
1422
994
  bool tempdir_created = false;
1423
995
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1427
999
  bool gnutls_initialized = false;
1428
1000
  bool gpgme_initialized = false;
1429
1001
  float delay = 2.5f;
1430
 
  double retry_interval = 10; /* 10s between trying a server and
1431
 
                                 retrying the same server again */
1432
1002
  
1433
1003
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1434
1004
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1440
1010
  errno = 0;
1441
1011
  ret = setgid(gid);
1442
1012
  if(ret == -1){
1443
 
    perror_plus("setgid");
 
1013
    perror("setgid");
1444
1014
  }
1445
1015
  
1446
1016
  /* Lower user privileges (temporarily) */
1447
1017
  errno = 0;
1448
1018
  ret = seteuid(uid);
1449
1019
  if(ret == -1){
1450
 
    perror_plus("seteuid");
 
1020
    perror("seteuid");
1451
1021
  }
1452
1022
  
1453
1023
  if(quit_now){
1488
1058
        .arg = "SECONDS",
1489
1059
        .doc = "Maximum delay to wait for interface startup",
1490
1060
        .group = 2 },
1491
 
      { .name = "retry", .key = 132,
1492
 
        .arg = "SECONDS",
1493
 
        .doc = "Retry interval used when denied by the mandos server",
1494
 
        .group = 2 },
1495
 
      /*
1496
 
       * These reproduce what we would get without ARGP_NO_HELP
1497
 
       */
1498
 
      { .name = "help", .key = '?',
1499
 
        .doc = "Give this help list", .group = -1 },
1500
 
      { .name = "usage", .key = -3,
1501
 
        .doc = "Give a short usage message", .group = -1 },
1502
 
      { .name = "version", .key = 'V',
1503
 
        .doc = "Print program version", .group = -1 },
1504
1061
      { .name = NULL }
1505
1062
    };
1506
1063
    
1507
1064
    error_t parse_opt(int key, char *arg,
1508
1065
                      struct argp_state *state){
1509
 
      errno = 0;
1510
1066
      switch(key){
1511
1067
      case 128:                 /* --debug */
1512
1068
        debug = true;
1528
1084
        tmpmax = strtoimax(arg, &tmp, 10);
1529
1085
        if(errno != 0 or tmp == arg or *tmp != '\0'
1530
1086
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1531
 
          argp_error(state, "Bad number of DH bits");
 
1087
          fprintf(stderr, "Bad number of DH bits\n");
 
1088
          exit(EXIT_FAILURE);
1532
1089
        }
1533
1090
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1534
1091
        break;
1539
1096
        errno = 0;
1540
1097
        delay = strtof(arg, &tmp);
1541
1098
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1542
 
          argp_error(state, "Bad delay");
1543
 
        }
1544
 
      case 132:                 /* --retry */
1545
 
        errno = 0;
1546
 
        retry_interval = strtod(arg, &tmp);
1547
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1548
 
           or (retry_interval * 1000) > INT_MAX
1549
 
           or retry_interval < 0){
1550
 
          argp_error(state, "Bad retry interval");
 
1099
          fprintf(stderr, "Bad delay\n");
 
1100
          exit(EXIT_FAILURE);
1551
1101
        }
1552
1102
        break;
1553
 
        /*
1554
 
         * These reproduce what we would get without ARGP_NO_HELP
1555
 
         */
1556
 
      case '?':                 /* --help */
1557
 
        argp_state_help(state, state->out_stream,
1558
 
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1559
 
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
1560
 
      case -3:                  /* --usage */
1561
 
        argp_state_help(state, state->out_stream,
1562
 
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1563
 
      case 'V':                 /* --version */
1564
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
1565
 
        exit(argp_err_exit_status);
 
1103
      case ARGP_KEY_ARG:
 
1104
        argp_usage(state);
 
1105
      case ARGP_KEY_END:
1566
1106
        break;
1567
1107
      default:
1568
1108
        return ARGP_ERR_UNKNOWN;
1569
1109
      }
1570
 
      return errno;
 
1110
      return 0;
1571
1111
    }
1572
1112
    
1573
1113
    struct argp argp = { .options = options, .parser = parse_opt,
1574
1114
                         .args_doc = "",
1575
1115
                         .doc = "Mandos client -- Get and decrypt"
1576
1116
                         " passwords from a Mandos server" };
1577
 
    ret = argp_parse(&argp, argc, argv,
1578
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1579
 
    switch(ret){
1580
 
    case 0:
1581
 
      break;
1582
 
    case ENOMEM:
1583
 
    default:
1584
 
      errno = ret;
1585
 
      perror_plus("argp_parse");
1586
 
      exitcode = EX_OSERR;
1587
 
      goto end;
1588
 
    case EINVAL:
1589
 
      exitcode = EX_USAGE;
1590
 
      goto end;
1591
 
    }
1592
 
  }
1593
 
    
1594
 
  {
1595
 
    /* Work around Debian bug #633582:
1596
 
       <http://bugs.debian.org/633582> */
1597
 
    struct stat st;
1598
 
    
1599
 
    /* Re-raise priviliges */
1600
 
    errno = 0;
1601
 
    ret = seteuid(0);
1602
 
    if(ret == -1){
1603
 
      perror_plus("seteuid");
1604
 
    }
1605
 
    
1606
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1607
 
      int seckey_fd = open(seckey, O_RDONLY);
1608
 
      if(seckey_fd == -1){
1609
 
        perror_plus("open");
1610
 
      } else {
1611
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1612
 
        if(ret == -1){
1613
 
          perror_plus("fstat");
1614
 
        } else {
1615
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1616
 
            ret = fchown(seckey_fd, uid, gid);
1617
 
            if(ret == -1){
1618
 
              perror_plus("fchown");
1619
 
            }
1620
 
          }
1621
 
        }
1622
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1623
 
      }
1624
 
    }
1625
 
    
1626
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1627
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1628
 
      if(pubkey_fd == -1){
1629
 
        perror_plus("open");
1630
 
      } else {
1631
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1632
 
        if(ret == -1){
1633
 
          perror_plus("fstat");
1634
 
        } else {
1635
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1636
 
            ret = fchown(pubkey_fd, uid, gid);
1637
 
            if(ret == -1){
1638
 
              perror_plus("fchown");
1639
 
            }
1640
 
          }
1641
 
        }
1642
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1643
 
      }
1644
 
    }
1645
 
    
1646
 
    /* Lower privileges */
1647
 
    errno = 0;
1648
 
    ret = seteuid(uid);
1649
 
    if(ret == -1){
1650
 
      perror_plus("seteuid");
1651
 
    }
1652
 
  }
1653
 
  
1654
 
  /* Find network hooks and run them */
1655
 
  {
1656
 
    struct dirent **direntries;
1657
 
    struct dirent *direntry;
1658
 
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
1659
 
                           alphasort);
1660
 
    int devnull = open("/dev/null", O_RDONLY);
1661
 
    for(int i = 0; i < numhooks; i++){
1662
 
      direntry = direntries[0];
1663
 
      char *fullname = NULL;
1664
 
      ret = asprintf(&fullname, "%s/%s", tempdir,
1665
 
                     direntry->d_name);
1666
 
      if(ret < 0){
1667
 
        perror_plus("asprintf");
1668
 
        continue;
1669
 
      }
1670
 
      pid_t hook_pid = fork();
1671
 
      if(hook_pid == 0){
1672
 
        /* Child */
1673
 
        dup2(devnull, STDIN_FILENO);
1674
 
        close(devnull);
1675
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1676
 
        setenv("DEVICE", interface, 1);
1677
 
        setenv("VERBOSE", debug ? "1" : "0", 1);
1678
 
        setenv("MODE", "start", 1);
1679
 
        /* setenv( XXX more here */
1680
 
        ret = execl(fullname, direntry->d_name, "start");
1681
 
        perror_plus("execl");
1682
 
      }
1683
 
      free(fullname);
1684
 
      if(quit_now){
1685
 
        goto end;
1686
 
      }
1687
 
    }
1688
 
    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
    }
1689
1123
  }
1690
1124
  
1691
1125
  if(not debug){
1692
1126
    avahi_set_log_function(empty_log);
1693
1127
  }
1694
1128
  
1695
 
  if(interface[0] == '\0'){
1696
 
    struct dirent **direntries;
1697
 
    ret = scandir(sys_class_net, &direntries, good_interface,
1698
 
                  alphasort);
1699
 
    if(ret >= 1){
1700
 
      /* Pick the first good interface */
1701
 
      interface = strdup(direntries[0]->d_name);
1702
 
      if(debug){
1703
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1704
 
      }
1705
 
      if(interface == NULL){
1706
 
        perror_plus("malloc");
1707
 
        free(direntries);
1708
 
        exitcode = EXIT_FAILURE;
1709
 
        goto end;
1710
 
      }
1711
 
      free(direntries);
1712
 
    } else {
1713
 
      free(direntries);
1714
 
      fprintf(stderr, "Could not find a network interface\n");
1715
 
      exitcode = EXIT_FAILURE;
1716
 
      goto end;
1717
 
    }
1718
 
  }
1719
 
  
1720
1129
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1721
1130
     from the signal handler */
1722
1131
  /* Initialize the pseudo-RNG for Avahi */
1724
1133
  mc.simple_poll = avahi_simple_poll_new();
1725
1134
  if(mc.simple_poll == NULL){
1726
1135
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1727
 
    exitcode = EX_UNAVAILABLE;
 
1136
    exitcode = EXIT_FAILURE;
1728
1137
    goto end;
1729
1138
  }
1730
1139
  
1731
1140
  sigemptyset(&sigterm_action.sa_mask);
1732
1141
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1733
1142
  if(ret == -1){
1734
 
    perror_plus("sigaddset");
1735
 
    exitcode = EX_OSERR;
 
1143
    perror("sigaddset");
 
1144
    exitcode = EXIT_FAILURE;
1736
1145
    goto end;
1737
1146
  }
1738
1147
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1739
1148
  if(ret == -1){
1740
 
    perror_plus("sigaddset");
1741
 
    exitcode = EX_OSERR;
 
1149
    perror("sigaddset");
 
1150
    exitcode = EXIT_FAILURE;
1742
1151
    goto end;
1743
1152
  }
1744
1153
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1745
1154
  if(ret == -1){
1746
 
    perror_plus("sigaddset");
1747
 
    exitcode = EX_OSERR;
 
1155
    perror("sigaddset");
 
1156
    exitcode = EXIT_FAILURE;
1748
1157
    goto end;
1749
1158
  }
1750
1159
  /* Need to check if the handler is SIG_IGN before handling:
1753
1162
  */
1754
1163
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1755
1164
  if(ret == -1){
1756
 
    perror_plus("sigaction");
1757
 
    return EX_OSERR;
 
1165
    perror("sigaction");
 
1166
    return EXIT_FAILURE;
1758
1167
  }
1759
1168
  if(old_sigterm_action.sa_handler != SIG_IGN){
1760
1169
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1761
1170
    if(ret == -1){
1762
 
      perror_plus("sigaction");
1763
 
      exitcode = EX_OSERR;
 
1171
      perror("sigaction");
 
1172
      exitcode = EXIT_FAILURE;
1764
1173
      goto end;
1765
1174
    }
1766
1175
  }
1767
1176
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1768
1177
  if(ret == -1){
1769
 
    perror_plus("sigaction");
1770
 
    return EX_OSERR;
 
1178
    perror("sigaction");
 
1179
    return EXIT_FAILURE;
1771
1180
  }
1772
1181
  if(old_sigterm_action.sa_handler != SIG_IGN){
1773
1182
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1774
1183
    if(ret == -1){
1775
 
      perror_plus("sigaction");
1776
 
      exitcode = EX_OSERR;
 
1184
      perror("sigaction");
 
1185
      exitcode = EXIT_FAILURE;
1777
1186
      goto end;
1778
1187
    }
1779
1188
  }
1780
1189
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1781
1190
  if(ret == -1){
1782
 
    perror_plus("sigaction");
1783
 
    return EX_OSERR;
 
1191
    perror("sigaction");
 
1192
    return EXIT_FAILURE;
1784
1193
  }
1785
1194
  if(old_sigterm_action.sa_handler != SIG_IGN){
1786
1195
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1787
1196
    if(ret == -1){
1788
 
      perror_plus("sigaction");
1789
 
      exitcode = EX_OSERR;
 
1197
      perror("sigaction");
 
1198
      exitcode = EXIT_FAILURE;
1790
1199
      goto end;
1791
1200
    }
1792
1201
  }
1793
1202
  
1794
1203
  /* If the interface is down, bring it up */
1795
 
  if(strcmp(interface, "none") != 0){
 
1204
  if(interface[0] != '\0'){
1796
1205
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1797
1206
    if(if_index == 0){
1798
1207
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1799
 
      exitcode = EX_UNAVAILABLE;
 
1208
      exitcode = EXIT_FAILURE;
1800
1209
      goto end;
1801
1210
    }
1802
1211
    
1808
1217
    errno = 0;
1809
1218
    ret = seteuid(0);
1810
1219
    if(ret == -1){
1811
 
      perror_plus("seteuid");
 
1220
      perror("seteuid");
1812
1221
    }
1813
1222
    
1814
1223
#ifdef __linux__
1815
1224
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1816
 
       messages about the network interface to mess up the prompt */
 
1225
       messages to mess up the prompt */
1817
1226
    ret = klogctl(8, NULL, 5);
1818
1227
    bool restore_loglevel = true;
1819
1228
    if(ret == -1){
1820
1229
      restore_loglevel = false;
1821
 
      perror_plus("klogctl");
 
1230
      perror("klogctl");
1822
1231
    }
1823
1232
#endif  /* __linux__ */
1824
1233
    
1825
1234
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1826
1235
    if(sd < 0){
1827
 
      perror_plus("socket");
1828
 
      exitcode = EX_OSERR;
 
1236
      perror("socket");
 
1237
      exitcode = EXIT_FAILURE;
1829
1238
#ifdef __linux__
1830
1239
      if(restore_loglevel){
1831
1240
        ret = klogctl(7, NULL, 0);
1832
1241
        if(ret == -1){
1833
 
          perror_plus("klogctl");
 
1242
          perror("klogctl");
1834
1243
        }
1835
1244
      }
1836
1245
#endif  /* __linux__ */
1838
1247
      errno = 0;
1839
1248
      ret = seteuid(uid);
1840
1249
      if(ret == -1){
1841
 
        perror_plus("seteuid");
 
1250
        perror("seteuid");
1842
1251
      }
1843
1252
      goto end;
1844
1253
    }
1845
1254
    strcpy(network.ifr_name, interface);
1846
1255
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1847
1256
    if(ret == -1){
1848
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1257
      perror("ioctl SIOCGIFFLAGS");
1849
1258
#ifdef __linux__
1850
1259
      if(restore_loglevel){
1851
1260
        ret = klogctl(7, NULL, 0);
1852
1261
        if(ret == -1){
1853
 
          perror_plus("klogctl");
 
1262
          perror("klogctl");
1854
1263
        }
1855
1264
      }
1856
1265
#endif  /* __linux__ */
1857
 
      exitcode = EX_OSERR;
 
1266
      exitcode = EXIT_FAILURE;
1858
1267
      /* Lower privileges */
1859
1268
      errno = 0;
1860
1269
      ret = seteuid(uid);
1861
1270
      if(ret == -1){
1862
 
        perror_plus("seteuid");
 
1271
        perror("seteuid");
1863
1272
      }
1864
1273
      goto end;
1865
1274
    }
1869
1278
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1870
1279
      if(ret == -1){
1871
1280
        take_down_interface = false;
1872
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1873
 
        exitcode = EX_OSERR;
 
1281
        perror("ioctl SIOCSIFFLAGS");
 
1282
        exitcode = EXIT_FAILURE;
1874
1283
#ifdef __linux__
1875
1284
        if(restore_loglevel){
1876
1285
          ret = klogctl(7, NULL, 0);
1877
1286
          if(ret == -1){
1878
 
            perror_plus("klogctl");
 
1287
            perror("klogctl");
1879
1288
          }
1880
1289
        }
1881
1290
#endif  /* __linux__ */
1883
1292
        errno = 0;
1884
1293
        ret = seteuid(uid);
1885
1294
        if(ret == -1){
1886
 
          perror_plus("seteuid");
 
1295
          perror("seteuid");
1887
1296
        }
1888
1297
        goto end;
1889
1298
      }
1890
1299
    }
1891
 
    /* Sleep checking until interface is running.
1892
 
       Check every 0.25s, up to total time of delay */
 
1300
    /* sleep checking until interface is running */
1893
1301
    for(int i=0; i < delay * 4; i++){
1894
1302
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1895
1303
      if(ret == -1){
1896
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1304
        perror("ioctl SIOCGIFFLAGS");
1897
1305
      } else if(network.ifr_flags & IFF_RUNNING){
1898
1306
        break;
1899
1307
      }
1900
1308
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1901
1309
      ret = nanosleep(&sleeptime, NULL);
1902
1310
      if(ret == -1 and errno != EINTR){
1903
 
        perror_plus("nanosleep");
 
1311
        perror("nanosleep");
1904
1312
      }
1905
1313
    }
1906
1314
    if(not take_down_interface){
1907
1315
      /* We won't need the socket anymore */
1908
1316
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1909
1317
      if(ret == -1){
1910
 
        perror_plus("close");
 
1318
        perror("close");
1911
1319
      }
1912
1320
    }
1913
1321
#ifdef __linux__
1915
1323
      /* Restores kernel loglevel to default */
1916
1324
      ret = klogctl(7, NULL, 0);
1917
1325
      if(ret == -1){
1918
 
        perror_plus("klogctl");
 
1326
        perror("klogctl");
1919
1327
      }
1920
1328
    }
1921
1329
#endif  /* __linux__ */
1925
1333
      /* Lower privileges */
1926
1334
      ret = seteuid(uid);
1927
1335
      if(ret == -1){
1928
 
        perror_plus("seteuid");
 
1336
        perror("seteuid");
1929
1337
      }
1930
1338
    } else {
1931
1339
      /* Lower privileges permanently */
1932
1340
      ret = setuid(uid);
1933
1341
      if(ret == -1){
1934
 
        perror_plus("setuid");
 
1342
        perror("setuid");
1935
1343
      }
1936
1344
    }
1937
1345
  }
1943
1351
  ret = init_gnutls_global(pubkey, seckey);
1944
1352
  if(ret == -1){
1945
1353
    fprintf(stderr, "init_gnutls_global failed\n");
1946
 
    exitcode = EX_UNAVAILABLE;
 
1354
    exitcode = EXIT_FAILURE;
1947
1355
    goto end;
1948
1356
  } else {
1949
1357
    gnutls_initialized = true;
1953
1361
    goto end;
1954
1362
  }
1955
1363
  
 
1364
  tempdir_created = true;
1956
1365
  if(mkdtemp(tempdir) == NULL){
1957
 
    perror_plus("mkdtemp");
 
1366
    tempdir_created = false;
 
1367
    perror("mkdtemp");
1958
1368
    goto end;
1959
1369
  }
1960
 
  tempdir_created = true;
1961
1370
  
1962
1371
  if(quit_now){
1963
1372
    goto end;
1965
1374
  
1966
1375
  if(not init_gpgme(pubkey, seckey, tempdir)){
1967
1376
    fprintf(stderr, "init_gpgme failed\n");
1968
 
    exitcode = EX_UNAVAILABLE;
 
1377
    exitcode = EXIT_FAILURE;
1969
1378
    goto end;
1970
1379
  } else {
1971
1380
    gpgme_initialized = true;
1981
1390
    char *address = strrchr(connect_to, ':');
1982
1391
    if(address == NULL){
1983
1392
      fprintf(stderr, "No colon in address\n");
1984
 
      exitcode = EX_USAGE;
 
1393
      exitcode = EXIT_FAILURE;
1985
1394
      goto end;
1986
1395
    }
1987
1396
    
1995
1404
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1996
1405
       or tmpmax != (uint16_t)tmpmax){
1997
1406
      fprintf(stderr, "Bad port number\n");
1998
 
      exitcode = EX_USAGE;
 
1407
      exitcode = EXIT_FAILURE;
1999
1408
      goto end;
2000
1409
    }
2001
1410
  
2005
1414
    
2006
1415
    port = (uint16_t)tmpmax;
2007
1416
    *address = '\0';
 
1417
    address = connect_to;
2008
1418
    /* Colon in address indicates IPv6 */
2009
1419
    int af;
2010
 
    if(strchr(connect_to, ':') != NULL){
 
1420
    if(strchr(address, ':') != NULL){
2011
1421
      af = AF_INET6;
2012
 
      /* Accept [] around IPv6 address - see RFC 5952 */
2013
 
      if(connect_to[0] == '[' and address[-1] == ']')
2014
 
        {
2015
 
          connect_to++;
2016
 
          address[-1] = '\0';
2017
 
        }
2018
1422
    } else {
2019
1423
      af = AF_INET;
2020
1424
    }
2021
 
    address = connect_to;
2022
1425
    
2023
1426
    if(quit_now){
2024
1427
      goto end;
2025
1428
    }
2026
1429
    
2027
 
    while(not quit_now){
2028
 
      ret = start_mandos_communication(address, port, if_index, af);
2029
 
      if(quit_now or ret == 0){
2030
 
        break;
2031
 
      }
2032
 
      if(debug){
2033
 
        fprintf(stderr, "Retrying in %d seconds\n",
2034
 
                (int)retry_interval);
2035
 
      }
2036
 
      sleep((int)retry_interval);
2037
 
    }
2038
 
    
2039
 
    if (not quit_now){
 
1430
    ret = start_mandos_communication(address, port, if_index, af);
 
1431
    if(ret < 0){
 
1432
      exitcode = EXIT_FAILURE;
 
1433
    } else {
2040
1434
      exitcode = EXIT_SUCCESS;
2041
1435
    }
2042
 
    
2043
1436
    goto end;
2044
1437
  }
2045
1438
  
2069
1462
  if(mc.server == NULL){
2070
1463
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2071
1464
            avahi_strerror(error));
2072
 
    exitcode = EX_UNAVAILABLE;
 
1465
    exitcode = EXIT_FAILURE;
2073
1466
    goto end;
2074
1467
  }
2075
1468
  
2084
1477
  if(sb == NULL){
2085
1478
    fprintf(stderr, "Failed to create service browser: %s\n",
2086
1479
            avahi_strerror(avahi_server_errno(mc.server)));
2087
 
    exitcode = EX_UNAVAILABLE;
 
1480
    exitcode = EXIT_FAILURE;
2088
1481
    goto end;
2089
1482
  }
2090
1483
  
2097
1490
  if(debug){
2098
1491
    fprintf(stderr, "Starting Avahi loop search\n");
2099
1492
  }
2100
 
 
2101
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2102
 
                                (int)(retry_interval * 1000));
2103
 
  if(debug){
2104
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2105
 
            (ret == 0) ? "successfully" : "with error");
2106
 
  }
 
1493
  
 
1494
  avahi_simple_poll_loop(mc.simple_poll);
2107
1495
  
2108
1496
 end:
2109
1497
  
2130
1518
  if(gpgme_initialized){
2131
1519
    gpgme_release(mc.ctx);
2132
1520
  }
2133
 
 
2134
 
  /* Cleans up the circular linked list of Mandos servers the client
2135
 
     has seen */
2136
 
  if(mc.current_server != NULL){
2137
 
    mc.current_server->prev->next = NULL;
2138
 
    while(mc.current_server != NULL){
2139
 
      server *next = mc.current_server->next;
2140
 
      free(mc.current_server);
2141
 
      mc.current_server = next;
2142
 
    }
2143
 
  }
2144
 
  
2145
 
  /* XXX run network hooks "stop" here  */
2146
1521
  
2147
1522
  /* Take down the network interface */
2148
1523
  if(take_down_interface){
2150
1525
    errno = 0;
2151
1526
    ret = seteuid(0);
2152
1527
    if(ret == -1){
2153
 
      perror_plus("seteuid");
 
1528
      perror("seteuid");
2154
1529
    }
2155
1530
    if(geteuid() == 0){
2156
1531
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2157
1532
      if(ret == -1){
2158
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1533
        perror("ioctl SIOCGIFFLAGS");
2159
1534
      } else if(network.ifr_flags & IFF_UP) {
2160
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1535
        network.ifr_flags &= ~IFF_UP; /* clear flag */
2161
1536
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2162
1537
        if(ret == -1){
2163
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1538
          perror("ioctl SIOCSIFFLAGS");
2164
1539
        }
2165
1540
      }
2166
1541
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2167
1542
      if(ret == -1){
2168
 
        perror_plus("close");
 
1543
        perror("close");
2169
1544
      }
2170
1545
      /* Lower privileges permanently */
2171
1546
      errno = 0;
2172
1547
      ret = setuid(uid);
2173
1548
      if(ret == -1){
2174
 
        perror_plus("setuid");
 
1549
        perror("setuid");
2175
1550
      }
2176
1551
    }
2177
1552
  }
2178
1553
  
2179
 
  /* Removes the GPGME temp directory and all files inside */
 
1554
  /* Removes the temp directory used by GPGME */
2180
1555
  if(tempdir_created){
2181
 
    struct dirent **direntries = NULL;
2182
 
    struct dirent *direntry = NULL;
2183
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2184
 
                             alphasort);
2185
 
    if (numentries > 0){
2186
 
      for(int i = 0; i < numentries; i++){
2187
 
        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
        }
2188
1576
        char *fullname = NULL;
2189
1577
        ret = asprintf(&fullname, "%s/%s", tempdir,
2190
1578
                       direntry->d_name);
2191
1579
        if(ret < 0){
2192
 
          perror_plus("asprintf");
 
1580
          perror("asprintf");
2193
1581
          continue;
2194
1582
        }
2195
1583
        ret = remove(fullname);
2199
1587
        }
2200
1588
        free(fullname);
2201
1589
      }
2202
 
    }
2203
 
 
2204
 
    /* need to clean even if 0 because man page doesn't specify */
2205
 
    free(direntries);
2206
 
    if (numentries == -1){
2207
 
      perror_plus("scandir");
 
1590
      closedir(d);
2208
1591
    }
2209
1592
    ret = rmdir(tempdir);
2210
1593
    if(ret == -1 and errno != ENOENT){
2211
 
      perror_plus("rmdir");
 
1594
      perror("rmdir");
2212
1595
    }
2213
1596
  }
2214
1597
  
2215
1598
  if(quit_now){
2216
1599
    sigemptyset(&old_sigterm_action.sa_mask);
2217
1600
    old_sigterm_action.sa_handler = SIG_DFL;
2218
 
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
2219
 
                                            &old_sigterm_action,
2220
 
                                            NULL));
 
1601
    ret = sigaction(signal_received, &old_sigterm_action, NULL);
2221
1602
    if(ret == -1){
2222
 
      perror_plus("sigaction");
2223
 
    }
2224
 
    do {
2225
 
      ret = raise(signal_received);
2226
 
    } while(ret != 0 and errno == EINTR);
2227
 
    if(ret != 0){
2228
 
      perror_plus("raise");
2229
 
      abort();
2230
 
    }
2231
 
    TEMP_FAILURE_RETRY(pause());
 
1603
      perror("sigaction");
 
1604
    }
 
1605
    raise(signal_received);
2232
1606
  }
2233
1607
  
2234
1608
  return exitcode;