/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

merge

Show diffs side-by-side

added added

removed removed

Lines of Context:
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
33
 
#ifndef _LARGEFILE_SOURCE
34
33
#define _LARGEFILE_SOURCE
35
 
#endif
36
 
#ifndef _FILE_OFFSET_BITS
37
34
#define _FILE_OFFSET_BITS 64
38
 
#endif
39
35
 
40
36
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
37
 
42
38
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror(), remove() */
 
39
                                   stdout, ferror(), sscanf(),
 
40
                                   remove() */
44
41
#include <stdint.h>             /* uint16_t, uint32_t */
45
42
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
 
                                   strtof(), abort() */
 
43
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
 
44
                                   srand() */
48
45
#include <stdbool.h>            /* bool, false, true */
49
46
#include <string.h>             /* memset(), strcmp(), strlen(),
50
47
                                   strerror(), asprintf(), strcpy() */
59
56
#include <fcntl.h>              /* open() */
60
57
#include <dirent.h>             /* opendir(), struct dirent, readdir()
61
58
                                 */
62
 
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
 
                                   strtoimax() */
 
59
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
64
60
#include <assert.h>             /* assert() */
65
61
#include <errno.h>              /* perror(), errno */
66
62
#include <time.h>               /* nanosleep(), time() */
71
67
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
72
68
                                */
73
69
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
 
                                   getuid(), getgid(), seteuid(),
75
 
                                   setgid(), pause() */
 
70
                                   getuid(), getgid(), setuid(),
 
71
                                   setgid() */
76
72
#include <arpa/inet.h>          /* inet_pton(), htons */
77
73
#include <iso646.h>             /* not, or, and */
78
74
#include <argp.h>               /* struct argp_option, error_t, struct
80
76
                                   argp_parse(), ARGP_KEY_ARG,
81
77
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
82
78
#include <signal.h>             /* sigemptyset(), sigaddset(),
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 */
 
79
                                   sigaction(), SIGTERM, sigaction,
 
80
                                   sig_atomic_t */
87
81
 
88
82
#ifdef __linux__
89
83
#include <sys/klog.h>           /* klogctl() */
144
138
                      .dh_bits = 1024, .priority = "SECURE256"
145
139
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
146
140
 
147
 
sig_atomic_t quit_now = 0;
148
 
int signal_received = 0;
149
 
 
150
141
/*
151
142
 * Make additional room in "buffer" for at least BUFFER_SIZE more
152
143
 * bytes. "buffer_capacity" is how much is currently allocated,
169
160
 */
170
161
static bool init_gpgme(const char *seckey,
171
162
                       const char *pubkey, const char *tempdir){
 
163
  int ret;
172
164
  gpgme_error_t rc;
173
165
  gpgme_engine_info_t engine_info;
174
166
  
177
169
   * Helper function to insert pub and seckey to the engine keyring.
178
170
   */
179
171
  bool import_key(const char *filename){
180
 
    int ret;
181
172
    int fd;
182
173
    gpgme_data_t pgp_data;
183
174
    
254
245
    return false;
255
246
  }
256
247
  
257
 
  return true;
 
248
  return true; 
258
249
}
259
250
 
260
251
/* 
314
305
        }
315
306
        gpgme_recipient_t recipient;
316
307
        recipient = result->recipients;
317
 
        while(recipient != NULL){
318
 
          fprintf(stderr, "Public key algorithm: %s\n",
319
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
320
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
321
 
          fprintf(stderr, "Secret key available: %s\n",
322
 
                  recipient->status == GPG_ERR_NO_SECKEY
323
 
                  ? "No" : "Yes");
324
 
          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
          }
325
318
        }
326
319
      }
327
320
    }
479
472
static int init_gnutls_session(gnutls_session_t *session){
480
473
  int ret;
481
474
  /* GnuTLS session creation */
