/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: Björn Påhlsson
  • Date: 2011-06-23 22:27:15 UTC
  • mto: This revision was merged to the branch mainline in revision 485.
  • Revision ID: belorn@fukt.bsnet.se-20110623222715-q5wro9ma9iyjl367
* Makefile (CFLAGS): Added "-lrt" to include real time library.
* plugins.d/mandos-client.c: use scandir(3) instead of readdir(3)
                             Prefix all debug output with "Mandos plugin " + program_invocation_short_name
                             Retry servers that failed to provide password.
                             New option --retry SECONDS that sets the interval between rechecking.
                             --retry also controls how often it retries a server when using --connect.
* plugins.d/splashy.c:  Prefix all debug output with "Mandos plugin " + program_invocation_short_name
* plugins.d/usplash.c: --||--
* plugins.d/askpass-fifo.c: --||--
* plugins.d/password-prompt.c: --||--
* plugins.d/plymouth.c: --||--
* mandos: Lower logger level from warning to info on failed client requests because client was disabled or unknown fingerprint.
* plugins.d/plymouth.c (get_pid): bug fix. Was not calling free on direntries. 

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
43
43
                                   stdout, ferror(), remove() */
44
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
47
 
                                   srand(), strtof() */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
 
47
                                   strtof(), abort() */
48
48
#include <stdbool.h>            /* bool, false, true */
49
49
#include <string.h>             /* memset(), strcmp(), strlen(),
50
50
                                   strerror(), asprintf(), strcpy() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno */
66
 
#include <time.h>               /* nanosleep(), time() */
 
65
#include <errno.h>              /* perror(), errno, program_invocation_short_name */
 
66
#include <time.h>               /* nanosleep(), time(), sleep() */
67
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
68
                                   SIOCSIFFLAGS, if_indextoname(),
69
69
                                   if_nametoindex(), IF_NAMESIZE */
71
71
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
72
72
                                */
73
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
 
                                   getuid(), getgid(), setuid(),
75
 
                                   setgid() */
 
74
                                   getuid(), getgid(), seteuid(),
 
75
                                   setgid(), pause() */
76
76
#include <arpa/inet.h>          /* inet_pton(), htons */
77
77
#include <iso646.h>             /* not, or, and */
78
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
80
                                   argp_parse(), ARGP_KEY_ARG,
81
81
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
82
82
#include <signal.h>             /* sigemptyset(), sigaddset(),
83
 
                                   sigaction(), SIGTERM, sigaction,
84
 
                                   sig_atomic_t */
 
83
                                   sigaction(), SIGTERM, sig_atomic_t,
 
84
                                   raise() */
 
85
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
 
86
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
85
87
 
86
88
#ifdef __linux__
87
89
#include <sys/klog.h>           /* klogctl() */
125
127
static const char mandos_protocol_version[] = "1";
126
128
const char *argp_program_version = "mandos-client " VERSION;
127
129
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
130
static const char sys_class_net[] = "/sys/class/net";
 
131
char *connect_to = NULL;
 
132
 
 
133
/* Doubly linked list that need to be circular linked when ever used */
 
134
typedef struct server{
 
135
  const char *ip;
 
136
  uint16_t port;
 
137
  AvahiIfIndex if_index;
 
138
  int af;
 
139
  struct timespec last_seen;
 
140
  struct server *next;
 
141
  struct server *prev;
 
142
} server;
128
143
 
129
144
/* Used for passing in values through the Avahi callback functions */
130
145
typedef struct {
135
150
  gnutls_dh_params_t dh_params;
136
151
  const char *priority;
137
152
  gpgme_ctx_t ctx;
 
153
  server *current_server;
138
154
} mandos_context;
139
155
 
140
156
/* global context so signal handler can reach it*/
141
157
mandos_context mc = { .simple_poll = NULL, .server = NULL,
142
158
                      .dh_bits = 1024, .priority = "SECURE256"
143
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
159
                      ":!CTYPE-X.509:+CTYPE-OPENPGP", .current_server = NULL };
 
160
 
 
161
sig_atomic_t quit_now = 0;
 
162
int signal_received = 0;
 
163
 
 
164
/* Function to use when printing errors */
 
165
void perror_plus(const char *print_text){
 
166
  fprintf(stderr, "Mandos plugin %s: ", program_invocation_short_name);
 
167
  perror(print_text);
 
168
}
144
169
 
145
170
/*
146
171
 * Make additional room in "buffer" for at least BUFFER_SIZE more
159
184
  return buffer_capacity;
160
185
}
161
186
 
 
187
int add_server(const char *ip, uint16_t port,
 
188
                 AvahiIfIndex if_index,
 
189
                 int af){
 
190
  int ret;
 
191
  server *new_server = malloc(sizeof(server));
 
192
  if(new_server == NULL){
 
193
    perror_plus("malloc");
 
194
    return -1;
 
195
  }
 
196
  *new_server = (server){ .ip = strdup(ip),
 
197
                         .port = port,
 
198
                         .if_index = if_index,
 
199
                         .af = af };
 
200
  if(new_server->ip == NULL){
 
201
    perror_plus("strdup");
 
202
    return -1;    
 
203
  }
 
204
  /* uniqe case of first server */
 
205
  if (mc.current_server == NULL){
 
206
    new_server->next = new_server;
 
207
    new_server->prev = new_server;
 
208
    mc.current_server = new_server;
 
209
  /* Placing the new server last in the list */
 
210
  } else {
 
211
    new_server->next = mc.current_server;
 
212
    new_server->prev = mc.current_server->prev;
 
213
    new_server->prev->next = new_server;
 
214
    mc.current_server->prev = new_server;
 
215
  }
 
216
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
217
  if(ret == -1){
 
218
    perror_plus("clock_gettime");
 
219
    return -1;
 
220
  }
 
221
  return 0;
 
222
}
 
223
 
162
224
/* 
163
225
 * Initialize GPGME.
164
226
 */
