/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

Convert some programs to use the exit codes from <sysexits.h>.  Change
all programs using the "argp" parsing functions to use them correctly;
checking return value, using argp_error() to report parse errors etc.

* plugin-runner.c: Use <sysexits.h> exit codes.  Always use fallback,
                   even on option errors, except for "--help", etc.
  (getplugin): Make sure "errno" is set correctly on return.
  (main): Declare our own "--help", "--usage", and "--version"
          options which do not cause the fallback to be invoked.
          In all other options, use fallback on any error.
  (parse_opt, parse_opt_config_file): Reset errno at start and return
                                      errno.  No need to check "arg"
                                      for NULL.  New "--help",
                                      "--usage", and "--version"
                                      options.
  (parse_opt): Accept empty string as global option.  Do not print
               errors which will be detected and reported later.  Do
               "argp_error()" on parse error or empty plugin names.
* plugins.d/mandos-client.c: Use <sysexits.h> exit codes.  Do not
                             return successful exit code on "--help",
                             etc. since this would give the wrong
                             message to "plugin-runner".
  (main): Declare our own "--help", "--usage", and "--version"
          options which do not return a successful exit code.
  (parse_opt): Reset errno at start and return errno.  Do
               "argp_error()" on parse errors.  New "--help",
               "--usage", and "--version" options.
* plugins.d/password-prompt.c: Use exit codes from <sysexits.h>.  Do
                               not return successful exit code on
                               "--help", etc. since this would give
                               the wrong message to "plugin-runner".
  (main): Declare our own "--help", "--usage", and "--version" options
          which do not return a successful exit code.  Do
          close(STDOUT_FILENO) after writing to check its return code.
  (parse_opt): Reset errno at start and return errno.

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