482
 
  do {
483
 
    ret = gnutls_init(session, GNUTLS_SERVER);
484
 
    if(quit_now){
485
 
      return -1;
486
 
    }
487
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
475
  ret = gnutls_init(session, GNUTLS_SERVER);
488
476
  if(ret != GNUTLS_E_SUCCESS){
489
477
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
490
478
            safer_gnutls_strerror(ret));
492
480
  
493
481
  {
494
482
    const char *err;
495
 
    do {
496
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
497
 
      if(quit_now){
498
 
        gnutls_deinit(*session);
499
 
        return -1;
500
 
      }
501
 
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
483
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
502
484
    if(ret != GNUTLS_E_SUCCESS){
503
485
      fprintf(stderr, "Syntax error at: %s\n", err);
504
486
      fprintf(stderr, "GnuTLS error: %s\n",
508
490
    }
509
491
  }
510
492
  
511
 
  do {
512
 
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
513
 
                                 mc.cred);
514
 
    if(quit_now){
515
 
      gnutls_deinit(*session);
516
 
      return -1;
517
 
    }
518
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
493
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
494
                               mc.cred);
519
495
  if(ret != GNUTLS_E_SUCCESS){
520
496
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
521
497
            safer_gnutls_strerror(ret));
524
500
  }
525
501
  
526
502
  /* ignore client certificate if any. */
527
 
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
 
503
  gnutls_certificate_server_set_request(*session,
 
504
                                        GNUTLS_CERT_IGNORE);
528
505
  
529
506
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
530
507
  
539
516
static int start_mandos_communication(const char *ip, uint16_t port,
540
517
                                      AvahiIfIndex if_index,
541
518
                                      int af){
542
 
  int ret, tcp_sd = -1;
 
519
  int ret, tcp_sd;
543
520
  ssize_t sret;
544
521
  union {
545
522
    struct sockaddr_in in;
546
523
    struct sockaddr_in6 in6;
547
524
  } to;
548
525
  char *buffer = NULL;
549
 
  char *decrypted_buffer = NULL;
 
526
  char *decrypted_buffer;
550
527
  size_t buffer_length = 0;
551
528
  size_t buffer_capacity = 0;
 
529
  ssize_t decrypted_buffer_size;
552
530
  size_t written;
553
 
  int retval = -1;
 
531
  int retval = 0;
554
532
  gnutls_session_t session;
555
533
  int pf;                       /* Protocol family */
556
534
  
557
 
  errno = 0;
558
 
  
559
 
  if(quit_now){
560
 
    errno = EINTR;
561
 
    return -1;
562
 
  }
563
 
  
564
535
  switch(af){
565
536
  case AF_INET6:
566
537
    pf = PF_INET6;
570
541
    break;
571
542
  default:
572
543
    fprintf(stderr, "Bad address family: %d\n", af);
573
 
    errno = EINVAL;
574
544
    return -1;
575
545
  }
576
546
  
586
556
  
587
557
  tcp_sd = socket(pf, SOCK_STREAM, 0);
588
558
  if(tcp_sd < 0){
589
 
    int e = errno;
590
559
    perror("socket");
591
 
    errno = e;
592
 
    goto mandos_end;
593
 
  }
594
 
  
595
 
  if(quit_now){
596
 
    errno = EINTR;
597
 
    goto mandos_end;
 
560
    return -1;
598
561
  }
599
562
  
600
563
  memset(&to, 0, sizeof(to));
601
564
  if(af == AF_INET6){
602
 
    to.in6.sin6_family = (sa_family_t)af;
 
565
    to.in6.sin6_family = (uint16_t)af;
603
566
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
604
567
  } else {                      /* IPv4 */
605
568
    to.in.sin_family = (sa_family_t)af;
606
569
    ret = inet_pton(af, ip, &to.in.sin_addr);
607
570
  }
608
571
  if(ret < 0 ){
609
 
    int e = errno;
610
572
    perror("inet_pton");
611
 
    errno = e;
612
 
    goto mandos_end;
 
573
    return -1;
613
574
  }
614
575
  if(ret == 0){
615
 
    int e = errno;
616
576
    fprintf(stderr, "Bad address: %s\n", ip);
617
 
    errno = e;
618
 
    goto mandos_end;
 
577
    return -1;
619
578
  }
620
579
  if(af == AF_INET6){
621
580
    to.in6.sin6_port = htons(port); /* Spurious warnings from
628
587
      if(if_index == AVAHI_IF_UNSPEC){
629
588
        fprintf(stderr, "An IPv6 link-local address is incomplete"
630
589
                " without a network interface\n");
631
 
        errno = EINVAL;
632
 
        goto mandos_end;
 
590
        return -1;
633
591
      }
634
592
      /* Set the network interface number as scope */
635
593
      to.in6.sin6_scope_id = (uint32_t)if_index;
640
598
                                     -Wunreachable-code */
641
599
  }
642
600
  
643
 
  if(quit_now){
644
 
    errno = EINTR;
645
 
    goto mandos_end;
646
 
  }
647
 
  
648
601
  if(debug){
649
602
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
650
603
      char interface[IF_NAMESIZE];
677
630
    }
678
631
  }
679
632
  
680
 
  if(quit_now){
681
 
    errno = EINTR;
682
 
    goto mandos_end;
683
 
  }
684
 
  
685
633
  if(af == AF_INET6){
686
634
    ret = connect(tcp_sd, &to.in6, sizeof(to));
687
635
  } else {
688
636
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
689
637
  }
690
638
  if(ret < 0){
691
 
    int e = errno;
692
639
    perror("connect");
693
 
    errno = e;
694
 
    goto mandos_end;
695
 
  }
696
 
  
697
 
  if(quit_now){
698
 
    errno = EINTR;
699
 
    goto mandos_end;
 
640
    return -1;
700
641
  }
701
642
  
702
643
  const char *out = mandos_protocol_version;
706
647
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
707
648
                                   out_size - written));