165
227
static bool init_gpgme(const char *seckey,
166
228
                       const char *pubkey, const char *tempdir){
167
 
  int ret;
168
229
  gpgme_error_t rc;
169
230
  gpgme_engine_info_t engine_info;
170
231
  
173
234
   * Helper function to insert pub and seckey to the engine keyring.
174
235
   */
175
236
  bool import_key(const char *filename){
 
237
    int ret;
176
238
    int fd;
177
239
    gpgme_data_t pgp_data;
178
240
    
179
241
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
180
242
    if(fd == -1){
181
 
      perror("open");
 
243
      perror_plus("open");
182
244
      return false;
183
245
    }
184
246
    
198
260
    
199
261
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
200
262
    if(ret == -1){
201
 
      perror("close");
 
263
      perror_plus("close");
202
264
    }
203
265
    gpgme_data_release(pgp_data);
204
266
    return true;
249
311
    return false;
250
312
  }
251
313
  
252
 
  return true; 
 
314
  return true;
253
315
}
254
316
 
255
317
/* 
309
371
        }
310
372
        gpgme_recipient_t recipient;
311
373
        recipient = result->recipients;
312
 
        if(recipient){
313
 
          while(recipient != NULL){
314
 
            fprintf(stderr, "Public key algorithm: %s\n",
315
 
                    gpgme_pubkey_algo_name(recipient->pubkey_algo));
316
 
            fprintf(stderr, "Key ID: %s\n", recipient->keyid);
317
 
            fprintf(stderr, "Secret key available: %s\n",
318
 
                    recipient->status == GPG_ERR_NO_SECKEY
319
 
                    ? "No" : "Yes");
320
 
            recipient = recipient->next;
321
 
          }
 
374
        while(recipient != NULL){
 
375
          fprintf(stderr, "Public key algorithm: %s\n",
 
376
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
377
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
378
          fprintf(stderr, "Secret key available: %s\n",
 
379
                  recipient->status == GPG_ERR_NO_SECKEY
 
380
                  ? "No" : "Yes");
 
381
          recipient = recipient->next;
322
382
        }
323
383
      }
324
384
    }
331
391
  
332
392
  /* Seek back to the beginning of the GPGME plaintext data buffer */
333
393
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
334
 
    perror("gpgme_data_seek");
 
394
    perror_plus("gpgme_data_seek");
335
395
    plaintext_length = -1;
336
396
    goto decrypt_end;
337
397
  }
342
402
                                      (size_t)plaintext_length,
343
403
                                      plaintext_capacity);
344
404
    if(plaintext_capacity == 0){
345
 
        perror("incbuffer");
 
405
        perror_plus("incbuffer");
346
406
        plaintext_length = -1;
347
407
        goto decrypt_end;
348
408
    }
355
415
      break;
356
416
    }
357
417
    if(ret < 0){
358
 
      perror("gpgme_data_read");
 
418
      perror_plus("gpgme_data_read");
359
419
      plaintext_length = -1;
360
420
      goto decrypt_end;
361
421
    }
476
536
static int init_gnutls_session(gnutls_session_t *session){
477
537
  int ret;
478
538
  /* GnuTLS session creation */
479
 
  ret = gnutls_init(session, GNUTLS_SERVER);
 
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);
480
545
  if(ret != GNUTLS_E_SUCCESS){
481
546
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
482
547
            safer_gnutls_strerror(ret));
484
549
  
485
550
  {
486
551
    const char *err;
487
 
    ret = gnutls_priority_set_direct(*session, mc.priority, &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);
488
559
    if(ret != GNUTLS_E_SUCCESS){
489
560
      fprintf(stderr, "Syntax error at: %s\n", err);
490
561
      fprintf(stderr, "GnuTLS error: %s\n",
494
565
    }
495
566
  }
496
567
  
497
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
498
 
                               mc.cred);
 
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);
499
576
  if(ret != GNUTLS_E_SUCCESS){
500
577
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
501
578
            safer_gnutls_strerror(ret));
504
581
  }
505
582
  
506
583
  /* ignore client certificate if any. */
507
 
  gnutls_certificate_server_set_request(*session,
508
 
                                        GNUTLS_CERT_IGNORE);
 
584
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
509
585
  
510
586
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
511
587
  
520
596
static int start_mandos_communication(const char *ip, uint16_t port,
521
597
                                      AvahiIfIndex if_index,
522
598
                                      int af){
523
 
  int ret, tcp_sd;
 
599
  int ret, tcp_sd = -1;
524
600
  ssize_t sret;
525
601
  union {
526
602
    struct sockaddr_in in;
527
603
    struct sockaddr_in6 in6;
528
604
  } to;
529
605
  char *buffer = NULL;
530
 
  char *decrypted_buffer;
 
606
  char *decrypted_buffer = NULL;
531
607
  size_t buffer_length = 0;
532
608
  size_t buffer_capacity = 0;
533
 
  ssize_t decrypted_buffer_size;
534
609
  size_t written;
535
 
  int retval = 0;
 
610
  int retval = -1;
536
611
  gnutls_session_t session;
537
612
  int pf;                       /* Protocol family */
538
613
  
 
614
  errno = 0;
 
615
  
 
616
  if(quit_now){
 
617
    errno = EINTR;
 
618
    return -1;
 
619
  }
 
620
  
539
621
  switch(af){
540
622
  case AF_INET6:
541
623
    pf = PF_INET6;
545
627
    break;
546
628
  default:
547
629
    fprintf(stderr, "Bad address family: %d\n", af);
 
630
    errno = EINVAL;
548
631
    return -1;
549
632
  }
550
633
  
560
643
  
561
644
  tcp_sd = socket(pf, SOCK_STREAM, 0);
562
645
  if(tcp_sd < 0){
563
 
    perror("socket");
564
 
    return -1;
 
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;
565
655
  }
566
656
  
567
657
  memset(&to, 0, sizeof(to));
568
658
  if(af == AF_INET6){
569
 
    to.in6.sin6_family = (uint16_t)af;
 
659
    to.in6.sin6_family = (sa_family_t)af;
570
660
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
571
661
  } else {                      /* IPv4 */
572
662
    to.in.sin_family = (sa_family_t)af;
573
663
    ret = inet_pton(af, ip, &to.in.sin_addr);
574
664
  }
575
665
  if(ret < 0 ){
576
 
    perror("inet_pton");
577
 
    return -1;
 
666
    int e = errno;
 
667
    perror_plus("inet_pton");
 
668
    errno = e;
 
669
    goto mandos_end;
578
670
  }
579
671
  if(ret == 0){
 
672
    int e = errno;
580
673
    fprintf(stderr, "Bad address: %s\n", ip);
581
 
    return -1;
 
674
    errno = e;
 
675
    goto mandos_end;
582
676
  }
583
677
  if(af == AF_INET6){
584
678
    to.in6.sin6_port = htons(port); /* Spurious warnings from
591
685
      if(if_index == AVAHI_IF_UNSPEC){
592
686
        fprintf(stderr, "An IPv6 link-local address is incomplete"
593
687
                " without a network interface\n");
594
 
        return -1;
 
688
        errno = EINVAL;
 
689
        goto mandos_end;
595
690
      }
596
691
      /* Set the network interface number as scope */
597
692
      to.in6.sin6_scope_id = (uint32_t)if_index;
602
697
                                     -Wunreachable-code */
603
698
  }
604
699
  
 
700
  if(quit_now){
 
701
    errno = EINTR;
 
702
    goto mandos_end;
 
703
  }
 
704
  
605
705
  if(debug){
606
706
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
607
707
      char interface[IF_NAMESIZE];
608
708
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
609
 
        perror("if_indextoname");
 
709
        perror_plus("if_indextoname");
610
710
      } else {
611
711
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
612
712
                ip, interface, port);
626
726
                        sizeof(addrstr));
