/mandos/release

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

« back to all changes in this revision

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

* Makefile (plugins.d/mandos-client): Bug fix: Put $^ before all
                                      libraries.  Remove "$(COMMON)".
                                      Thanks to Angel Abad
                                      <angelabad@ubuntu.com>.
* initramfs-tools-script: Work around change in initramfs-tools,
                          Debian bug #633582.
* plugins.d/mandos-client.c (init_gnutls_global): Bug fix: check for
                errors from gnutls_certificate_allocate_credentials().

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() */
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
65
#include <errno.h>              /* perror(), errno */
66
 
#include <time.h>               /* nanosleep(), time() */
 
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() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
74
                                   getuid(), getgid(), seteuid(),
 
75
                                   setgid(), pause() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
77
77
#include <iso646.h>             /* not, or, and */
78
78
#include <argp.h>               /* struct argp_option, error_t, struct
79
79
                                   argp_state, struct argp,
82
82
#include <signal.h>             /* sigemptyset(), sigaddset(),
83
83
                                   sigaction(), SIGTERM, sig_atomic_t,
84
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;
128
132
 
129
133
/* Used for passing in values through the Avahi callback functions */
130
134
typedef struct {
142
146
                      .dh_bits = 1024, .priority = "SECURE256"
143
147
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
144
148
 
 
149
sig_atomic_t quit_now = 0;
 
150
int signal_received = 0;
 
151
 
145
152
/*
146
153
 * Make additional room in "buffer" for at least BUFFER_SIZE more
147
154
 * bytes. "buffer_capacity" is how much is currently allocated,
416
423
  }
417
424
  
418
425
  /* OpenPGP credentials */
419
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
426
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
420
427
  if(ret != GNUTLS_E_SUCCESS){
421
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
422
 
                                                    from
423
 
                                                    -Wunreachable-code
424
 
                                                 */
 
428
    fprintf(stderr, "GnuTLS memory error: %s\n",
425
429
            safer_gnutls_strerror(ret));
426
430
    gnutls_global_deinit();
427
431
    return -1;
474
478
static int init_gnutls_session(gnutls_session_t *session){
475
479
  int ret;
476
480
  /* GnuTLS session creation */
477
 
  ret = gnutls_init(session, GNUTLS_SERVER);
 
481
  do {
 
482
    ret = gnutls_init(session, GNUTLS_SERVER);
 
483
    if(quit_now){
 
484
      return -1;
 
485
    }
 
486
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
478
487
  if(ret != GNUTLS_E_SUCCESS){
479
488
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
480
489
            safer_gnutls_strerror(ret));
482
491
  
483
492
  {
484
493
    const char *err;
485
 
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
494
    do {
 
495
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
496
      if(quit_now){
 
497
        gnutls_deinit(*session);
 
498
        return -1;
 
499
      }
 
500
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
486
501
    if(ret != GNUTLS_E_SUCCESS){
487
502
      fprintf(stderr, "Syntax error at: %s\n", err);
488
503
      fprintf(stderr, "GnuTLS error: %s\n",
492
507
    }
493
508
  }
494
509
  
495
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
496
 
                               mc.cred);
 
510
  do {
 
511
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
512
                                 mc.cred);
 
513
    if(quit_now){
 
514
      gnutls_deinit(*session);
 
515
      return -1;
 
516
    }
 
517
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
497
518
  if(ret != GNUTLS_E_SUCCESS){
498
519
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
499
520
            safer_gnutls_strerror(ret));
502
523
  }
503
524
  
504
525
  /* ignore client certificate if any. */
505
 
  gnutls_certificate_server_set_request(*session,
506
 
                                        GNUTLS_CERT_IGNORE);
 
526
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
507
527
  
508
528
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
509
529
  
514
534
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
515
535
                      __attribute__((unused)) const char *txt){}
516
536
 
517
 
sig_atomic_t quit_now = 0;
518
 
int signal_received = 0;
519
 
 
520
537
/* Called when a Mandos server is found */
521
538
static int start_mandos_communication(const char *ip, uint16_t port,
522
539
                                      AvahiIfIndex if_index,
528
545
    struct sockaddr_in6 in6;
529
546
  } to;
530
547
  char *buffer = NULL;
531
 
  char *decrypted_buffer;
 
548
  char *decrypted_buffer = NULL;
532
549
  size_t buffer_length = 0;
533
550
  size_t buffer_capacity = 0;
534
551
  size_t written;
535
 
  int retval = 0;
 
552
  int retval = -1;
536
553
  gnutls_session_t session;
537
554
  int pf;                       /* Protocol family */
538
555
  
 
556
  errno = 0;
 
557
  
539
558
  if(quit_now){
 
559
    errno = EINTR;
540
560
    return -1;
541
561
  }
542
562
  
549
569
    break;
550
570
  default:
551
571
    fprintf(stderr, "Bad address family: %d\n", af);
 
572
    errno = EINVAL;
552
573
    return -1;
553
574
  }
554
575
  
564
585
  
565
586
  tcp_sd = socket(pf, SOCK_STREAM, 0);
566
587
  if(tcp_sd < 0){
 
588
    int e = errno;
567
589
    perror("socket");
568
 
    retval = -1;
 
590
    errno = e;
569
591
    goto mandos_end;
570
592
  }
571
593
  
572
594
  if(quit_now){
 
595
    errno = EINTR;
573
596
    goto mandos_end;
574
597
  }
575
598
  
582
605
    ret = inet_pton(af, ip, &to.in.sin_addr);
583
606
  }
584
607
  if(ret < 0 ){
 
608
    int e = errno;
585
609
    perror("inet_pton");
586
 
    retval = -1;
 
610
    errno = e;
587
611
    goto mandos_end;
588
612
  }
589
613
  if(ret == 0){
 
614
    int e = errno;
590
615
    fprintf(stderr, "Bad address: %s\n", ip);
591
 
    retval = -1;
 
616
    errno = e;
592
617
    goto mandos_end;
593
618
  }
594
619
  if(af == AF_INET6){
602
627
      if(if_index == AVAHI_IF_UNSPEC){
603
628
        fprintf(stderr, "An IPv6 link-local address is incomplete"
604
629
                " without a network interface\n");
605
 
        retval = -1;
 
630
        errno = EINVAL;
606
631
        goto mandos_end;
607
632
      }
608
633
      /* Set the network interface number as scope */
615
640
  }
616
641
  
617
642
  if(quit_now){
 
643
    errno = EINTR;
618
644
    goto mandos_end;
619
645
  }
620
646
  
651
677
  }