708
649
    if(ret == -1){
709
 
      int e = errno;
710
650
      perror("write");
711
 
      errno = e;
 
651
      retval = -1;
712
652
      goto mandos_end;
713
653
    }
714
654
    written += (size_t)ret;
722
662
        break;
723
663
      }
724
664
    }
725
 
  
726
 
    if(quit_now){
727
 
      errno = EINTR;
728
 
      goto mandos_end;
729
 
    }
730
665
  }
731
666
  
732
667
  if(debug){
733
668
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
734
669
  }
735
670
  
736
 
  if(quit_now){
737
 
    errno = EINTR;
738
 
    goto mandos_end;
739
 
  }
740
 
  
741
671
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
742
672
  
743
 
  if(quit_now){
744
 
    errno = EINTR;
745
 
    goto mandos_end;
746
 
  }
747
 
  
748
 
  do {
 
673
  do{
749
674
    ret = gnutls_handshake(session);
750
 
    if(quit_now){
751
 
      errno = EINTR;
752
 
      goto mandos_end;
753
 
    }
754
675
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
755
676
  
756
677
  if(ret != GNUTLS_E_SUCCESS){
758
679
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
759
680
      gnutls_perror(ret);
760
681
    }
761
 
    errno = EPROTO;
 
682
    retval = -1;
762
683
    goto mandos_end;
763
684
  }
764
685
  
770
691
  }
771
692
  
772
693
  while(true){
773
 
    
774
 
    if(quit_now){
775
 
      errno = EINTR;
776
 
      goto mandos_end;
777
 
    }
778
 
    
779
694
    buffer_capacity = incbuffer(&buffer, buffer_length,
780
695
                                   buffer_capacity);
781
696
    if(buffer_capacity == 0){
782
 
      int e = errno;
783
697
      perror("incbuffer");
784
 
      errno = e;
785
 
      goto mandos_end;
786
 
    }
787
 
    
788
 
    if(quit_now){
789
 
      errno = EINTR;
 
698
      retval = -1;
790
699
      goto mandos_end;
791
700
    }
792
701
    
801
710
      case GNUTLS_E_AGAIN:
802
711
        break;
803
712
      case GNUTLS_E_REHANDSHAKE:
804
 
        do {
 
713
        do{
805
714
          ret = gnutls_handshake(session);
806
 
          
807
 
          if(quit_now){
808
 
            errno = EINTR;
809
 
            goto mandos_end;
810
 
          }
811
715
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
812
716
        if(ret < 0){
813
717
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
814
718
          gnutls_perror(ret);
815
 
          errno = EPROTO;
 
719
          retval = -1;
816
720
          goto mandos_end;
817
721
        }
818
722
        break;
819
723
      default:
820
724
        fprintf(stderr, "Unknown error while reading data from"
821
725
                " encrypted session with Mandos server\n");
 
726
        retval = -1;
822
727
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
823
 
        errno = EIO;
824
728
        goto mandos_end;
825
729
      }
826
730
    } else {
832
736
    fprintf(stderr, "Closing TLS session\n");
833
737
  }
834
738
  
835
 
  if(quit_now){
836
 
    errno = EINTR;
837
 
    goto mandos_end;
838
 
  }
839
 
  
840
 
  do {
841
 
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
842
 
    if(quit_now){
843
 
      errno = EINTR;
844
 
      goto mandos_end;
845
 
    }
846
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
 
739
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
847
740
  
848
741
  if(buffer_length > 0){
849
 
    ssize_t decrypted_buffer_size;
850
742
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
851
743
                                               buffer_length,
852
744
                                               &decrypted_buffer);
853
745
    if(decrypted_buffer_size >= 0){
854
 
      
855
746
      written = 0;
856
747
      while(written < (size_t) decrypted_buffer_size){
857
 
        if(quit_now){
858
 
          errno = EINTR;
859
 
          goto mandos_end;
860
 
        }
861
 
        
862
748
        ret = (int)fwrite(decrypted_buffer + written, 1,
863
749
                          (size_t)decrypted_buffer_size - written,
864
750
                          stdout);
865
751
        if(ret == 0 and ferror(stdout)){
866
 
          int e = errno;
867
752
          if(debug){
868
753
            fprintf(stderr, "Error writing encrypted data: %s\n",
869
754
                    strerror(errno));
870
755
          }
871
 
          errno = e;
872
 
          goto mandos_end;
 
756
          retval = -1;
 
757
          break;
873
758
        }
874
759
        written += (size_t)ret;
875
760
      }
876
 
      retval = 0;
 
761
      free(decrypted_buffer);
 
762
    } else {
 
763
      retval = -1;
877
764
    }
 
765
  } else {
 
766
    retval = -1;
878
767
  }
879
768
  
880
769
  /* Shutdown procedure */
881
770
  
882
771
 mandos_end:
883
 
  {
884
 
    int e = errno;
885
 
    free(decrypted_buffer);
886
 
    free(buffer);
887
 
    if(tcp_sd >= 0){
888
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
889
 
    }
890
 
    if(ret == -1){
891
 
      if(e == 0){
892
 
        e = errno;
893
 
      }
894
 
      perror("close");
895
 
    }
896
 
    gnutls_deinit(session);
897
 
    if(quit_now){
898
 
      e = EINTR;
899
 
      retval = -1;
900
 
    }
901
 
    errno = e;
 
772
  free(buffer);
 
773
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
774
  if(ret == -1){
 
775
    perror("close");
902
776
  }
 
777
  gnutls_deinit(session);
903
778
  return retval;
904
779
}
905
780
 
922
797
  /* Called whenever a service has been resolved successfully or
923
798
     timed out */
924
799
  
925
 
  if(quit_now){
926
 
    return;
927
 
  }
928
 
  
929
800
  switch(event){
930
801
  default:
931
802
  case AVAHI_RESOLVER_FAILURE:
968
839
  /* Called whenever a new services becomes available on the LAN or
969
840
     is removed from the LAN */
970
841
  
971
 
  if(quit_now){
972
 
    return;
973
 
  }
974
 
  
975
842
  switch(event){
976
843
  default:
977
844
  case AVAHI_BROWSER_FAILURE:
987
854
       the callback function is called the Avahi server will free the
988
855
       resolver for us. */
989
856
    
990
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
991
 
                                    name, type, domain, protocol, 0,
992
 
                                    resolve_callback, NULL) == NULL)
 
857
    if(!(avahi_s_service_resolver_new(mc.server, interface,
 
858
                                       protocol, name, type, domain,
 
859
                                       AVAHI_PROTO_INET6, 0,
 
860
                                       resolve_callback, NULL)))
993
861
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
994
862
              name, avahi_strerror(avahi_server_errno(mc.server)));