627
727
    }
628
728
    if(pcret == NULL){
629
 
      perror("inet_ntop");
 
729
      perror_plus("inet_ntop");
630
730
    } else {
631
731
      if(strcmp(addrstr, ip) != 0){
632
732
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
634
734
    }
635
735
  }
636
736
  
 
737
  if(quit_now){
 
738
    errno = EINTR;
 
739
    goto mandos_end;
 
740
  }
 
741
  
637
742
  if(af == AF_INET6){
638
743
    ret = connect(tcp_sd, &to.in6, sizeof(to));
639
744
  } else {
640
745
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
641
746
  }
642
747
  if(ret < 0){
643
 
    perror("connect");
644
 
    return -1;
 
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;
645
759
  }
646
760
  
647
761
  const char *out = mandos_protocol_version;
651
765
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
652
766
                                   out_size - written));
653
767
    if(ret == -1){
654
 
      perror("write");
655
 
      retval = -1;
 
768
      int e = errno;
 
769
      perror_plus("write");
 
770
      errno = e;
656
771
      goto mandos_end;
657
772
    }
658
773
    written += (size_t)ret;
666
781
        break;
667
782
      }
668
783
    }
 
784
  
 
785
    if(quit_now){
 
786
      errno = EINTR;
 
787
      goto mandos_end;
 
788
    }
669
789
  }
670
790
  
671
791
  if(debug){
672
792
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
673
793
  }
674
794
  
 
795
  if(quit_now){
 
796
    errno = EINTR;
 
797
    goto mandos_end;
 
798
  }
 
799
 
 
800
  /* Spurious warnings from -Wint-to-pointer-cast */
675
801
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
676
802
  
677
 
  do{
 
803
  if(quit_now){
 
804
    errno = EINTR;
 
805
    goto mandos_end;
 
806
  }
 
807
  
 
808
  do {
678
809
    ret = gnutls_handshake(session);
 
810
    if(quit_now){
 
811
      errno = EINTR;
 
812
      goto mandos_end;
 
813
    }
679
814
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
680
815
  
681
816
  if(ret != GNUTLS_E_SUCCESS){
683
818
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
684
819
      gnutls_perror(ret);
685
820
    }
686
 
    retval = -1;
 
821
    errno = EPROTO;
687
822
    goto mandos_end;
688
823
  }
689
824
  
695
830
  }
696
831
  
697
832
  while(true){
 
833
    
 
834
    if(quit_now){
 
835
      errno = EINTR;
 
836
      goto mandos_end;
 
837
    }
 
838
    
698
839
    buffer_capacity = incbuffer(&buffer, buffer_length,
699
840
                                   buffer_capacity);
700
841
    if(buffer_capacity == 0){
701
 
      perror("incbuffer");
702
 
      retval = -1;
 
842
      int e = errno;
 
843
      perror_plus("incbuffer");
 
844
      errno = e;
 
845
      goto mandos_end;
 
846
    }
 
847
    
 
848
    if(quit_now){
 
849
      errno = EINTR;
703
850
      goto mandos_end;
704
851
    }
705
852
    
714
861
      case GNUTLS_E_AGAIN:
715
862
        break;
716
863
      case GNUTLS_E_REHANDSHAKE:
717
 
        do{
 
864
        do {
718
865
          ret = gnutls_handshake(session);
 
866
          
 
867
          if(quit_now){
 
868
            errno = EINTR;
 
869
            goto mandos_end;
 
870
          }
719
871
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
720
872
        if(ret < 0){
721
873
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
722
874
          gnutls_perror(ret);
723
 
          retval = -1;
 
875
          errno = EPROTO;
724
876
          goto mandos_end;
725
877
        }
726
878
        break;
727
879
      default:
728
880
        fprintf(stderr, "Unknown error while reading data from"
729
881
                " encrypted session with Mandos server\n");
730
 
        retval = -1;
731
882
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
883
        errno = EIO;
732
884
        goto mandos_end;
733
885
      }
734
886
    } else {
740
892
    fprintf(stderr, "Closing TLS session\n");
741
893
  }
742
894
  
743
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
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);
744
907
  
745
908
  if(buffer_length > 0){
 
909
    ssize_t decrypted_buffer_size;
746
910
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
747
911
                                               buffer_length,
748
912
                                               &decrypted_buffer);
749
913
    if(decrypted_buffer_size >= 0){
 
914
      
750
915
      written = 0;
751
916
      while(written < (size_t) decrypted_buffer_size){
 
917
        if(quit_now){
 
918
          errno = EINTR;
 
919
          goto mandos_end;
 
920
        }
 
921
        
752
922
        ret = (int)fwrite(decrypted_buffer + written, 1,
753
923
                          (size_t)decrypted_buffer_size - written,
754
924
                          stdout);
755
925
        if(ret == 0 and ferror(stdout)){
 
926
          int e = errno;
756
927
          if(debug){
757
928
            fprintf(stderr, "Error writing encrypted data: %s\n",
758
929
                    strerror(errno));
759
930
          }
760
 
          retval = -1;
761
 
          break;
 
931
          errno = e;
 
932
          goto mandos_end;
762
933
        }
763
934
        written += (size_t)ret;
764
935
      }
765
 
      free(decrypted_buffer);
766
 
    } else {
767
 
      retval = -1;
 
936
      retval = 0;
768
937
    }