652
678
  
653
679
  if(quit_now){
 
680
    errno = EINTR;
654
681
    goto mandos_end;
655
682
  }
656
683
  
660
687
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
661
688
  }
662
689
  if(ret < 0){
663
 
    perror("connect");
664
 
    retval = -1;
 
690
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
691
      int e = errno;
 
692
      perror("connect");
 
693
      errno = e;
 
694
    }
665
695
    goto mandos_end;
666
696
  }
667
697
  
668
698
  if(quit_now){
 
699
    errno = EINTR;
669
700
    goto mandos_end;
670
701
  }
671
702
  
676
707
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
677
708
                                   out_size - written));
678
709
    if(ret == -1){
 
710
      int e = errno;
679
711
      perror("write");
680
 
      retval = -1;
 
712
      errno = e;
681
713
      goto mandos_end;
682
714
    }
683
715
    written += (size_t)ret;
693
725
    }
694
726
  
695
727
    if(quit_now){
 
728
      errno = EINTR;
696
729
      goto mandos_end;
697
730
    }
698
731
  }
702
735
  }
703
736
  
704
737
  if(quit_now){
 
738
    errno = EINTR;
705
739
    goto mandos_end;
706
740
  }
707
741
  
708
742
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
709
743
  
710
744
  if(quit_now){
 
745
    errno = EINTR;
711
746
    goto mandos_end;
712
747
  }
713
748
  
714
 
  do{
 
749
  do {
715
750
    ret = gnutls_handshake(session);
716
751
    if(quit_now){
 
752
      errno = EINTR;
717
753
      goto mandos_end;
718
754
    }
719
755
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
723
759
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
724
760
      gnutls_perror(ret);
725
761
    }
726
 
    retval = -1;
 
762
    errno = EPROTO;
727
763
    goto mandos_end;
728
764
  }
729
765
  