995
863
    break;
1006
874
  }
1007
875
}
1008
876
 
 
877
sig_atomic_t quit_now = 0;
 
878
 
1009
879
/* stop main loop after sigterm has been called */
1010
 
static void handle_sigterm(int sig){
 
880
static void handle_sigterm(__attribute__((unused)) int sig){
1011
881
  if(quit_now){
1012
882
    return;
1013
883
  }
1014
884
  quit_now = 1;
1015
 
  signal_received = sig;
1016
885
  int old_errno = errno;
1017
886
  if(mc.simple_poll != NULL){
1018
887
    avahi_simple_poll_quit(mc.simple_poll);
1025
894
  int error;
1026
895
  int ret;
1027
896
  intmax_t tmpmax;
1028
 
  char *tmp;
 
897
  int numchars;
1029
898
  int exitcode = EXIT_SUCCESS;
1030
899
  const char *interface = "eth0";
1031
900
  struct ifreq network;
1032
 
  int sd = -1;
1033
 
  bool take_down_interface = false;
 
901
  int sd;
1034
902
  uid_t uid;
1035
903
  gid_t gid;
1036
904
  char *connect_to = NULL;
1040
908
  const char *seckey = PATHDIR "/" SECKEY;
1041
909
  const char *pubkey = PATHDIR "/" PUBKEY;
1042
910
  
 
911
  /* Initialize Mandos context */
 
912
  mc = (mandos_context){ .simple_poll = NULL, .server = NULL,
 
913
                         .dh_bits = 1024, .priority = "SECURE256"
 
914
                         ":!CTYPE-X.509:+CTYPE-OPENPGP" };
1043
915
  bool gnutls_initialized = false;
1044
916
  bool gpgme_initialized = false;
1045
 
  float delay = 2.5f;
1046
 
  
1047
 
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
 
917
  double delay = 2.5;
 
918
 
 
919
  struct sigaction old_sigterm_action;
1048
920
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1049
921
  
1050
 
  uid = getuid();
1051
 
  gid = getgid();
1052
 
  
1053
 
  /* Lower any group privileges we might have, just to be safe */
1054
 
  errno = 0;
1055
 
  ret = setgid(gid);
1056
 
  if(ret == -1){
1057
 
    perror("setgid");
1058
 
  }
1059
 
  
1060
 
  /* Lower user privileges (temporarily) */
1061
 
  errno = 0;
1062
 
  ret = seteuid(uid);
1063
 
  if(ret == -1){
1064
 
    perror("seteuid");
1065
 
  }
1066
 
  
1067
 
  if(quit_now){
1068
 
    goto end;
1069
 
  }
1070
 
  
1071
922
  {
1072
923
    struct argp_option options[] = {
1073
924
      { .name = "debug", .key = 128,
1102
953
        .arg = "SECONDS",
1103
954
        .doc = "Maximum delay to wait for interface startup",
1104
955
        .group = 2 },
1105
 
      /*
1106
 
       * These reproduce what we would get without ARGP_NO_HELP
1107
 
       */
1108
 
      { .name = "help", .key = '?',
1109
 
        .doc = "Give this help list", .group = -1 },
1110
 
      { .name = "usage", .key = -3,
1111
 
        .doc = "Give a short usage message", .group = -1 },
1112
 
      { .name = "version", .key = 'V',
1113
 
        .doc = "Print program version", .group = -1 },
1114
956
      { .name = NULL }
1115
957
    };
1116
958
    
1117
959
    error_t parse_opt(int key, char *arg,
1118
960
                      struct argp_state *state){
1119
 
      errno = 0;
1120
961
      switch(key){
1121
962
      case 128:                 /* --debug */
1122
963
        debug = true;
1134
975
        pubkey = arg;
1135
976
        break;
1136
977
      case 129:                 /* --dh-bits */
1137
 
        errno = 0;
1138
 
        tmpmax = strtoimax(arg, &tmp, 10);
1139
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1140
 
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1141
 
          argp_error(state, "Bad number of DH bits");
 
978
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
979
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
 
980
           or arg[numchars] != '\0'){
 
981
          fprintf(stderr, "Bad number of DH bits\n");
 
982
          exit(EXIT_FAILURE);
1142
983
        }
1143
984
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1144
985
        break;
1146
987
        mc.priority = arg;
1147
988
        break;
1148
989
      case 131:                 /* --delay */
1149
 
        errno = 0;
1150
 
        delay = strtof(arg, &tmp);
1151
 
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1152
 
          argp_error(state, "Bad delay");
 
990
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
 
991
        if(ret < 1 or arg[numchars] != '\0'){
 
992
          fprintf(stderr, "Bad delay\n");
 
993
          exit(EXIT_FAILURE);
1153
994
        }
1154
995
        break;
1155
 
        /*
1156
 
         * These reproduce what we would get without ARGP_NO_HELP
1157
 
         */
1158
 
      case '?':                 /* --help */
1159
 
        argp_state_help(state, state->out_stream,
1160
 
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
1161
 
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
1162
 
      case -3:                  /* --usage */
1163
 
        argp_state_help(state, state->out_stream,
1164
 
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1165
 
      case 'V':                 /* --version */
1166
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
1167
 
        exit(argp_err_exit_status);
 
996
      case ARGP_KEY_ARG:
 
997
        argp_usage(state);
 
998
      case ARGP_KEY_END:
1168
999
        break;
1169
1000
      default:
1170
1001
        return ARGP_ERR_UNKNOWN;
1171
1002
      }
1172
 
      return errno;
 
1003
      return 0;
1173
1004
    }
1174
1005
    
1175
1006
    struct argp argp = { .options = options, .parser = parse_opt,
1176
1007
                         .args_doc = "",
1177
1008
                         .doc = "Mandos client -- Get and decrypt"
1178
1009
                         " passwords from a Mandos server" };
1179
 
    ret = argp_parse(&argp, argc, argv,
1180
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
1181
 
    switch(ret){
1182
 
    case 0:
1183
 
      break;
1184
 
    case ENOMEM:
1185
 
    default:
1186
 
      errno = ret;
1187
 
      perror("argp_parse");
1188
 
      exitcode = EX_OSERR;
1189
 
      goto end;
1190
 
    case EINVAL:
1191
 
      exitcode = EX_USAGE;
 
1010
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
1011
    if(ret == ARGP_ERR_UNKNOWN){
 
1012
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1013
      exitcode = EXIT_FAILURE;
1192
1014
      goto end;
1193
1015
    }
1194
1016
  }
1204
1026
  mc.simple_poll = avahi_simple_poll_new();
1205
1027
  if(mc.simple_poll == NULL){
1206
1028
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1207
 
    exitcode = EX_UNAVAILABLE;
 
1029
    exitcode = EXIT_FAILURE;
1208
1030
    goto end;
1209
1031
  }
1210
1032
  
1212
1034
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1213
1035
  if(ret == -1){
1214
1036
    perror("sigaddset");
1215
 
    exitcode = EX_OSERR;
 
1037
    exitcode = EXIT_FAILURE;
1216
1038
    goto end;
1217
1039
  }
1218
1040
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1219
1041
  if(ret == -1){
1220
1042
    perror("sigaddset");
1221
 
    exitcode = EX_OSERR;
 
1043
    exitcode = EXIT_FAILURE;
1222
1044
    goto end;
1223
1045
  }
1224
1046
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1225
1047
  if(ret == -1){
1226
1048
    perror("sigaddset");
1227
 
    exitcode = EX_OSERR;
1228
 
    goto end;
1229
 
  }
1230
 
  /* Need to check if the handler is SIG_IGN before handling:
1231
 
     | [[info:libc:Initial Signal Actions]] |
1232
 
     | [[info:libc:Basic Signal Handling]]  |
1233
 
  */
1234
 
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1235
 
  if(ret == -1){
1236
 
    perror("sigaction");
1237
 
    return EX_OSERR;
1238
 
  }
1239
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1240
 
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1241
 
    if(ret == -1){
1242
 
      perror("sigaction");
1243
 
      exitcode = EX_OSERR;
1244
 
      goto end;
1245
 
    }
1246
 
  }
1247
 
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1248
 
  if(ret == -1){
1249
 
    perror("sigaction");
1250
 
    return EX_OSERR;
1251
 
  }
1252
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1253
 
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1254
 
    if(ret == -1){
1255
 
      perror("sigaction");
1256
 
      exitcode = EX_OSERR;
1257
 
      goto end;
1258
 
    }
1259
 
  }
1260
 
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1261
 
  if(ret == -1){
1262
 
    perror("sigaction");
1263
 
    return EX_OSERR;
1264
 
  }
1265
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1266
 
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1267
 
    if(ret == -1){
1268
 
      perror("sigaction");
1269
 
      exitcode = EX_OSERR;
1270
 
      goto end;
1271
 
    }
1272
 
  }
 
1049
    exitcode = EXIT_FAILURE;
 
1050
    goto end;
 
1051
  }
 
1052
  ret = sigaction(SIGTERM, &sigterm_action, &old_sigterm_action);
 
1053
  if(ret == -1){
 
1054
    perror("sigaction");
 
1055
    exitcode = EXIT_FAILURE;
 
1056
    goto end;
 
1057
  }  
1273
1058
  
1274
1059
  /* If the interface is down, bring it up */
1275
1060
  if(interface[0] != '\0'){
1276
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1277
 
    if(if_index == 0){
1278
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1279
 
      exitcode = EX_UNAVAILABLE;
1280
 
      goto end;
1281
 
    }
1282
 
    
1283
 
    if(quit_now){
1284
 
      goto end;
1285
 
    }
1286
 
    
1287
 
    /* Re-raise priviliges */
1288
 
    errno = 0;
1289
 
    ret = seteuid(0);
1290
 
    if(ret == -1){
1291
 
      perror("seteuid");
1292
 
    }
1293
 
    
1294
1061
#ifdef __linux__
1295
1062
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1296
 
       messages about the network interface to mess up the prompt */
 
1063
       messages to mess up the prompt */
1297
1064
    ret = klogctl(8, NULL, 5);
1298
1065
    bool restore_loglevel = true;
1299
1066
    if(ret == -1){
1305
1072
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1306
1073
    if(sd < 0){
1307
1074
      perror("socket");
1308
 
      exitcode = EX_OSERR;
 
1075
      exitcode = EXIT_FAILURE;
1309
1076
#ifdef __linux__
1310
1077
      if(restore_loglevel){
1311
1078
        ret = klogctl(7, NULL, 0);
1314
1081
        }
1315
1082
      }
1316
1083
#endif  /* __linux__ */
1317
 
      /* Lower privileges */
1318
 
      errno = 0;
1319
 
      ret = seteuid(uid);
1320
 
      if(ret == -1){
1321
 
        perror("seteuid");
1322
 
      }
1323
1084
      goto end;
1324
1085
    }
1325
1086
    strcpy(network.ifr_name, interface);
1334
1095
        }
1335
1096
      }
1336
1097
#endif  /* __linux__ */
1337
 
      exitcode = EX_OSERR;
1338
 
      /* Lower privileges */
1339
 
      errno = 0;
1340
 
      ret = seteuid(uid);
1341
 
      if(ret == -1){
1342
 
        perror("seteuid");
1343
 
      }
 
1098
      exitcode = EXIT_FAILURE;
1344
1099
      goto end;
1345
1100
    }