769
 
  } else {
770
 
    retval = -1;
771
938
  }
772
939
  
773
940
  /* Shutdown procedure */
774
941
  
775
942
 mandos_end:
776
 
  free(buffer);
777
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
778
 
  if(ret == -1){
779
 
    perror("close");
 
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
    }
780
962
  }
781
 
  gnutls_deinit(session);
782
963
  return retval;
783
964
}
784
965
 
801
982
  /* Called whenever a service has been resolved successfully or
802
983
     timed out */
803
984
  
 
985
  if(quit_now){
 
986
    return;
 
987
  }
 
988
  
804
989
  switch(event){
805
990
  default:
806
991
  case AVAHI_RESOLVER_FAILURE:
822
1007
                                           avahi_proto_to_af(proto));
823
1008
      if(ret == 0){
824
1009
        avahi_simple_poll_quit(mc.simple_poll);
 
1010
      } else {
 
1011
        ret = add_server(ip, port, interface,
 
1012
                         avahi_proto_to_af(proto));
825
1013
      }
826
1014
    }
827
1015
  }
843
1031
  /* Called whenever a new services becomes available on the LAN or
844
1032
     is removed from the LAN */
845
1033
  
 
1034
  if(quit_now){
 
1035
    return;
 
1036
  }
 
1037
  
846
1038
  switch(event){
847
1039
  default:
848
1040
  case AVAHI_BROWSER_FAILURE:
877
1069
  }
878
1070
}
879
1071
 
880
 
sig_atomic_t quit_now = 0;
881
 
 
882
 
/* stop main loop after sigterm has been called */
883
 
static void handle_sigterm(__attribute__((unused)) int sig){
 
1072
/* Signal handler that stops main loop after sigterm has been called */
 
1073
static void handle_sigterm(int sig){
884
1074
  if(quit_now){
885
1075
    return;
886
1076
  }
887
1077
  quit_now = 1;
 
1078
  signal_received = sig;
888
1079
  int old_errno = errno;
 
1080
  /* set main loop to exit */
889
1081
  if(mc.simple_poll != NULL){
890
1082
    avahi_simple_poll_quit(mc.simple_poll);
891
1083
  }
892
1084
  errno = old_errno;
893
1085
}
894
1086
 
 
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 = (sizeof(ifreq_flags)*2)+3; /* "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, "Wait until first server is found. No timeout!\n");     
 
1213
      }
 
1214
      ret = avahi_simple_poll_iterate(s, -1);
 
1215
    } else {
 
1216
      if (debug){
 
1217
        fprintf(stderr, "Check current_server if we should run it, or wait\n"); 
 
1218
      }
 
1219
      /* the current time */
 
1220
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1221
      if(ret == -1){
 
1222
        perror_plus("clock_gettime");
 
1223
        return -1;
 
1224
      }
 
1225
      /* Calculating in ms how long time between now and server
 
1226
         who we visted longest time ago. Now - last seen.  */
 
1227
      waited_time.tv_sec = now.tv_sec - mc.current_server->last_seen.tv_sec;
 
1228
      waited_time.tv_nsec = now.tv_nsec - mc.current_server->last_seen.tv_nsec;
 
1229
      /* total time is 10s/10000ms. Converting to s to ms by 1000/s, and ns to ms by divind by 1000000. */
 
1230
      block_time = (retry_interval - ((intmax_t)waited_time.tv_sec * 1000)) - ((intmax_t)waited_time.tv_nsec / 1000000);
 
1231
 
 
1232
      if (debug){
 
1233
        fprintf(stderr, "Blocking for %ld ms\n", block_time);   
 
1234
      }
 
1235
 
 
1236
      if(block_time <= 0){
 
1237
        ret = start_mandos_communication(mc.current_server->ip,
 
1238
                                   mc.current_server->port,
 
1239
                                   mc.current_server->if_index,
 
1240
                                   mc.current_server->af);
 
1241
        if(ret == 0){
 
1242
          avahi_simple_poll_quit(mc.simple_poll);
 
1243
          return 0;
 
1244
        }
 
1245
        ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
1246
        if(ret == -1){
 
1247
          perror_plus("clock_gettime");
 
1248
          return -1;
 
1249
        }
 
1250
        mc.current_server = mc.current_server->next;
 
1251
        block_time = 0;         /* call avahi to find new mandos servers, but dont block */
 
1252
      }
 
1253
      
 
1254
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1255
    }
 
1256
    if(ret != 0){
 
1257
      if (ret > 0 or errno != EINTR) {
 
1258
        return (ret != 1) ? ret : 0;
 
1259
      }
 
1260
    }
 
1261
  }
 
1262
}
 
1263
 
