/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2009-02-13 05:38:21 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090213053821-03e696gckk4nbjps
Support not using IPv6 in server:

* mandos (AvahiService.__init__): Take new "protocol" parameter.  All
                                  callers changed.
  (IPv6_TCPServer.__init__): Take new "use_ipv6" parameter.  All
                             callers changed.
  (IPv6_TCPServer.server_bind): Create IPv4 socket if not using IPv6.
  (main): New "--no-ipv6" command line option.  New "use_ipv6" config
          option.
* mandos-options.xml ([@id="address"]): Document conditional IPv4
                                        address support.
  ([@id="ipv6"]): New paragraph.
* mandos.conf (use_ipv6): New config option.
* mandos.conf.xml (OPTIONS): Document new "use_dbus" option.
  (EXAMPLE): Changed to use IPv6 link-local address.  Added "use_ipv6"
             option.
* mandos.xml (SYNOPSIS): New "--no-ipv6" option.
  (OPTIONS): Document new "--no-ipv6" option.

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