1346
1101
    if((network.ifr_flags & IFF_UP) == 0){
1347
1102
      network.ifr_flags |= IFF_UP;
1348
 
      take_down_interface = true;
1349
1103
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1350
1104
      if(ret == -1){
1351
 
        take_down_interface = false;
1352
1105
        perror("ioctl SIOCSIFFLAGS");
1353
 
        exitcode = EX_OSERR;
 
1106
        exitcode = EXIT_FAILURE;
1354
1107
#ifdef __linux__
1355
1108
        if(restore_loglevel){
1356
1109
          ret = klogctl(7, NULL, 0);
1359
1112
          }
1360
1113
        }
1361
1114
#endif  /* __linux__ */
1362
 
        /* Lower privileges */
1363
 
        errno = 0;
1364
 
        ret = seteuid(uid);
1365
 
        if(ret == -1){
1366
 
          perror("seteuid");
1367
 
        }
1368
1115
        goto end;
1369
1116
      }
1370
1117
    }
1382
1129
        perror("nanosleep");
1383
1130
      }
1384
1131
    }
1385
 
    if(not take_down_interface){
1386
 
      /* We won't need the socket anymore */
1387
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1388
 
      if(ret == -1){
1389
 
        perror("close");
1390
 
      }
 
1132
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1133
    if(ret == -1){
 
1134
      perror("close");
1391
1135
    }
1392
1136
#ifdef __linux__
1393
1137
    if(restore_loglevel){
1398
1142
      }
1399
1143
    }