895
1264
int main(int argc, char *argv[]){
896
1265
  AvahiSServiceBrowser *sb = NULL;
897
1266
  int error;
899
1268
  intmax_t tmpmax;
900
1269
  char *tmp;
901
1270
  int exitcode = EXIT_SUCCESS;
902
 
  const char *interface = "eth0";
 
1271
  const char *interface = "";
903
1272
  struct ifreq network;
904
 
  int sd;
 
1273
  int sd = -1;
 
1274
  bool take_down_interface = false;
905
1275
  uid_t uid;
906
1276
  gid_t gid;
907
 
  char *connect_to = NULL;
908
1277
  char tempdir[] = "/tmp/mandosXXXXXX";
909
1278
  bool tempdir_created = false;
910
1279
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
914
1283
  bool gnutls_initialized = false;
915
1284
  bool gpgme_initialized = false;
916
1285
  float delay = 2.5f;
 
1286
  double retry_interval = 10; /* 10s between retrying a server and checking again*/
917
1287
  
918
 
  struct sigaction old_sigterm_action;
 
1288
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
919
1289
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
920
1290
  
 
1291
  uid = getuid();
 
1292
  gid = getgid();
 
1293
  
 
1294
  /* Lower any group privileges we might have, just to be safe */
 
1295
  errno = 0;
 
1296
  ret = setgid(gid);
 
1297
  if(ret == -1){
 
1298
    perror_plus("setgid");
 
1299
  }
 
1300
  
 
1301
  /* Lower user privileges (temporarily) */
 
1302
  errno = 0;
 
1303
  ret = seteuid(uid);
 
1304
  if(ret == -1){
 
1305
    perror_plus("seteuid");
 
1306
  }
 
1307
  
 
1308
  if(quit_now){
 
1309
    goto end;
 
1310
  }
 
1311
  
921
1312
  {
922
1313
    struct argp_option options[] = {
923
1314
      { .name = "debug", .key = 128,
952
1343
        .arg = "SECONDS",
953
1344
        .doc = "Maximum delay to wait for interface startup",
954
1345
        .group = 2 },
 
1346
      { .name = "retry", .key = 132,
 
1347
        .arg = "SECONDS",
 
1348
        .doc = "Retry interval used when denied by the mandos server",
 
1349
        .group = 2 },
 
1350
      /*
 
1351
       * These reproduce what we would get without ARGP_NO_HELP
 
1352
       */
 
1353
      { .name = "help", .key = '?',
 
1354
        .doc = "Give this help list", .group = -1 },
 
1355
      { .name = "usage", .key = -3,
 
1356
        .doc = "Give a short usage message", .group = -1 },
 
1357
      { .name = "version", .key = 'V',
 
1358
        .doc = "Print program version", .group = -1 },
955
1359
      { .name = NULL }
956
1360
    };
957
1361
    
958
1362
    error_t parse_opt(int key, char *arg,
959
1363
                      struct argp_state *state){
 
1364
      errno = 0;
960
1365
      switch(key){
961
1366
      case 128:                 /* --debug */
962
1367
        debug = true;
978
1383
        tmpmax = strtoimax(arg, &tmp, 10);
979
1384
        if(errno != 0 or tmp == arg or *tmp != '\0'
980
1385
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
981
 
          fprintf(stderr, "Bad number of DH bits\n");
982
 
          exit(EXIT_FAILURE);
 
1386
          argp_error(state, "Bad number of DH bits");
983
1387
        }
984
1388
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
985
1389
        break;
990
1394
        errno = 0;
991
1395
        delay = strtof(arg, &tmp);
992
1396
        if(errno != 0 or tmp == arg or *tmp != '\0'){
993
 
          fprintf(stderr, "Bad delay\n");
994
 
          exit(EXIT_FAILURE);
 
1397
          argp_error(state, "Bad delay");
 
1398
        }
 
1399
      case 132:                 /* --retry */
 
1400
        errno = 0;
 
1401
        retry_interval = strtod(arg, &tmp);
 
1402
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1403
           or (retry_interval * 1000) > INT_MAX){
 
1404
          argp_error(state, "Bad retry interval");
995
1405
        }
996
1406
        break;
997
 
      case ARGP_KEY_ARG:
998
 
        argp_usage(state);
999
 
      case ARGP_KEY_END:
 
1407
        /*
 
1408
         * These reproduce what we would get without ARGP_NO_HELP
 
1409
         */
 
1410
      case '?':                 /* --help */
 
1411
        argp_state_help(state, state->out_stream,
 
1412
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
 
1413
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
 
1414
      case -3:                  /* --usage */
 
1415
        argp_state_help(state, state->out_stream,
 
1416
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
 
1417
      case 'V':                 /* --version */
 
1418
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1419
        exit(argp_err_exit_status);
1000
1420
        break;
1001
1421
      default:
1002
1422
        return ARGP_ERR_UNKNOWN;
1003
1423
      }
1004
 
      return 0;
 
1424
      return errno;
1005
1425
    }
1006
1426
    
1007
1427
    struct argp argp = { .options = options, .parser = parse_opt,
1008
1428
                         .args_doc = "",
1009
1429
                         .doc = "Mandos client -- Get and decrypt"
1010
1430
                         " passwords from a Mandos server" };
1011
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
1012
 
    if(ret == ARGP_ERR_UNKNOWN){
1013
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
1014
 
      exitcode = EXIT_FAILURE;
 
1431
    ret = argp_parse(&argp, argc, argv,
 
1432
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1433
    switch(ret){
 
1434
    case 0:
 
1435
      break;
 
1436
    case ENOMEM:
 
1437
    default:
 
1438
      errno = ret;
 
1439
      perror_plus("argp_parse");
 
1440
      exitcode = EX_OSERR;
 
1441
      goto end;
 
1442
    case EINVAL:
 
1443
      exitcode = EX_USAGE;
1015
1444
      goto end;
1016
1445
    }
1017
1446
  }
1019
1448
  if(not debug){
1020
1449
    avahi_set_log_function(empty_log);
1021
1450
  }
 
1451
 
 
1452
  if(interface[0] == '\0'){
 
1453
    struct dirent **direntries;
 
1454
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1455
                  alphasort);
 
1456
    if(ret >= 1){
 
1457
      /* Pick the first good interface */
 
1458
      interface = strdup(direntries[0]->d_name);
 
1459
      if(debug){
 
1460
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1461
      }
 
1462
      if(interface == NULL){
 
1463
        perror_plus("malloc");
 
1464
        free(direntries);
 
1465
        exitcode = EXIT_FAILURE;
 
1466
        goto end;
 
1467
      }
 
1468
      free(direntries);
 
1469
    } else {
 
1470
      free(direntries);
 
1471
      fprintf(stderr, "Could not find a network interface\n");
 
1472
      exitcode = EXIT_FAILURE;
 
1473
      goto end;
 
1474
    }
 
1475
  }
1022
1476
  
1023
1477
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1024
1478
     from the signal handler */
1027
1481
  mc.simple_poll = avahi_simple_poll_new();
1028
1482
  if(mc.simple_poll == NULL){
1029
1483
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1030
 
    exitcode = EXIT_FAILURE;
 
1484
    exitcode = EX_UNAVAILABLE;
1031
1485
    goto end;
1032
1486
  }
1033
1487
  
1034
1488
  sigemptyset(&sigterm_action.sa_mask);
1035
1489
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1036
1490
  if(ret == -1){
1037
 
    perror("sigaddset");
1038
 
    exitcode = EXIT_FAILURE;
 
1491
    perror_plus("sigaddset");
 
1492
    exitcode = EX_OSERR;
1039
1493
    goto end;
1040
1494
  }
1041
1495
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1042
1496
  if(ret == -1){
1043
 
    perror("sigaddset");
1044
 
    exitcode = EXIT_FAILURE;
 
1497
    perror_plus("sigaddset");
 
1498
    exitcode = EX_OSERR;
1045
1499
    goto end;
1046
1500
  }
1047
1501
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1048
1502
  if(ret == -1){
1049
 
    perror("sigaddset");
1050
 
    exitcode = EXIT_FAILURE;
1051
 
    goto end;
1052
 
  }
1053
 
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
1054
 
  if(ret == -1){
1055
 
    perror("sigaction");
1056
 
    exitcode = EXIT_FAILURE;
1057
 
    goto end;
1058
 
  }  
 
1503
    perror_plus("sigaddset");
 
1504
    exitcode = EX_OSERR;
 
1505
    goto end;
 
1506
  }
 
1507
  /* Need to check if the handler is SIG_IGN before handling:
 
1508
     | [[info:libc:Initial Signal Actions]] |
 
1509
     | [[info:libc:Basic Signal Handling]]  |
 
1510
  */
 
1511
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
 
1512
  if(ret == -1){
 
1513
    perror_plus("sigaction");
 
1514
    return EX_OSERR;
 
1515
  }
 
1516
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1517
    ret = sigaction(SIGINT, &sigterm_action, NULL);
 
1518
    if(ret == -1){
 
1519
      perror_plus("sigaction");
 
1520
      exitcode = EX_OSERR;
 
1521
      goto end;
 
1522
    }
 
1523
  }
 
1524
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
 
1525
  if(ret == -1){
 
1526
    perror_plus("sigaction");
 
1527
    return EX_OSERR;
 
1528
  }
 
1529
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1530
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
 
1531
    if(ret == -1){
 
1532
      perror_plus("sigaction");
 
1533
      exitcode = EX_OSERR;
 
1534
      goto end;
 
1535
    }
 
1536
  }
 
