/mandos/release

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

« back to all changes in this revision

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

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

Show diffs side-by-side

added added

removed removed

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