1400
1144
#endif  /* __linux__ */
1401
 
    /* Lower privileges */
1402
 
    errno = 0;
1403
 
    if(take_down_interface){
1404
 
      /* Lower privileges */
1405
 
      ret = seteuid(uid);
1406
 
      if(ret == -1){
1407
 
        perror("seteuid");
1408
 
      }
1409
 
    } else {
1410
 
      /* Lower privileges permanently */
1411
 
      ret = setuid(uid);
1412
 
      if(ret == -1){
1413
 
        perror("setuid");
1414
 
      }
1415
 
    }
1416
 
  }
1417
 
  
1418
 
  if(quit_now){
1419
 
    goto end;
 
1145
  }
 
1146
  
 
1147
  uid = getuid();
 
1148
  gid = getgid();
 
1149
  
 
1150
  errno = 0;
 
1151
  setgid(gid);
 
1152
  if(ret == -1){
 
1153
    perror("setgid");
 
1154
  }
 
1155
  
 
1156
  ret = setuid(uid);
 
1157
  if(ret == -1){
 
1158
    perror("setuid");
1420
1159
  }
1421
1160
  
1422
1161
  ret = init_gnutls_global(pubkey, seckey);
1423
1162
  if(ret == -1){
1424
1163
    fprintf(stderr, "init_gnutls_global failed\n");
1425
 
    exitcode = EX_UNAVAILABLE;
 
1164
    exitcode = EXIT_FAILURE;
1426
1165
    goto end;
1427
1166
  } else {
1428
1167
    gnutls_initialized = true;
1429
1168
  }