1537
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
 
1538
  if(ret == -1){
 
1539
    perror_plus("sigaction");
 
1540
    return EX_OSERR;
 
1541
  }
 
1542
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1543
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
 
1544
    if(ret == -1){
 
1545
      perror_plus("sigaction");
 
1546
      exitcode = EX_OSERR;
 
1547
      goto end;
 
1548
    }
 
1549
  }
1059
1550
  
1060
1551
  /* If the interface is down, bring it up */
1061
 
  if(interface[0] != '\0'){
 
1552
  if(strcmp(interface, "none") != 0){
 
1553
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1554
    if(if_index == 0){
 
1555
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1556
      exitcode = EX_UNAVAILABLE;
 
1557
      goto end;
 
1558
    }
 
1559
    
 
1560
    if(quit_now){
 
1561
      goto end;
 
1562
    }
 
1563
    
 
1564
    /* Re-raise priviliges */
 
1565
    errno = 0;
 
1566
    ret = seteuid(0);
 
1567
    if(ret == -1){
 
1568
      perror_plus("seteuid");
 
1569
    }
 
1570
    
1062
1571
#ifdef __linux__
1063
1572
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1064
 
       messages to mess up the prompt */
 
1573
       messages about the network interface to mess up the prompt */
1065
1574
    ret = klogctl(8, NULL, 5);
1066
1575
    bool restore_loglevel = true;
1067
1576
    if(ret == -1){
1068
1577
      restore_loglevel = false;
1069
 
      perror("klogctl");
 
1578
      perror_plus("klogctl");
1070
1579
    }
1071
1580
#endif  /* __linux__ */
1072
1581
    
1073
1582
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1074
1583
    if(sd < 0){
1075
 
      perror("socket");
1076
 
      exitcode = EXIT_FAILURE;
 
1584
      perror_plus("socket");
 
1585
      exitcode = EX_OSERR;
1077
1586
#ifdef __linux__
1078
1587
      if(restore_loglevel){
1079
1588
        ret = klogctl(7, NULL, 0);
1080
1589
        if(ret == -1){
1081
 
          perror("klogctl");
 
1590
          perror_plus("klogctl");
1082
1591
        }
1083
1592
      }
1084
1593
#endif  /* __linux__ */
 
1594
      /* Lower privileges */
 
1595
      errno = 0;
 
1596
      ret = seteuid(uid);
 
1597
      if(ret == -1){
 
1598
        perror_plus("seteuid");
 
1599
      }
1085
1600
      goto end;
1086
1601
    }
1087
1602
    strcpy(network.ifr_name, interface);
1088
1603
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1089
1604
    if(ret == -1){
1090
 
      perror("ioctl SIOCGIFFLAGS");
 
1605
      perror_plus("ioctl SIOCGIFFLAGS");
1091
1606
#ifdef __linux__
1092
1607
      if(restore_loglevel){
1093
1608
        ret = klogctl(7, NULL, 0);
1094
1609
        if(ret == -1){
1095
 
          perror("klogctl");
 
1610
          perror_plus("klogctl");
1096
1611
        }
1097
1612
      }
1098
1613
#endif  /* __linux__ */
1099
 
      exitcode = EXIT_FAILURE;
 
1614
      exitcode = EX_OSERR;
 
1615
      /* Lower privileges */
 
1616
      errno = 0;
 
1617
      ret = seteuid(uid);
 
1618
      if(ret == -1){
 
1619
        perror_plus("seteuid");
 
1620
      }
1100
1621
      goto end;
1101
1622
    }
1102
1623
    if((network.ifr_flags & IFF_UP) == 0){
1103
1624
      network.ifr_flags |= IFF_UP;
 
1625
      take_down_interface = true;
1104
1626
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1105
1627
      if(ret == -1){
1106
 
        perror("ioctl SIOCSIFFLAGS");
1107
 
        exitcode = EXIT_FAILURE;
 
1628
        take_down_interface = false;
 
1629
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1630
        exitcode = EX_OSERR;
1108
1631
#ifdef __linux__
1109
1632
        if(restore_loglevel){
1110
1633
          ret = klogctl(7, NULL, 0);
1111
1634
          if(ret == -1){
1112
 
            perror("klogctl");
 
1635
            perror_plus("klogctl");
1113
1636
          }
1114
1637
        }
1115
1638
#endif  /* __linux__ */
 
1639
        /* Lower privileges */
 
1640
        errno = 0;
 
1641
        ret = seteuid(uid);
 
1642
        if(ret == -1){
 
1643
          perror_plus("seteuid");
 
1644
        }
1116
1645
        goto end;
1117
1646
      }
1118
1647
    }
1119
 
    /* sleep checking until interface is running */
 
1648
    /* sleep checking until interface is running. Check every 0.25s, up to total time of delay */
1120
1649
    for(int i=0; i < delay * 4; i++){
1121
1650
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1122
1651
      if(ret == -1){
1123
 
        perror("ioctl SIOCGIFFLAGS");
 
1652
        perror_plus("ioctl SIOCGIFFLAGS");
1124
1653
      } else if(network.ifr_flags & IFF_RUNNING){
1125
1654
        break;
1126
1655
      }
1127
1656
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1128
1657
      ret = nanosleep(&sleeptime, NULL);
1129
1658
      if(ret == -1 and errno != EINTR){
1130
 
        perror("nanosleep");
 
1659
        perror_plus("nanosleep");
1131
1660
      }
1132
1661
    }
1133
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1134
 
    if(ret == -1){
1135
 
      perror("close");
 
1662
    if(not take_down_interface){
 
1663
      /* We won't need the socket anymore */
 
1664
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1665
      if(ret == -1){
 
1666
        perror_plus("close");
 
1667
      }
1136
1668
    }
1137
1669
#ifdef __linux__
1138
1670
    if(restore_loglevel){
1139
1671
      /* Restores kernel loglevel to default */
1140
1672
      ret = klogctl(7, NULL, 0);
1141
1673
      if(ret == -1){
1142
 
        perror("klogctl");
 
1674
        perror_plus("klogctl");
1143
1675
      }
1144
1676
    }
1145
1677
#endif  /* __linux__ */
1146
 
  }
1147
 
  
1148
 
  uid = getuid();
1149
 
  gid = getgid();
1150
 
  
1151
 
  errno = 0;
1152
 
  setgid(gid);
1153
 
  if(ret == -1){
1154
 
    perror("setgid");
1155
 
  }
1156
 
  
1157
 
  ret = setuid(uid);
1158
 
  if(ret == -1){
1159
 
    perror("setuid");
 
1678
    /* Lower privileges */
 
1679
    errno = 0;
 
1680
    if(take_down_interface){
 
1681
      /* Lower privileges */
 
1682
      ret = seteuid(uid);
 
1683
      if(ret == -1){
 
1684
        perror_plus("seteuid");
 
1685
      }
 
1686
    } else {
 
1687
      /* Lower privileges permanently */
 
1688
      ret = setuid(uid);
 
1689
      if(ret == -1){
 
1690
        perror_plus("setuid");
 
1691
      }
 
1692
    }
 
1693
  }
 
1694
  
 
1695
  if(quit_now){
 
1696
    goto end;
1160
1697
  }
1161
1698
  
1162
1699
  ret = init_gnutls_global(pubkey, seckey);
1163
1700
  if(ret == -1){
1164
1701
    fprintf(stderr, "init_gnutls_global failed\n");
1165
 
    exitcode = EXIT_FAILURE;
 
1702
    exitcode = EX_UNAVAILABLE;
1166
1703
    goto end;
1167
1704
  } else {
1168
1705
    gnutls_initialized = true;
1169
1706
  }
1170
1707
  
 
1708
  if(quit_now){
 
1709
    goto end;
 
1710
  }
 
1711
  
1171
1712
  if(mkdtemp(tempdir) == NULL){
1172
 
    perror("mkdtemp");
 
1713
    perror_plus("mkdtemp");
1173
1714
    goto end;
1174
1715
  }
1175
1716
  tempdir_created = true;
1176
1717
  
 
1718
  if(quit_now){
 
1719
    goto end;
 
1720
  }
 
1721
  
1177
1722
  if(not init_gpgme(pubkey, seckey, tempdir)){
1178
1723
    fprintf(stderr, "init_gpgme failed\n");
1179
 
    exitcode = EXIT_FAILURE;
 
1724
    exitcode = EX_UNAVAILABLE;
1180
1725
    goto end;
1181
1726
  } else {
1182
1727
    gpgme_initialized = true;
1183
1728
  }
1184
1729
  
1185
 
  if(interface[0] != '\0'){
1186
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1187
 
    if(if_index == 0){
1188
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1189
 
      exitcode = EXIT_FAILURE;
1190
 
      goto end;
1191
 
    }
 
1730
  if(quit_now){
 
1731
    goto end;
1192
1732
  }
1193
1733
  
1194
1734
  if(connect_to != NULL){
1197
1737
    char *address = strrchr(connect_to, ':');
1198
1738
    if(address == NULL){
1199
1739
      fprintf(stderr, "No colon in address\n");
1200
 
      exitcode = EXIT_FAILURE;
1201
 
      goto end;
1202
 
    }
 
1740
      exitcode = EX_USAGE;
 
1741
      goto end;
 
1742
    }
 
1743
    
 
1744
    if(quit_now){
 
1745
      goto end;
 
1746
    }
 
1747
    
1203
1748
    uint16_t port;
1204
1749
    errno = 0;
1205
1750
    tmpmax = strtoimax(address+1, &tmp, 10);
1206
1751
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1207
1752
       or tmpmax != (uint16_t)tmpmax){
1208
1753
      fprintf(stderr, "Bad port number\n");
1209
 
      exitcode = EXIT_FAILURE;
1210
 
      goto end;
1211
 
    }
 
1754
      exitcode = EX_USAGE;
 
1755
      goto end;
 
1756
    }
 
1757
  
 
1758
    if(quit_now){
 
1759
      goto end;
 
1760
    }
 
1761
    
1212
1762
    port = (uint16_t)tmpmax;
1213
1763
    *address = '\0';
1214
1764
    address = connect_to;
1219
1769
    } else {
1220
1770
      af = AF_INET;
1221
1771
    }