737
773
  while(true){
738
774
    
739
775
    if(quit_now){
 
776
      errno = EINTR;
740
777
      goto mandos_end;
741
778
    }
742
779
    
743
780
    buffer_capacity = incbuffer(&buffer, buffer_length,
744
781
                                   buffer_capacity);
745
782
    if(buffer_capacity == 0){
 
783
      int e = errno;
746
784
      perror("incbuffer");
747
 
      retval = -1;
 
785
      errno = e;
748
786
      goto mandos_end;
749
787
    }
750
788
    
751
789
    if(quit_now){
 
790
      errno = EINTR;
752
791
      goto mandos_end;
753
792
    }
754
793
    
763
802
      case GNUTLS_E_AGAIN:
764
803
        break;
765
804
      case GNUTLS_E_REHANDSHAKE:
766
 
        do{
 
805
        do {
767
806
          ret = gnutls_handshake(session);
768
807
          
769
808
          if(quit_now){
 
809
            errno = EINTR;
770
810
            goto mandos_end;
771
811
          }
772
812
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
773
813
        if(ret < 0){
774
814
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
775
815
          gnutls_perror(ret);
776
 
          retval = -1;
 
816
          errno = EPROTO;
777
817
          goto mandos_end;
778
818
        }
779
819
        break;
780
820
      default:
781
821
        fprintf(stderr, "Unknown error while reading data from"
782
822
                " encrypted session with Mandos server\n");
783
 
        retval = -1;
784
823
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
824
        errno = EIO;
785
825
        goto mandos_end;
786
826
      }
787
827
    } else {
794
834
  }
795
835
  
796
836
  if(quit_now){
797
 
    goto mandos_end;
798
 
  }
799
 
  
800
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
801
 
  
802
 
  if(quit_now){
803
 
    goto mandos_end;
804
 
  }
 
837
    errno = EINTR;
 
838
    goto mandos_end;
 
839
  }
 
840
  
 
841
  do {
 
842
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
843
    if(quit_now){
 
844
      errno = EINTR;
 
845
      goto mandos_end;
 
846
    }
 
847
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
805
848
  
806
849
  if(buffer_length > 0){
807
850
    ssize_t decrypted_buffer_size;
813
856
      written = 0;
814
857
      while(written < (size_t) decrypted_buffer_size){
815
858
        if(quit_now){
 
859
          errno = EINTR;
816
860
          goto mandos_end;
817
861
        }
818
862
        
820
864
                          (size_t)decrypted_buffer_size - written,
821
865
                          stdout);
822
866
        if(ret == 0 and ferror(stdout)){
 
867
          int e = errno;
823
868
          if(debug){
824
869
            fprintf(stderr, "Error writing encrypted data: %s\n",
825
870
                    strerror(errno));
826
871
          }
827
 
          retval = -1;
828
 
          break;
 
872
          errno = e;
 
873
          goto mandos_end;
829
874
        }
830
875
        written += (size_t)ret;
831
876
      }
832
 
      free(decrypted_buffer);
833
 
    } else {
834
 
      retval = -1;
 
877
      retval = 0;
835
878
    }
836
 
  } else {
837
 
    retval = -1;
838
879
  }
839
880
  
840
881
  /* Shutdown procedure */
841
882
  
842
883
 mandos_end:
843
 
  free(buffer);
844
 
  if(tcp_sd >= 0){
845
 
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
846
 
  }
847
 
  if(ret == -1){
848
 
    perror("close");
849
 
  }
850
 
  gnutls_deinit(session);
851
 
  if(quit_now){
852
 
    retval = -1;
 
884
  {
 
885
    int e = errno;
 
886
    free(decrypted_buffer);
 
887
    free(buffer);
 
888
    if(tcp_sd >= 0){
 
889
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
890
    }
 
891
    if(ret == -1){
 
892
      if(e == 0){
 
893
        e = errno;
 
894
      }
 
895
      perror("close");
 
896
    }
 
897
    gnutls_deinit(session);
 
898
    if(quit_now){
 
899
      e = EINTR;
 
900
      retval = -1;
 
901
    }
 
902
    errno = e;
853
903
  }
854
904
  return retval;
855
905
}
971
1021
  errno = old_errno;
972
1022
}
973
1023
 
 
1024
/* 
 
1025
 * This function determines if a directory entry in /sys/class/net
 
1026
 * corresponds to an acceptable network device.
 
1027
 * (This function is passed to scandir(3) as a filter function.)
 
1028
 */
 
1029
int good_interface(const struct dirent *if_entry){
 
1030
  ssize_t ssret;
 
1031
  char *flagname = NULL;
 
1032
  if(if_entry->d_name[0] == '.'){
 
1033
    return 0;
 
1034
  }
 
1035
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1036
                     if_entry->d_name);
 