1430
1169
  
1431
 
  if(quit_now){
1432
 
    goto end;
1433
 
  }
1434
 
  
1435
 
  tempdir_created = true;
1436
1170
  if(mkdtemp(tempdir) == NULL){
1437
 
    tempdir_created = false;
1438
1171
    perror("mkdtemp");
1439
1172
    goto end;
1440
1173
  }
1441
 
  
1442
 
  if(quit_now){
1443
 
    goto end;
1444
 
  }
 
1174
  tempdir_created = true;
1445
1175
  
1446
1176
  if(not init_gpgme(pubkey, seckey, tempdir)){
1447
1177
    fprintf(stderr, "init_gpgme failed\n");
1448
 
    exitcode = EX_UNAVAILABLE;
 
1178
    exitcode = EXIT_FAILURE;
1449
1179
    goto end;
1450
1180
  } else {
1451
1181
    gpgme_initialized = true;
1452
1182
  }
1453
1183
  
1454
 
  if(quit_now){
1455
 
    goto end;
 
1184
  if(interface[0] != '\0'){
 
1185
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1186
    if(if_index == 0){
 
1187
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1188
      exitcode = EXIT_FAILURE;
 
1189
      goto end;
 
1190
    }
1456
1191
  }
1457
1192
  
1458
1193
  if(connect_to != NULL){
1461
1196
    char *address = strrchr(connect_to, ':');
1462
1197
    if(address == NULL){
1463
1198
      fprintf(stderr, "No colon in address\n");
1464
 
      exitcode = EX_USAGE;
1465
 
      goto end;
1466
 
    }
1467
 
    
1468
 
    if(quit_now){
1469
 
      goto end;
1470
 
    }
1471
 
    
 
1199
      exitcode = EXIT_FAILURE;
 
1200
      goto end;
 
1201
    }
1472
1202
    uint16_t port;
1473
 
    errno = 0;
1474
 
    tmpmax = strtoimax(address+1, &tmp, 10);
1475
 
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1476
 
       or tmpmax != (uint16_t)tmpmax){
 
1203
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
1204
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
 
1205
       or address[numchars+1] != '\0'){
1477
1206
      fprintf(stderr, "Bad port number\n");
1478
 
      exitcode = EX_USAGE;
1479
 
      goto end;
1480
 
    }
1481
 
  
1482
 
    if(quit_now){
1483
 
      goto end;
1484
 
    }
1485
 
    
 
1207
      exitcode = EXIT_FAILURE;
 
1208
      goto end;
 
1209
    }
1486
1210
    port = (uint16_t)tmpmax;
1487
1211
    *address = '\0';