1222
 
    ret = start_mandos_communication(address, port, if_index, af);
1223
 
    if(ret < 0){
1224
 
      exitcode = EXIT_FAILURE;
1225
 
    } else {
 
1772
    
 
1773
    if(quit_now){
 
1774
      goto end;
 
1775
    }
 
1776
 
 
1777
    while(not quit_now){
 
1778
      ret = start_mandos_communication(address, port, if_index, af);
 
1779
      if(quit_now or ret == 0){
 
1780
        break;
 
1781
      }
 
1782
      sleep((int)retry_interval or 1);
 
1783
    };
 
1784
 
 
1785
    if (not quit_now){
1226
1786
      exitcode = EXIT_SUCCESS;
1227
1787
    }
1228
 
    goto end;
1229
 
  }
1230
 
    
 
1788
 
 
1789
    goto end;
 
1790
  }
 
1791
  
 
1792
  if(quit_now){
 
1793
    goto end;
 
1794
  }
 
1795
  
1231
1796
  {
1232
1797
    AvahiServerConfig config;
1233
1798
    /* Do not publish any local Zeroconf records */
1250
1815
  if(mc.server == NULL){
1251
1816
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1252
1817
            avahi_strerror(error));
1253
 
    exitcode = EXIT_FAILURE;
 
1818
    exitcode = EX_UNAVAILABLE;
 
1819
    goto end;
 
1820
  }
 
