/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

Earlier signal handling

Show diffs side-by-side

added added

removed removed

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