1037
  if(ret < 0){
 
1038
    perror("asprintf");
 
1039
    return 0;
 
1040
  }
 
1041
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1042
  if(flags_fd == -1){
 
1043
    perror("open");
 
1044
    free(flagname);
 
1045
    return 0;
 
1046
  }
 
1047
  free(flagname);
 
1048
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1049
  /* read line from flags_fd */
 
1050
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
 
1051
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1052
  flagstring[(size_t)to_read] = '\0';
 
1053
  if(flagstring == NULL){
 
1054
    perror("malloc");
 
1055
    close(flags_fd);
 
1056
    return 0;
 
1057
  }
 
1058
  while(to_read > 0){
 
1059
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1060
                                             (size_t)to_read));
 
1061
    if(ssret == -1){
 
1062
      perror("read");
 
1063
      free(flagstring);
 
1064
      close(flags_fd);
 
1065
      return 0;
 
1066
    }
 
1067
    to_read -= ssret;
 
1068
    if(ssret == 0){
 
1069
      break;
 
1070
    }
 
1071
  }
 
1072
  close(flags_fd);
 
1073
  intmax_t tmpmax;
 
1074
  char *tmp;
 
1075
  errno = 0;
 
1076
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1077
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1078
                                         and not (isspace(*tmp)))
 
1079
     or tmpmax != (ifreq_flags)tmpmax){
 
1080
    if(debug){
 
1081
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1082
              flagstring, if_entry->d_name);
 
1083
    }
 
1084
    free(flagstring);
 
1085
    return 0;
 
1086
  }
 
1087
  free(flagstring);
 
1088
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1089
  /* Reject the loopback device */
 
1090
  if(flags & IFF_LOOPBACK){
 
1091
    if(debug){
 
1092
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1093
              if_entry->d_name);
 
1094
    }
 
1095
    return 0;
 
1096
  }
 
1097
  /* Accept point-to-point devices only if connect_to is specified */
 
1098
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1099
    if(debug){
 
1100
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1101
              if_entry->d_name);
 
1102
    }
 
1103
    return 1;
 
1104
  }
 
1105
  /* Otherwise, reject non-broadcast-capable devices */
 
1106
  if(not (flags & IFF_BROADCAST)){
 
1107
    if(debug){
 
1108
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1109
              if_entry->d_name);
 
1110
    }
 
1111
    return 0;
 
1112
  }
 
1113
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1114
  if(flags & IFF_NOARP){
 
1115
    if(debug){
 
1116
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1117
              if_entry->d_name);
 
1118
    }
 
1119
    return 0;
 
1120
  }
 
1121
  /* Accept this device */
 
1122
  if(debug){
 
1123
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1124
            if_entry->d_name);
 
1125
  }
 
1126
  return 1;
 
1127
}
 
1128
 