1821
  
 
1822
  if(quit_now){
1254
1823
    goto end;
1255
1824
  }
1256
1825
  
1261
1830
  if(sb == NULL){
1262
1831
    fprintf(stderr, "Failed to create service browser: %s\n",
1263
1832
            avahi_strerror(avahi_server_errno(mc.server)));
1264
 
    exitcode = EXIT_FAILURE;
 
1833
    exitcode = EX_UNAVAILABLE;
 
1834
    goto end;
 
1835
  }
 
1836
  
 
1837
  if(quit_now){
1265
1838
    goto end;
1266
1839
  }
1267
1840
  
1270
1843
  if(debug){
1271
1844
    fprintf(stderr, "Starting Avahi loop search\n");
1272
1845
  }
1273
 
  
1274
 
  avahi_simple_poll_loop(mc.simple_poll);
 
1846
 
 
1847
  ret = avahi_loop_with_timeout(mc.simple_poll, (int)(retry_interval * 1000));
 
1848
  if(debug){
 
1849
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1850
            (ret == 0) ? "successfully" : "with error");
 
1851
  }
1275
1852
  
1276
1853
 end:
1277
1854
  
1298
1875
  if(gpgme_initialized){
1299
1876
    gpgme_release(mc.ctx);
1300
1877
  }
1301
 
  
1302
 
  /* Removes the temp directory used by GPGME */
 
1878
 
 
1879
  /* cleans up the circular linked list of mandos servers the client has seen */
 
1880
  if(mc.current_server != NULL){
 
1881
    mc.current_server->prev->next = NULL;
 
1882
    while(mc.current_server != NULL){
 
1883
      server *next = mc.current_server->next;
 
1884
      free(mc.current_server);
 
1885
      mc.current_server = next;
 
1886
    }
 
1887
  }
 
1888
  
 
1889
  /* Take down the network interface */
 
1890
  if(take_down_interface){
 
1891
    /* Re-raise priviliges */
 
1892
    errno = 0;
 
1893
    ret = seteuid(0);
 
1894
    if(ret == -1){
 
1895
      perror_plus("seteuid");
 
1896
    }
 
1897
    if(geteuid() == 0){
 
1898
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1899
      if(ret == -1){
 
1900
        perror_plus("ioctl SIOCGIFFLAGS");
 
1901
      } else if(network.ifr_flags & IFF_UP) {
 
1902
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1903
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1904
        if(ret == -1){
 
1905
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1906
        }
 
1907
      }
 
1908
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1909
      if(ret == -1){
 
1910
        perror_plus("close");
 
1911
      }
 
1912
      /* Lower privileges permanently */
 
1913
      errno = 0;
 
1914
      ret = setuid(uid);
 
1915
      if(ret == -1){
 
1916
        perror_plus("setuid");
 
1917
      }
 
1918
    }
 
1919
  }
 
1920
  
 
1921
  /* Removes the GPGME temp directory and all files inside */
1303
1922
  if(tempdir_created){
1304
 
    DIR *d;
1305
 
    struct dirent *direntry;
1306
 
    d = opendir(tempdir);
1307
 
    if(d == NULL){
1308
 
      if(errno != ENOENT){
1309
 
        perror("opendir");
1310
 
      }
1311
 
    } else {
1312
 
      while(true){
1313
 
        direntry = readdir(d);
1314
 
        if(direntry == NULL){
1315
 
          break;
1316
 
        }
1317
 
        /* Skip "." and ".." */
1318
 
        if(direntry->d_name[0] == '.'
1319
 
           and (direntry->d_name[1] == '\0'
1320
 
                or (direntry->d_name[1] == '.'
1321
 
                    and direntry->d_name[2] == '\0'))){
1322
 
          continue;
1323
 
        }
 
1923
    struct dirent **direntries = NULL;
 
1924
    struct dirent *direntry = NULL;
 
1925
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
 
1926
    if (ret > 0){
 
1927
      for(int i = 0; i < ret; i++){
 
1928
        direntry = direntries[i];
1324
1929
        char *fullname = NULL;
1325
1930
        ret = asprintf(&fullname, "%s/%s", tempdir,
1326
1931
                       direntry->d_name);
1327
1932
        if(ret < 0){
1328
 
          perror("asprintf");
 
1933
          perror_plus("asprintf");
1329
1934
          continue;
1330
1935
        }
1331
1936
        ret = remove(fullname);
1335
1940
        }
1336
1941
        free(fullname);
1337
1942
      }
1338
 
      closedir(d);
 
1943
    }
 
1944
 
 
1945
    /* need to be cleaned even if ret == 0 because man page dont specify */
 
1946
    free(direntries);
 
1947
    if (ret == -1){
 
1948
      perror_plus("scandir");
1339
1949
    }
1340
1950
    ret = rmdir(tempdir);
1341
1951
    if(ret == -1 and errno != ENOENT){
1342
 
      perror("rmdir");
1343
 
    }
 
1952
      perror_plus("rmdir");
 
1953
    }
 
1954
  }
 
1955
  
 
1956
  if(quit_now){
 
1957
    sigemptyset(&old_sigterm_action.sa_mask);
 
1958
    old_sigterm_action.sa_handler = SIG_DFL;
 
1959
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
 
1960
                                            &old_sigterm_action,
 
1961
                                            NULL));
 
1962
    if(ret == -1){
 
1963
      perror_plus("sigaction");
 
1964
    }
 
1965
    do {
 
1966
      ret = raise(signal_received);
 
1967
    } while(ret != 0 and errno == EINTR);
 
1968
    if(ret != 0){
 
1969
      perror_plus("raise");
 
1970
      abort();
 
1971
    }
 
1972
    TEMP_FAILURE_RETRY(pause());
1344
1973
  }
1345
1974
  
1346
1975
  return exitcode;