1488
1212
    address = connect_to;
1493
1217
    } else {
1494
1218
      af = AF_INET;
1495
1219
    }
1496
 
    
1497
 
    if(quit_now){
1498
 
      goto end;
1499
 
    }
1500
 
    
1501
1220
    ret = start_mandos_communication(address, port, if_index, af);
1502
1221
    if(ret < 0){
1503
 
      switch(errno){
1504
 
      case ENETUNREACH:
1505
 
      case EHOSTDOWN:
1506
 
      case EHOSTUNREACH:
1507
 
        exitcode = EX_NOHOST;
1508
 
        break;
1509
 
      case EINVAL:
1510
 
        exitcode = EX_USAGE;
1511
 
        break;
1512
 
      case EIO:
1513
 
        exitcode = EX_IOERR;
1514
 
        break;
1515
 
      case EPROTO:
1516
 
        exitcode = EX_PROTOCOL;
1517
 
        break;
1518
 
      default:
1519
 
        exitcode = EX_OSERR;
1520
 
        break;
1521
 
      }
 
1222
      exitcode = EXIT_FAILURE;
1522
1223
    } else {
1523
1224
      exitcode = EXIT_SUCCESS;
1524
1225
    }
1525
1226
    goto end;
1526
1227
  }
1527
 
  
1528
 
  if(quit_now){
1529
 
    goto end;
1530
 
  }
1531
 
  
 
1228
    
1532
1229
  {
1533
1230
    AvahiServerConfig config;
1534
1231
    /* Do not publish any local Zeroconf records */
1551
1248
  if(mc.server == NULL){
1552
1249
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1553
1250
            avahi_strerror(error));
1554
 
    exitcode = EX_UNAVAILABLE;
1555
 
    goto end;
1556
 
  }
1557
 
  
1558
 
  if(quit_now){
 
1251
    exitcode = EXIT_FAILURE;
1559
1252
    goto end;
1560
1253
  }
1561
1254
  
1562
1255
  /* Create the Avahi service browser */
1563
1256
  sb = avahi_s_service_browser_new(mc.server, if_index,
1564
 
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
 
1257
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
1565
1258
                                   NULL, 0, browse_callback, NULL);
1566
1259
  if(sb == NULL){
1567
1260
    fprintf(stderr, "Failed to create service browser: %s\n",
1568
1261
            avahi_strerror(avahi_server_errno(mc.server)));
1569
 
    exitcode = EX_UNAVAILABLE;
1570
 
    goto end;
1571
 
  }
1572
 
  
1573
 
  if(quit_now){
 
1262
    exitcode = EXIT_FAILURE;
1574
1263
    goto end;
1575
1264
  }
1576
1265
  
1608
1297
    gpgme_release(mc.ctx);
1609
1298
  }
1610
1299
  
1611
 
  /* Take down the network interface */
1612
 
  if(take_down_interface){
1613
 
    /* Re-raise priviliges */
1614
 
    errno = 0;
1615
 
    ret = seteuid(0);
1616
 
    if(ret == -1){
1617
 
      perror("seteuid");
1618
 
    }
1619
 
    if(geteuid() == 0){
1620
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1621
 
      if(ret == -1){
1622
 
        perror("ioctl SIOCGIFFLAGS");
1623
 
      } else if(network.ifr_flags & IFF_UP) {
1624
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1625
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1626
 
        if(ret == -1){
1627
 
          perror("ioctl SIOCSIFFLAGS");
1628
 
        }
1629
 
      }
1630
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1631
 
      if(ret == -1){
1632
 
        perror("close");
1633
 
      }
1634
 
      /* Lower privileges permanently */
1635
 
      errno = 0;
1636
 
      ret = setuid(uid);
1637
 
      if(ret == -1){
1638
 
        perror("setuid");
1639
 
      }
1640
 
    }
1641
 
  }
1642
 
  
1643
1300
  /* Removes the temp directory used by GPGME */
1644
1301
  if(tempdir_created){
1645
1302
    DIR *d;
1684
1341
    }
1685
1342
  }
1686
1343
  
1687
 
  if(quit_now){
1688
 
    sigemptyset(&old_sigterm_action.sa_mask);
1689
 
    old_sigterm_action.sa_handler = SIG_DFL;
1690
 
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
1691
 
                                            &old_sigterm_action,
1692
 
                                            NULL));
1693
 
    if(ret == -1){
1694
 
      perror("sigaction");
1695
 
    }
1696
 
    do {
1697
 
      ret = raise(signal_received);
1698
 
    } while(ret != 0 and errno == EINTR);
1699
 
    if(ret != 0){
1700
 
      perror("raise");
1701
 
      abort();
1702
 
    }
1703
 
    TEMP_FAILURE_RETRY(pause());
1704
 
  }
1705
 
  
1706
1344
  return exitcode;
1707
1345
}