/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

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