974
1129
int main(int argc, char *argv[]){
975
1130
  AvahiSServiceBrowser *sb = NULL;
976
1131
  int error;
978
1133
  intmax_t tmpmax;
979
1134
  char *tmp;
980
1135
  int exitcode = EXIT_SUCCESS;
981
 
  const char *interface = "eth0";
 
1136
  const char *interface = "";
982
1137
  struct ifreq network;
983
1138
  int sd = -1;
984
1139
  bool take_down_interface = false;
985
1140
  uid_t uid;
986
1141
  gid_t gid;
987
 
  char *connect_to = NULL;
988
1142
  char tempdir[] = "/tmp/mandosXXXXXX";
989
1143
  bool tempdir_created = false;
990
1144
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
995
1149
  bool gpgme_initialized = false;
996
1150
  float delay = 2.5f;
997
1151
  
998
 
  struct sigaction old_sigterm_action;
 
1152
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
999
1153
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1000
1154
  
 
1155
  uid = getuid();
 
1156
  gid = getgid();
 
1157
  
 
1158
  /* Lower any group privileges we might have, just to be safe */
 
1159
  errno = 0;
 
1160
  ret = setgid(gid);
 
1161
  if(ret == -1){
 
1162
    perror("setgid");
 
1163
  }
 
1164
  
 
1165
  /* Lower user privileges (temporarily) */
 
1166
  errno = 0;
 
1167
  ret = seteuid(uid);
 
1168
  if(ret == -1){
 
1169
    perror("seteuid");
 
1170
  }
 
1171
  
 
1172
  if(quit_now){
 
1173
    goto end;
 
1174
  }
 
1175
  
1001
1176
  {
1002
1177
    struct argp_option options[] = {
1003
1178
      { .name = "debug", .key = 128,
1032
1207
        .arg = "SECONDS",
1033
1208
        .doc = "Maximum delay to wait for interface startup",
1034
1209
        .group = 2 },
 
1210
      /*
 
1211
       * These reproduce what we would get without ARGP_NO_HELP
 
1212
       */
 
1213
      { .name = "help", .key = '?',
 
1214
        .doc = "Give this help list", .group = -1 },
 
1215
      { .name = "usage", .key = -3,
 
1216
        .doc = "Give a short usage message", .group = -1 },
 
1217
      { .name = "version", .key = 'V',
 
1218
        .doc = "Print program version", .group = -1 },
1035
1219
      { .name = NULL }
1036
1220
    };
1037
1221
    
1038
1222
    error_t parse_opt(int key, char *arg,
1039
1223
                      struct argp_state *state){
 
1224
      errno = 0;
1040
1225
      switch(key){
1041
1226
      case 128:                 /* --debug */
1042
1227
        debug = true;
1058
1243
        tmpmax = strtoimax(arg, &tmp, 10);
1059
1244
        if(errno != 0 or tmp == arg or *tmp != '\0'
1060
1245
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1061
 
          fprintf(stderr, "Bad number of DH bits\n");
1062
 
          exit(EXIT_FAILURE);
 
1246
          argp_error(state, "Bad number of DH bits");
1063
1247
        }
1064
1248
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1065
1249
        break;
1070
1254
        errno = 0;
1071
1255
        delay = strtof(arg, &tmp);
1072
1256
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1073
 
          fprintf(stderr, "Bad delay\n");
1074
 
          exit(EXIT_FAILURE);
 
1257
          argp_error(state, "Bad delay");
1075
1258
        }
1076
1259
        break;
1077
 
      case ARGP_KEY_ARG:
1078
 
        argp_usage(state);
1079
 
      case ARGP_KEY_END:
 
1260
        /*
 
1261
         * These reproduce what we would get without ARGP_NO_HELP
 
1262
         */
 
1263
      case '?':                 /* --help */
 
1264
        argp_state_help(state, state->out_stream,
 
1265
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
 
1266
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
 
1267
      case -3:                  /* --usage */
 
1268
        argp_state_help(state, state->out_stream,
 
1269
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
 
1270
      case 'V':                 /* --version */
 
1271
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1272
        exit(argp_err_exit_status);
1080
1273
        break;
1081
1274
      default:
1082
1275
        return ARGP_ERR_UNKNOWN;
1083
1276
      }
1084
 
      return 0;
 
1277
      return errno;
1085
1278
    }
1086
1279
    
1087
1280
    struct argp argp = { .options = options, .parser = parse_opt,
1088
1281
                         .args_doc = "",
1089
1282
                         .doc = "Mandos client -- Get and decrypt"
1090
1283
                         " passwords from a Mandos server" };
1091
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
1092
 
    if(ret == ARGP_ERR_UNKNOWN){
1093
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
1094
 
      exitcode = EXIT_FAILURE;
 
1284
    ret = argp_parse(&argp, argc, argv,
 
1285
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1286
    switch(ret){
 
1287
    case 0:
 
1288
      break;
 
1289
    case ENOMEM:
 
1290
    default:
 
1291
      errno = ret;
 
1292
      perror("argp_parse");
 
1293
      exitcode = EX_OSERR;
 
1294
      goto end;
 
1295
    case EINVAL:
 
1296
      exitcode = EX_USAGE;
1095
1297
      goto end;
1096
1298
    }
1097
1299
  }
1099
1301
  if(not debug){
1100
1302
    avahi_set_log_function(empty_log);
1101
1303
  }
 
1304
 
 
1305
  if(interface[0] == '\0'){
 
1306
    struct dirent **direntries;
 
1307
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1308
                  alphasort);
 
1309
    if(ret >= 1){
 
1310
      /* Pick the first good interface */
 
1311
      interface = strdup(direntries[0]->d_name);
 
1312
      if(debug){
 
1313
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1314
      }
 
1315
      if(interface == NULL){
 
1316
        perror("malloc");
 
1317
        free(direntries);
 
1318
        exitcode = EXIT_FAILURE;
 
1319
        goto end;
 
1320
      }
 
1321
      free(direntries);
 
1322
    } else {
 
1323
      free(direntries);
 
1324
      fprintf(stderr, "Could not find a network interface\n");
 
1325
      exitcode = EXIT_FAILURE;
 
1326
      goto end;
 
1327
    }
 
1328
  }
1102
1329
  
1103
1330
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1104
1331
     from the signal handler */
1107
1334
  mc.simple_poll = avahi_simple_poll_new();
1108
1335
  if(mc.simple_poll == NULL){
1109
1336
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1110
 
    exitcode = EXIT_FAILURE;
 
1337
    exitcode = EX_UNAVAILABLE;
1111
1338
    goto end;
1112
1339
  }
1113
1340
  
1115
1342
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1116
1343
  if(ret == -1){
1117
1344
    perror("sigaddset");
1118
 
    exitcode = EXIT_FAILURE;
 
1345
    exitcode = EX_OSERR;
1119
1346
    goto end;
1120
1347
  }
1121
1348
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1122
1349
  if(ret == -1){
1123
1350
    perror("sigaddset");
1124
 
    exitcode = EXIT_FAILURE;
 
1351
    exitcode = EX_OSERR;
1125
1352
    goto end;
1126
1353
  }
1127
1354
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1128
1355
  if(ret == -1){
1129
1356
    perror("sigaddset");
1130
 
    exitcode = EXIT_FAILURE;
 
1357
    exitcode = EX_OSERR;
1131
1358
    goto end;
1132
1359
  }
1133
1360
  /* Need to check if the handler is SIG_IGN before handling:
1137
1364
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1138
1365
  if(ret == -1){
1139
1366
    perror("sigaction");
1140
 
    return EXIT_FAILURE;
 
1367
    return EX_OSERR;
1141
1368
  }
1142
1369
  if(old_sigterm_action.sa_handler != SIG_IGN){
1143
1370
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1144
1371
    if(ret == -1){
1145
1372
      perror("sigaction");
1146
 
      exitcode = EXIT_FAILURE;
 
1373
      exitcode = EX_OSERR;
1147
1374
      goto end;
1148
1375
    }
1149
1376
  }
1150
1377
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1151
1378
  if(ret == -1){
1152
1379
    perror("sigaction");
1153
 
    return EXIT_FAILURE;
 
1380
    return EX_OSERR;
1154
1381
  }
1155
1382
  if(old_sigterm_action.sa_handler != SIG_IGN){
1156
1383
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1157
1384
    if(ret == -1){
1158
1385
      perror("sigaction");
1159
 
      exitcode = EXIT_FAILURE;
 
1386
      exitcode = EX_OSERR;
1160
1387
      goto end;
1161
1388
    }
1162
1389
  }
1163
1390
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1164
1391
  if(ret == -1){
1165
1392
    perror("sigaction");
1166
 
    return EXIT_FAILURE;
 
1393
    return EX_OSERR;
1167
1394
  }
1168
1395
  if(old_sigterm_action.sa_handler != SIG_IGN){
1169
1396
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1170
1397
    if(ret == -1){
1171
1398
      perror("sigaction");
1172
 
      exitcode = EXIT_FAILURE;
 
1399
      exitcode = EX_OSERR;
1173
1400
      goto end;
1174
1401
    }
1175
1402
  }
1176
1403
  
1177
1404
  /* If the interface is down, bring it up */
1178
 
  if(interface[0] != '\0'){
 
1405
  if(strcmp(interface, "none") != 0){
1179
1406
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1180
1407
    if(if_index == 0){
1181
1408
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1182
 
      exitcode = EXIT_FAILURE;
 
1409
      exitcode = EX_UNAVAILABLE;
1183
1410
      goto end;
1184
1411
    }
1185
1412
    
1187
1414
      goto end;
1188
1415
    }
1189
1416
    
 
1417
    /* Re-raise priviliges */
 
1418
    errno = 0;
 
1419
    ret = seteuid(0);
 
1420
    if(ret == -1){
 
1421
      perror("seteuid");
 
1422
    }
 
1423
    
1190
1424
#ifdef __linux__
1191
1425
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1192
 
       messages to mess up the prompt */
 
1426
       messages about the network interface to mess up the prompt */
1193
1427
    ret = klogctl(8, NULL, 5);
1194
1428
    bool restore_loglevel = true;
1195
1429
    if(ret == -1){
1201
1435
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1202
1436
    if(sd < 0){
1203
1437
      perror("socket");
1204
 
      exitcode = EXIT_FAILURE;
 
1438
      exitcode = EX_OSERR;
1205
1439
#ifdef __linux__
1206
1440
      if(restore_loglevel){
1207
1441
        ret = klogctl(7, NULL, 0);
1210
1444
        }
1211
1445
      }
1212
1446
#endif  /* __linux__ */
 
1447
      /* Lower privileges */
 
1448
      errno = 0;
 
1449
      ret = seteuid(uid);
 
1450
      if(ret == -1){
 
1451
        perror("seteuid");
 
1452
      }
1213
1453
      goto end;
1214
1454
    }
1215
1455
    strcpy(network.ifr_name, interface);
1224
1464
        }
1225
1465
      }
1226
1466
#endif  /* __linux__ */
1227
 
      exitcode = EXIT_FAILURE;
 
1467
      exitcode = EX_OSERR;
 
1468
      /* Lower privileges */
 
1469
      errno = 0;
 
1470
      ret = seteuid(uid);
 
1471
      if(ret == -1){
 
1472
        perror("seteuid");
 
1473
      }
1228
1474
      goto end;
1229
1475
    }
1230
1476
    if((network.ifr_flags & IFF_UP) == 0){
1233
1479
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1234
1480
      if(ret == -1){
1235
1481
        take_down_interface = false;
1236
 
        perror("ioctl SIOCSIFFLAGS");
1237
 
        exitcode = EXIT_FAILURE;
 
1482
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
 
1483
        exitcode = EX_OSERR;
1238
1484
#ifdef __linux__
1239
1485
        if(restore_loglevel){
1240
1486
          ret = klogctl(7, NULL, 0);
1243
1489
          }
1244
1490
        }
1245
1491
#endif  /* __linux__ */
 
1492
        /* Lower privileges */
 
1493
        errno = 0;
 
1494
        ret = seteuid(uid);
 
1495
        if(ret == -1){
 
1496
          perror("seteuid");
 
1497
        }
1246
1498
        goto end;
1247
1499
      }
1248
1500
    }
1276
1528
      }
1277
1529
    }
1278
1530
#endif  /* __linux__ */
1279
 
  }
1280
 
  
1281
 
  if(quit_now){
1282
 
    goto end;
1283
 
  }
1284
 
  
1285
 
  uid = getuid();
1286
 
  gid = getgid();
1287
 
  
1288
 
  errno = 0;
1289
 
  setgid(gid);
1290
 
  if(ret == -1){
1291
 
    perror("setgid");
1292
 
  }
1293
 
  
1294
 
  ret = setuid(uid);
1295
 
  if(ret == -1){
1296
 
    perror("setuid");
 
1531
    /* Lower privileges */
 
1532
    errno = 0;
 
1533
    if(take_down_interface){
 
1534
      /* Lower privileges */
 
1535
      ret = seteuid(uid);
 
1536
      if(ret == -1){
 
1537
        perror("seteuid");
 
1538
      }
 
1539
    } else {
 
1540
      /* Lower privileges permanently */
 
1541
      ret = setuid(uid);
 
1542
      if(ret == -1){
 
1543
        perror("setuid");
 
1544
      }
 
1545
    }
1297
1546
  }
1298
1547
  
1299
1548
  if(quit_now){
1303
1552
  ret = init_gnutls_global(pubkey, seckey);
1304
1553
  if(ret == -1){
1305
1554
    fprintf(stderr, "init_gnutls_global failed\n");
1306
 
    exitcode = EXIT_FAILURE;
 
1555
    exitcode = EX_UNAVAILABLE;
1307
1556
    goto end;
1308
1557
  } else {
1309
1558
    gnutls_initialized = true;
1326
1575
  
1327
1576
  if(not init_gpgme(pubkey, seckey, tempdir)){
1328
1577
    fprintf(stderr, "init_gpgme failed\n");
1329
 
    exitcode = EXIT_FAILURE;
 
1578
    exitcode = EX_UNAVAILABLE;
1330
1579
    goto end;
1331
1580
  } else {
1332
1581
    gpgme_initialized = true;
1342
1591
    char *address = strrchr(connect_to, ':');
1343
1592
    if(address == NULL){
1344
1593
      fprintf(stderr, "No colon in address\n");
1345
 
      exitcode = EXIT_FAILURE;
 
1594
      exitcode = EX_USAGE;
1346
1595
      goto end;
1347
1596
    }
1348
1597
    
1356
1605
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1357
1606
       or tmpmax != (uint16_t)tmpmax){
1358
1607
      fprintf(stderr, "Bad port number\n");
1359
 
      exitcode = EXIT_FAILURE;
 
1608
      exitcode = EX_USAGE;
1360
1609
      goto end;
1361
1610
    }
1362
1611
  
1378
1627
    if(quit_now){
1379
1628
      goto end;
1380
1629
    }
1381
 
    
1382
 
    ret = start_mandos_communication(address, port, if_index, af);
1383
 
    if(ret < 0){
1384
 
      exitcode = EXIT_FAILURE;
1385
 
    } else {
 
1630
 
 
1631
    while(not quit_now){
 
1632
      ret = start_mandos_communication(address, port, if_index, af);
 
1633
      if(quit_now or ret == 0){
 
1634
        break;
 
1635
      }
 
1636
      sleep(15);
 
1637
    };
 
1638
 
 
1639
    if (not quit_now){
1386
1640
      exitcode = EXIT_SUCCESS;
1387
1641
    }
 
1642
 
1388
1643
    goto end;
1389
1644
  }
1390
1645
  
1414
1669
  if(mc.server == NULL){
1415
1670
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1416
1671
            avahi_strerror(error));
1417
 
    exitcode = EXIT_FAILURE;
 
1672
    exitcode = EX_UNAVAILABLE;
1418
1673
    goto end;
1419
1674
  }
1420
1675
  
1429
1684
  if(sb == NULL){
1430
1685
    fprintf(stderr, "Failed to create service browser: %s\n",
1431
1686
            avahi_strerror(avahi_server_errno(mc.server)));
1432
 
    exitcode = EXIT_FAILURE;
 
1687
    exitcode = EX_UNAVAILABLE;
1433
1688
    goto end;
1434
1689
  }
1435
1690
  
1473
1728
  
1474
1729
  /* Take down the network interface */
1475
1730
  if(take_down_interface){
1476
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1731
    /* Re-raise priviliges */
 
1732
    errno = 0;
 
1733
    ret = seteuid(0);
1477
1734
    if(ret == -1){
1478
 
      perror("ioctl SIOCGIFFLAGS");
1479
 
    } else if(network.ifr_flags & IFF_UP) {
1480
 
      network.ifr_flags &= ~IFF_UP; /* clear flag */
1481
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1482
 
      if(ret == -1){
1483
 
        perror("ioctl SIOCSIFFLAGS");
1484
 
      }
 
1735
      perror("seteuid");
1485
1736
    }
1486
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1487
 
    if(ret == -1){
1488
 
      perror("close");
 
1737
    if(geteuid() == 0){
 
1738
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1739
      if(ret == -1){
 
1740
        perror("ioctl SIOCGIFFLAGS");
 
1741
      } else if(network.ifr_flags & IFF_UP) {
 
1742
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1743
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1744
        if(ret == -1){
 
1745
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
 
1746
        }
 
1747
      }
 
1748
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1749
      if(ret == -1){
 
1750
        perror("close");
 
1751
      }
 
1752
      /* Lower privileges permanently */
 
1753
      errno = 0;
 
1754
      ret = setuid(uid);
 
1755
      if(ret == -1){
 
1756
        perror("setuid");
 
1757
      }
1489
1758
    }
1490
1759
  }
1491
1760
  
1536
1805
  if(quit_now){
1537
1806
    sigemptyset(&old_sigterm_action.sa_mask);
1538
1807
    old_sigterm_action.sa_handler = SIG_DFL;
1539
 
    ret = sigaction(signal_received, &old_sigterm_action, NULL);
 
1808
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
 
1809
                                            &old_sigterm_action,
 
1810
                                            NULL));
1540
1811
    if(ret == -1){
1541
1812
      perror("sigaction");
1542
1813
    }
1543
 
    raise(signal_received);
 
1814
    do {
 
1815
      ret = raise(signal_received);
 
1816
    } while(ret != 0 and errno == EINTR);
 
1817
    if(ret != 0){
 
1818
      perror("raise");
 
1819
      abort();
 
1820
    }
 
1821
    TEMP_FAILURE_RETRY(pause());
1544
1822
  }
1545
1823
  
1546
1824
  return exitcode;