/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2016-02-28 20:34:59 UTC
  • Revision ID: teddy@recompile.se-20160228203459-81vtqvr96yukyrok
Client: Remove calls to gnutls_global_init and gnutls_global_deinit

* plugins.d/mandos-client.c (init_gnutls_global, main): Don't call
  gnutls_global_init or gnutls_global_deinit anymore; these are
  unnecessary in GnuTLS 3.3.

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-2014 Teddy Hogeborn
13
 
 * Copyright © 2008-2014 Björn Påhlsson
 
12
 * Copyright © 2008-2016 Teddy Hogeborn
 
13
 * Copyright © 2008-2016 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
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
48
48
#include <stdbool.h>            /* bool, false, true */
49
 
#include <string.h>             /* memset(), strcmp(), strlen(),
50
 
                                   strerror(), asprintf(), strcpy() */
 
49
#include <string.h>             /* strcmp(), strlen(), strerror(),
 
50
                                   asprintf(), strncpy() */
51
51
#include <sys/ioctl.h>          /* ioctl */
52
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
53
                                   sockaddr_in6, PF_INET6,
305
305
      return false;
306
306
    }
307
307
    
308
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
 
308
    ret = close(fd);
309
309
    if(ret == -1){
310
310
      perror_plus("close");
311
311
    }
513
513
  fprintf_plus(stderr, "GnuTLS: %s", string);
514
514
}
515
515
 
516
 
__attribute__((nonnull, warn_unused_result))
 
516
__attribute__((nonnull(1, 2, 4), warn_unused_result))
517
517
static int init_gnutls_global(const char *pubkeyfilename,
518
518
                              const char *seckeyfilename,
 
519
                              const char *dhparamsfilename,
519
520
                              mandos_context *mc){
520
521
  int ret;
521
522
  unsigned int uret;
524
525
    fprintf_plus(stderr, "Initializing GnuTLS\n");
525
526
  }
526
527
  
527
 
  ret = gnutls_global_init();
528
 
  if(ret != GNUTLS_E_SUCCESS){
529
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
530
 
                 safer_gnutls_strerror(ret));
531
 
    return -1;
532
 
  }
533
 
  
534
528
  if(debug){
535
529
    /* "Use a log level over 10 to enable all debugging options."
536
530
     * - GnuTLS manual
544
538
  if(ret != GNUTLS_E_SUCCESS){
545
539
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
546
540
                 safer_gnutls_strerror(ret));
547
 
    gnutls_global_deinit();
548
541
    return -1;
549
542
  }
550
543
  
575
568
                 safer_gnutls_strerror(ret));
576
569
    goto globalfail;
577
570
  }
578
 
  if(mc->dh_bits == 0){
579
 
    /* Find out the optimal number of DH bits */
580
 
    /* Try to read the private key file */
581
 
    gnutls_datum_t buffer = { .data = NULL, .size = 0 };
582
 
    {
583
 
      int secfile = open(seckeyfilename, O_RDONLY);
584
 
      size_t buffer_capacity = 0;
 
571
  /* If a Diffie-Hellman parameters file was given, try to use it */
 
572
  if(dhparamsfilename != NULL){
 
573
    gnutls_datum_t params = { .data = NULL, .size = 0 };
 
574
    do {
 
575
      int dhpfile = open(dhparamsfilename, O_RDONLY);
 
576
      if(dhpfile == -1){
 
577
        perror_plus("open");
 
578
        dhparamsfilename = NULL;
 
579
        break;
 
580
      }
 
581
      size_t params_capacity = 0;
585
582
      while(true){
586
 
        buffer_capacity = incbuffer((char **)&buffer.data,
587
 
                                    (size_t)buffer.size,
588
 
                                    (size_t)buffer_capacity);
589
 
        if(buffer_capacity == 0){
 
583
        params_capacity = incbuffer((char **)&params.data,
 
584
                                    (size_t)params.size,
 
585
                                    (size_t)params_capacity);
 
586
        if(params_capacity == 0){
590
587
          perror_plus("incbuffer");
591
 
          free(buffer.data);
592
 
          buffer.data = NULL;
 
588
          free(params.data);
 
589
          params.data = NULL;
 
590
          dhparamsfilename = NULL;
593
591
          break;
594
592
        }
595
 
        ssize_t bytes_read = read(secfile, buffer.data + buffer.size,
 
593
        ssize_t bytes_read = read(dhpfile,
 
594
                                  params.data + params.size,
596
595
                                  BUFFER_SIZE);
597
596
        /* EOF */
598
597
        if(bytes_read == 0){
601
600
        /* check bytes_read for failure */
602
601
        if(bytes_read < 0){
603
602
          perror_plus("read");
604
 
          free(buffer.data);
605
 
          buffer.data = NULL;
606
 
          break;
607
 
        }
608
 
        buffer.size += (unsigned int)bytes_read;
609
 
      }
610
 
      close(secfile);
611
 
    }
612
 
    /* If successful, use buffer to parse private key */
613
 
    gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
614
 
    if(buffer.data != NULL){
615
 
      {
616
 
        gnutls_openpgp_privkey_t privkey = NULL;
617
 
        ret = gnutls_openpgp_privkey_init(&privkey);
618
 
        if(ret != GNUTLS_E_SUCCESS){
619
 
          fprintf_plus(stderr, "Error initializing OpenPGP key"
620
 
                       " structure: %s", safer_gnutls_strerror(ret));
621
 
          free(buffer.data);
622
 
          buffer.data = NULL;
623
 
        } else {
624
 
          ret = gnutls_openpgp_privkey_import(privkey, &buffer,
625
 
                                            GNUTLS_OPENPGP_FMT_BASE64,
626
 
                                              "", 0);
 
603
          free(params.data);
 
604
          params.data = NULL;
 
605
          dhparamsfilename = NULL;
 
606
          break;
 
607
        }
 
608
        params.size += (unsigned int)bytes_read;
 
609
      }
 
610
      if(params.data == NULL){
 
611
        dhparamsfilename = NULL;
 
612
      }
 
613
      if(dhparamsfilename == NULL){
 
614
        break;
 
615
      }
 
616
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
 
617
                                          GNUTLS_X509_FMT_PEM);
 
618
      if(ret != GNUTLS_E_SUCCESS){
 
619
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
 
620
                     " \"%s\": %s\n", dhparamsfilename,
 
621
                     safer_gnutls_strerror(ret));
 
622
        dhparamsfilename = NULL;
 
623
      }
 
624
    } while(false);
 
625
  }
 
626
  if(dhparamsfilename == NULL){
 
627
    if(mc->dh_bits == 0){
 
628
      /* Find out the optimal number of DH bits */
 
629
      /* Try to read the private key file */
 
630
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
 
631
      do {
 
632
        int secfile = open(seckeyfilename, O_RDONLY);
 
633
        if(secfile == -1){
 
634
          perror_plus("open");
 
635
          break;
 
636
        }
 
637
        size_t buffer_capacity = 0;
 
638
        while(true){
 
639
          buffer_capacity = incbuffer((char **)&buffer.data,
 
640
                                      (size_t)buffer.size,
 
641
                                      (size_t)buffer_capacity);
 
642
          if(buffer_capacity == 0){
 
643
            perror_plus("incbuffer");
 
644
            free(buffer.data);
 
645
            buffer.data = NULL;
 
646
            break;
 
647
          }
 
648
          ssize_t bytes_read = read(secfile,
 
649
                                    buffer.data + buffer.size,
 
650
                                    BUFFER_SIZE);
 
651
          /* EOF */
 
652
          if(bytes_read == 0){
 
653
            break;
 
654
          }
 
655
          /* check bytes_read for failure */
 
656
          if(bytes_read < 0){
 
657
            perror_plus("read");
 
658
            free(buffer.data);
 
659
            buffer.data = NULL;
 
660
            break;
 
661
          }
 
662
          buffer.size += (unsigned int)bytes_read;
 
663
        }
 
664
        close(secfile);
 
665
      } while(false);
 
666
      /* If successful, use buffer to parse private key */
 
667
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
668
      if(buffer.data != NULL){
 
669
        {
 
670
          gnutls_openpgp_privkey_t privkey = NULL;
 
671
          ret = gnutls_openpgp_privkey_init(&privkey);
627
672
          if(ret != GNUTLS_E_SUCCESS){
628
 
            fprintf_plus(stderr, "Error importing OpenPGP key : %s",
 
673
            fprintf_plus(stderr, "Error initializing OpenPGP key"
 
674
                         " structure: %s",
629
675
                         safer_gnutls_strerror(ret));
630
 
            privkey = NULL;
 
676
            free(buffer.data);
 
677
            buffer.data = NULL;
 
678
          } else {
 
679
            ret = gnutls_openpgp_privkey_import
 
680
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
 
681
            if(ret != GNUTLS_E_SUCCESS){
 
682
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
 
683
                           safer_gnutls_strerror(ret));
 
684
              privkey = NULL;
 
685
            }
 
686
            free(buffer.data);
 
687
            buffer.data = NULL;
 
688
            if(privkey != NULL){
 
689
              /* Use private key to suggest an appropriate
 
690
                 sec_param */
 
691
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
 
692
              gnutls_openpgp_privkey_deinit(privkey);
 
693
              if(debug){
 
694
                fprintf_plus(stderr, "This OpenPGP key implies using"
 
695
                             " a GnuTLS security parameter \"%s\".\n",
 
696
                             safe_string(gnutls_sec_param_get_name
 
697
                                         (sec_param)));
 
698
              }
 
699
            }
631
700
          }
632
 
          free(buffer.data);
633
 
          buffer.data = NULL;
634
 
          if(privkey != NULL){
635
 
            /* Use private key to suggest an appropriate sec_param */
636
 
            sec_param = gnutls_openpgp_privkey_sec_param(privkey);
637
 
            gnutls_openpgp_privkey_deinit(privkey);
638
 
            if(debug){
639
 
              fprintf_plus(stderr, "This OpenPGP key implies using a"
640
 
                           " GnuTLS security parameter \"%s\".\n",
641
 
                           safe_string(gnutls_sec_param_get_name
642
 
                                       (sec_param)));
643
 
            }
 
701
        }
 
702
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
 
703
          /* Err on the side of caution */
 
704
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
705
          if(debug){
 
706
            fprintf_plus(stderr, "Falling back to security parameter"
 
707
                         " \"%s\"\n",
 
708
                         safe_string(gnutls_sec_param_get_name
 
709
                                     (sec_param)));
644
710
          }
645
711
        }
646
712
      }
647
 
      if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
648
 
        /* Err on the side of caution */
649
 
        sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
713
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
 
714
      if(uret != 0){
 
715
        mc->dh_bits = uret;
650
716
        if(debug){
651
 
          fprintf_plus(stderr, "Falling back to security parameter"
652
 
                       " \"%s\"\n",
 
717
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
 
718
                       " implies %u DH bits; using that.\n",
653
719
                       safe_string(gnutls_sec_param_get_name
654
 
                                   (sec_param)));
 
720
                                   (sec_param)),
 
721
                       mc->dh_bits);
655
722
        }
656
 
      }
657
 
    }
658
 
    uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
659
 
    if(uret != 0){
660
 
      mc->dh_bits = uret;
661
 
      if(debug){
662
 
        fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
663
 
                     " implies %u DH bits; using that.\n",
 
723
      } else {
 
724
        fprintf_plus(stderr, "Failed to get implied number of DH"
 
725
                     " bits for security parameter \"%s\"): %s\n",
664
726
                     safe_string(gnutls_sec_param_get_name
665
727
                                 (sec_param)),
666
 
                     mc->dh_bits);
 
728
                     safer_gnutls_strerror(ret));
 
729
        goto globalfail;
667
730
      }
668
 
    } else {
669
 
      fprintf_plus(stderr, "Failed to get implied number of DH"
670
 
                   " bits for security parameter \"%s\"): %s\n",
671
 
                   safe_string(gnutls_sec_param_get_name(sec_param)),
 
731
    } else if(debug){
 
732
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
 
733
                   mc->dh_bits);
 
734
    }
 
735
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
736
    if(ret != GNUTLS_E_SUCCESS){
 
737
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
 
738
                   " bits): %s\n", mc->dh_bits,
672
739
                   safer_gnutls_strerror(ret));
673
740
      goto globalfail;
674
741
    }
675
 
  } else if(debug){
676
 
    fprintf_plus(stderr, "DH bits explicitly set to %u\n",
677
 
                 mc->dh_bits);
678
 
  }
679
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
680
 
  if(ret != GNUTLS_E_SUCCESS){
681
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation (%u bits):"
682
 
                 " %s\n", mc->dh_bits, safer_gnutls_strerror(ret));
683
 
    goto globalfail;
684
 
  }
685
 
  
 
742
  }
686
743
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
687
744
  
688
745
  return 0;
690
747
 globalfail:
691
748
  
692
749
  gnutls_certificate_free_credentials(mc->cred);
693
 
  gnutls_global_deinit();
694
750
  gnutls_dh_params_deinit(mc->dh_params);
695
751
  return -1;
696
752
}
748
804
  /* ignore client certificate if any. */
749
805
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
750
806
  
751
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
752
 
  
753
807
  return 0;
754
808
}
755
809
 
757
811
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
758
812
                      __attribute__((unused)) const char *txt){}
759
813
 
 
814
/* Set effective uid to 0, return errno */
 
815
__attribute__((warn_unused_result))
 
816
error_t raise_privileges(void){
 
817
  error_t old_errno = errno;
 
818
  error_t ret_errno = 0;
 
819
  if(seteuid(0) == -1){
 
820
    ret_errno = errno;
 
821
  }
 
822
  errno = old_errno;
 
823
  return ret_errno;
 
824
}
 
825
 
 
826
/* Set effective and real user ID to 0.  Return errno. */
 
827
__attribute__((warn_unused_result))
 
828
error_t raise_privileges_permanently(void){
 
829
  error_t old_errno = errno;
 
830
  error_t ret_errno = raise_privileges();
 
831
  if(ret_errno != 0){
 
832
    errno = old_errno;
 
833
    return ret_errno;
 
834
  }
 
835
  if(setuid(0) == -1){
 
836
    ret_errno = errno;
 
837
  }
 
838
  errno = old_errno;
 
839
  return ret_errno;
 
840
}
 
841
 
 
842
/* Set effective user ID to unprivileged saved user ID */
 
843
__attribute__((warn_unused_result))
 
844
error_t lower_privileges(void){
 
845
  error_t old_errno = errno;
 
846
  error_t ret_errno = 0;
 
847
  if(seteuid(uid) == -1){
 
848
    ret_errno = errno;
 
849
  }
 
850
  errno = old_errno;
 
851
  return ret_errno;
 
852
}
 
853
 
 
854
/* Lower privileges permanently */
 
855
__attribute__((warn_unused_result))
 
856
error_t lower_privileges_permanently(void){
 
857
  error_t old_errno = errno;
 
858
  error_t ret_errno = 0;
 
859
  if(setuid(uid) == -1){
 
860
    ret_errno = errno;
 
861
  }
 
862
  errno = old_errno;
 
863
  return ret_errno;
 
864
}
 
865
 
 
866
/* Helper function to add_local_route() and delete_local_route() */
 
867
__attribute__((nonnull, warn_unused_result))
 
868
static bool add_delete_local_route(const bool add,
 
869
                                   const char *address,
 
870
                                   AvahiIfIndex if_index){
 
871
  int ret;
 
872
  char helper[] = "mandos-client-iprouteadddel";
 
873
  char add_arg[] = "add";
 
874
  char delete_arg[] = "delete";
 
875
  char debug_flag[] = "--debug";
 
876
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
 
877
  if(pluginhelperdir == NULL){
 
878
    if(debug){
 
879
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
 
880
                   " variable not set; cannot run helper\n");
 
881
    }
 
882
    return false;
 
883
  }
 
884
  
 
885
  char interface[IF_NAMESIZE];
 
886
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
887
    perror_plus("if_indextoname");
 
888
    return false;
 
889
  }
 
890
  
 
891
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
892
  if(devnull == -1){
 
893
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
894
    return false;
 
895
  }
 
896
  pid_t pid = fork();
 
897
  if(pid == 0){
 
898
    /* Child */
 
899
    /* Raise privileges */
 
900
    errno = raise_privileges_permanently();
 
901
    if(errno != 0){
 
902
      perror_plus("Failed to raise privileges");
 
903
      /* _exit(EX_NOPERM); */
 
904
    } else {
 
905
      /* Set group */
 
906
      errno = 0;
 
907
      ret = setgid(0);
 
908
      if(ret == -1){
 
909
        perror_plus("setgid");
 
910
        _exit(EX_NOPERM);
 
911
      }
 
912
      /* Reset supplementary groups */
 
913
      errno = 0;
 
914
      ret = setgroups(0, NULL);
 
915
      if(ret == -1){
 
916
        perror_plus("setgroups");
 
917
        _exit(EX_NOPERM);
 
918
      }
 
919
    }
 
920
    ret = dup2(devnull, STDIN_FILENO);
 
921
    if(ret == -1){
 
922
      perror_plus("dup2(devnull, STDIN_FILENO)");
 
923
      _exit(EX_OSERR);
 
924
    }
 
925
    ret = close(devnull);
 
926
    if(ret == -1){
 
927
      perror_plus("close");
 
928
      _exit(EX_OSERR);
 
929
    }
 
930
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
931
    if(ret == -1){
 
932
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
933
      _exit(EX_OSERR);
 
934
    }
 
935
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
 
936
                                                    O_RDONLY
 
937
                                                    | O_DIRECTORY
 
938
                                                    | O_PATH
 
939
                                                    | O_CLOEXEC));
 
940
    if(helperdir_fd == -1){
 
941
      perror_plus("open");
 
942
      _exit(EX_UNAVAILABLE);
 
943
    }
 
944
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
 
945
                                                   helper, O_RDONLY));
 
946
    if(helper_fd == -1){
 
947
      perror_plus("openat");
 
948
      close(helperdir_fd);
 
949
      _exit(EX_UNAVAILABLE);
 
950
    }
 
951
    close(helperdir_fd);
 
952
#ifdef __GNUC__
 
953
#pragma GCC diagnostic push
 
954
#pragma GCC diagnostic ignored "-Wcast-qual"
 
955
#endif
 
956
    if(fexecve(helper_fd, (char *const [])
 
957
               { helper, add ? add_arg : delete_arg, (char *)address,
 
958
                   interface, debug ? debug_flag : NULL, NULL },
 
959
               environ) == -1){
 
960
#ifdef __GNUC__
 
961
#pragma GCC diagnostic pop
 
962
#endif
 
963
      perror_plus("fexecve");
 
964
      _exit(EXIT_FAILURE);
 
965
    }
 
966
  }
 
967
  if(pid == -1){
 
968
    perror_plus("fork");
 
969
    return false;
 
970
  }
 
971
  int status;
 
972
  pid_t pret = -1;
 
973
  errno = 0;
 
974
  do {
 
975
    pret = waitpid(pid, &status, 0);
 
976
    if(pret == -1 and errno == EINTR and quit_now){
 
977
      int errno_raising = 0;
 
978
      if((errno = raise_privileges()) != 0){
 
979
        errno_raising = errno;
 
980
        perror_plus("Failed to raise privileges in order to"
 
981
                    " kill helper program");
 
982
      }
 
983
      if(kill(pid, SIGTERM) == -1){
 
984
        perror_plus("kill");
 
985
      }
 
986
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
 
987
        perror_plus("Failed to lower privileges after killing"
 
988
                    " helper program");
 
989
      }
 
990
      return false;
 
991
    }
 
992
  } while(pret == -1 and errno == EINTR);
 
993
  if(pret == -1){
 
994
    perror_plus("waitpid");
 
995
    return false;
 
996
  }
 
997
  if(WIFEXITED(status)){
 
998
    if(WEXITSTATUS(status) != 0){
 
999
      fprintf_plus(stderr, "Error: iprouteadddel exited"
 
1000
                   " with status %d\n", WEXITSTATUS(status));
 
1001
      return false;
 
1002
    }
 
1003
    return true;
 
1004
  }
 
1005
  if(WIFSIGNALED(status)){
 
1006
    fprintf_plus(stderr, "Error: iprouteadddel died by"
 
1007
                 " signal %d\n", WTERMSIG(status));
 
1008
    return false;
 
1009
  }
 
1010
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
 
1011
  return false;
 
1012
}
 
1013
 
 
1014
__attribute__((nonnull, warn_unused_result))
 
1015
static bool add_local_route(const char *address,
 
1016
                            AvahiIfIndex if_index){
 
1017
  if(debug){
 
1018
    fprintf_plus(stderr, "Adding route to %s\n", address);
 
1019
  }
 
1020
  return add_delete_local_route(true, address, if_index);
 
1021
}
 
1022
 
 
1023
__attribute__((nonnull, warn_unused_result))
 
1024
static bool delete_local_route(const char *address,
 
1025
                               AvahiIfIndex if_index){
 
1026
  if(debug){
 
1027
    fprintf_plus(stderr, "Removing route to %s\n", address);
 
1028
  }
 
1029
  return add_delete_local_route(false, address, if_index);
 
1030
}
 
1031
 
760
1032
/* Called when a Mandos server is found */
761
1033
__attribute__((nonnull, warn_unused_result))
762
1034
static int start_mandos_communication(const char *ip, in_port_t port,
773
1045
  int retval = -1;
774
1046
  gnutls_session_t session;
775
1047
  int pf;                       /* Protocol family */
 
1048
  bool route_added = false;
776
1049
  
777
1050
  errno = 0;
778
1051
  
836
1109
                 PRIuMAX "\n", ip, (uintmax_t)port);
837
1110
  }
838
1111
  
839
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
1112
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
840
1113
  if(tcp_sd < 0){
841
1114
    int e = errno;
842
1115
    perror_plus("socket");
849
1122
    goto mandos_end;
850
1123
  }
851
1124
  
852
 
  memset(&to, 0, sizeof(to));
853
1125
  if(af == AF_INET6){
854
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
855
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
1126
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
 
1127
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
 
1128
    ret = inet_pton(af, ip, &to6->sin6_addr);
856
1129
  } else {                      /* IPv4 */
857
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
858
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
1130
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
 
1131
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
 
1132
    ret = inet_pton(af, ip, &to4->sin_addr);
859
1133
  }
860
1134
  if(ret < 0 ){
861
1135
    int e = errno;
931
1205
    goto mandos_end;
932
1206
  }
933
1207
  
934
 
  if(af == AF_INET6){
935
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
936
 
                  sizeof(struct sockaddr_in6));
937
 
  } else {
938
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
939
 
                  sizeof(struct sockaddr_in));
940
 
  }
941
 
  if(ret < 0){
942
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
943
 
      int e = errno;
944
 
      perror_plus("connect");
945
 
      errno = e;
946
 
    }
947
 
    goto mandos_end;
948
 
  }
949
 
  
950
 
  if(quit_now){
951
 
    errno = EINTR;
952
 
    goto mandos_end;
 
1208
  while(true){
 
1209
    if(af == AF_INET6){
 
1210
      ret = connect(tcp_sd, (struct sockaddr *)&to,
 
1211
                    sizeof(struct sockaddr_in6));
 
1212
    } else {
 
1213
      ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
1214
                    sizeof(struct sockaddr_in));
 
1215
    }
 
1216
    if(ret < 0){
 
1217
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
 
1218
         and if_index != AVAHI_IF_UNSPEC
 
1219
         and connect_to == NULL
 
1220
         and not route_added and
 
1221
         ((af == AF_INET6 and not
 
1222
           IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
 
1223
                                    &to)->sin6_addr)))
 
1224
          or (af == AF_INET and
 
1225
              /* Not a a IPv4LL address */
 
1226
              (ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
 
1227
               & 0xFFFF0000L) != 0xA9FE0000L))){
 
1228
        /* Work around Avahi bug - Avahi does not announce link-local
 
1229
           addresses if it has a global address, so local hosts with
 
1230
           *only* a link-local address (e.g. Mandos clients) cannot
 
1231
           connect to a Mandos server announced by Avahi on a server
 
1232
           host with a global address.  Work around this by retrying
 
1233
           with an explicit route added with the server's address.
 
1234
           
 
1235
           Avahi bug reference:
 
1236
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
 
1237
           https://bugs.debian.org/587961
 
1238
        */
 
1239
        if(debug){
 
1240
          fprintf_plus(stderr, "Mandos server unreachable, trying"
 
1241
                       " direct route\n");
 
1242
        }
 
1243
        int e = errno;
 
1244
        route_added = add_local_route(ip, if_index);
 
1245
        if(route_added){
 
1246
          continue;
 
1247
        }
 
1248
        errno = e;
 
1249
      }
 
1250
      if(errno != ECONNREFUSED or debug){
 
1251
        int e = errno;
 
1252
        perror_plus("connect");
 
1253
        errno = e;
 
1254
      }
 
1255
      goto mandos_end;
 
1256
    }
 
1257
    
 
1258
    if(quit_now){
 
1259
      errno = EINTR;
 
1260
      goto mandos_end;
 
1261
    }
 
1262
    break;
953
1263
  }
954
1264
  
955
1265
  const char *out = mandos_protocol_version;
1138
1448
  
1139
1449
 mandos_end:
1140
1450
  {
 
1451
    if(route_added){
 
1452
      if(not delete_local_route(ip, if_index)){
 
1453
        fprintf_plus(stderr, "Failed to delete local route to %s on"
 
1454
                     " interface %d", ip, if_index);
 
1455
      }
 
1456
    }
1141
1457
    int e = errno;
1142
1458
    free(decrypted_buffer);
1143
1459
    free(buffer);
1144
1460
    if(tcp_sd >= 0){
1145
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
1461
      ret = close(tcp_sd);
1146
1462
    }
1147
1463
    if(ret == -1){
1148
1464
      if(e == 0){
1312
1628
    errno = ret_errno;
1313
1629
    return false;
1314
1630
  }
1315
 
  strcpy(ifr->ifr_name, ifname);
 
1631
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
 
1632
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1316
1633
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1317
1634
  if(ret == -1){
1318
1635
    if(debug){
1569
1886
  }
1570
1887
}
1571
1888
 
1572
 
/* Set effective uid to 0, return errno */
1573
 
__attribute__((warn_unused_result))
1574
 
error_t raise_privileges(void){
1575
 
  error_t old_errno = errno;
1576
 
  error_t ret_errno = 0;
1577
 
  if(seteuid(0) == -1){
1578
 
    ret_errno = errno;
1579
 
  }
1580
 
  errno = old_errno;
1581
 
  return ret_errno;
1582
 
}
1583
 
 
1584
 
/* Set effective and real user ID to 0.  Return errno. */
1585
 
__attribute__((warn_unused_result))
1586
 
error_t raise_privileges_permanently(void){
1587
 
  error_t old_errno = errno;
1588
 
  error_t ret_errno = raise_privileges();
1589
 
  if(ret_errno != 0){
1590
 
    errno = old_errno;
1591
 
    return ret_errno;
1592
 
  }
1593
 
  if(setuid(0) == -1){
1594
 
    ret_errno = errno;
1595
 
  }
1596
 
  errno = old_errno;
1597
 
  return ret_errno;
1598
 
}
1599
 
 
1600
 
/* Set effective user ID to unprivileged saved user ID */
1601
 
__attribute__((warn_unused_result))
1602
 
error_t lower_privileges(void){
1603
 
  error_t old_errno = errno;
1604
 
  error_t ret_errno = 0;
1605
 
  if(seteuid(uid) == -1){
1606
 
    ret_errno = errno;
1607
 
  }
1608
 
  errno = old_errno;
1609
 
  return ret_errno;
1610
 
}
1611
 
 
1612
 
/* Lower privileges permanently */
1613
 
__attribute__((warn_unused_result))
1614
 
error_t lower_privileges_permanently(void){
1615
 
  error_t old_errno = errno;
1616
 
  error_t ret_errno = 0;
1617
 
  if(setuid(uid) == -1){
1618
 
    ret_errno = errno;
1619
 
  }
1620
 
  errno = old_errno;
1621
 
  return ret_errno;
1622
 
}
1623
 
 
1624
1889
__attribute__((nonnull))
1625
1890
void run_network_hooks(const char *mode, const char *interface,
1626
1891
                       const float delay){
1627
1892
  struct dirent **direntries = NULL;
1628
1893
  if(hookdir_fd == -1){
1629
 
    hookdir_fd = open(hookdir, O_RDONLY);
 
1894
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
 
1895
                      | O_CLOEXEC);
1630
1896
    if(hookdir_fd == -1){
1631
1897
      if(errno == ENOENT){
1632
1898
        if(debug){
1639
1905
      return;
1640
1906
    }
1641
1907
  }
1642
 
#ifdef __GLIBC__
1643
 
#if __GLIBC_PREREQ(2, 15)
1644
1908
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1645
1909
                           runnable_hook, alphasort);
1646
 
#else  /* not __GLIBC_PREREQ(2, 15) */
1647
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1648
 
                         alphasort);
1649
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
1650
 
#else   /* not __GLIBC__ */
1651
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1652
 
                         alphasort);
1653
 
#endif  /* not __GLIBC__ */
1654
1910
  if(numhooks == -1){
1655
1911
    perror_plus("scandir");
1656
1912
    return;
1657
1913
  }
1658
1914
  struct dirent *direntry;
1659
1915
  int ret;
1660
 
  int devnull = open("/dev/null", O_RDONLY);
 
1916
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
1917
  if(devnull == -1){
 
1918
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
1919
    return;
 
1920
  }
1661
1921
  for(int i = 0; i < numhooks; i++){
1662
1922
    direntry = direntries[i];
1663
1923
    if(debug){
1687
1947
        perror_plus("setgroups");
1688
1948
        _exit(EX_NOPERM);
1689
1949
      }
1690
 
      ret = dup2(devnull, STDIN_FILENO);
1691
 
      if(ret == -1){
1692
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
1693
 
        _exit(EX_OSERR);
1694
 
      }
1695
 
      ret = close(devnull);
1696
 
      if(ret == -1){
1697
 
        perror_plus("close");
1698
 
        _exit(EX_OSERR);
1699
 
      }
1700
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1701
 
      if(ret == -1){
1702
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1703
 
        _exit(EX_OSERR);
1704
 
      }
1705
1950
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1706
1951
      if(ret == -1){
1707
1952
        perror_plus("setenv");
1742
1987
          _exit(EX_OSERR);
1743
1988
        }
1744
1989
      }
1745
 
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
 
1990
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
 
1991
                                                   direntry->d_name,
 
1992
                                                   O_RDONLY));
1746
1993
      if(hook_fd == -1){
1747
1994
        perror_plus("openat");
1748
1995
        _exit(EXIT_FAILURE);
1749
1996
      }
1750
 
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1997
      if(close(hookdir_fd) == -1){
1751
1998
        perror_plus("close");
1752
1999
        _exit(EXIT_FAILURE);
1753
2000
      }
 
2001
      ret = dup2(devnull, STDIN_FILENO);
 
2002
      if(ret == -1){
 
2003
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
2004
        _exit(EX_OSERR);
 
2005
      }
 
2006
      ret = close(devnull);
 
2007
      if(ret == -1){
 
2008
        perror_plus("close");
 
2009
        _exit(EX_OSERR);
 
2010
      }
 
2011
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
2012
      if(ret == -1){
 
2013
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
2014
        _exit(EX_OSERR);
 
2015
      }
1754
2016
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
1755
2017
                 environ) == -1){
1756
2018
        perror_plus("fexecve");
1796
2058
    free(direntry);
1797
2059
  }
1798
2060
  free(direntries);
1799
 
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2061
  if(close(hookdir_fd) == -1){
1800
2062
    perror_plus("close");
1801
2063
  } else {
1802
2064
    hookdir_fd = -1;
1842
2104
    }
1843
2105
    
1844
2106
    if(quit_now){
1845
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2107
      ret = close(sd);
1846
2108
      if(ret == -1){
1847
2109
        perror_plus("close");
1848
2110
      }
1898
2160
    }
1899
2161
    
1900
2162
    /* Close the socket */
1901
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2163
    ret = close(sd);
1902
2164
    if(ret == -1){
1903
2165
      perror_plus("close");
1904
2166
    }
1986
2248
    }
1987
2249
    
1988
2250
    /* Close the socket */
1989
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2251
    int ret = close(sd);
1990
2252
    if(ret == -1){
1991
2253
      perror_plus("close");
1992
2254
    }
2008
2270
 
2009
2271
int main(int argc, char *argv[]){
2010
2272
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2011
 
                        .priority = "SECURE256:!CTYPE-X.509:"
2012
 
                        "+CTYPE-OPENPGP:!RSA", .current_server = NULL,
2013
 
                        .interfaces = NULL, .interfaces_size = 0 };
 
2273
                        .priority = "SECURE256:!CTYPE-X.509"
 
2274
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
 
2275
                        .current_server = NULL, .interfaces = NULL,
 
2276
                        .interfaces_size = 0 };
2014
2277
  AvahiSServiceBrowser *sb = NULL;
2015
2278
  error_t ret_errno;
2016
2279
  int ret;
2025
2288
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2026
2289
  const char *seckey = PATHDIR "/" SECKEY;
2027
2290
  const char *pubkey = PATHDIR "/" PUBKEY;
 
2291
  const char *dh_params_file = NULL;
2028
2292
  char *interfaces_hooks = NULL;
2029
2293
  
2030
2294
  bool gnutls_initialized = false;
2083
2347
        .doc = "Bit length of the prime number used in the"
2084
2348
        " Diffie-Hellman key exchange",
2085
2349
        .group = 2 },
 
2350
      { .name = "dh-params", .key = 134,
 
2351
        .arg = "FILE",
 
2352
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
 
2353
        " for the Diffie-Hellman key exchange",
 
2354
        .group = 2 },
2086
2355
      { .name = "priority", .key = 130,
2087
2356
        .arg = "STRING",
2088
2357
        .doc = "GnuTLS priority string for the TLS handshake",
2143
2412
        }
2144
2413
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2145
2414
        break;
 
2415
      case 134:                 /* --dh-params */
 
2416
        dh_params_file = arg;
 
2417
        break;
2146
2418
      case 130:                 /* --priority */
2147
2419
        mc.priority = arg;
2148
2420
        break;
2204
2476
      goto end;
2205
2477
    }
2206
2478
  }
2207
 
    
 
2479
  
2208
2480
  {
2209
2481
    /* Work around Debian bug #633582:
2210
2482
       <http://bugs.debian.org/633582> */
2234
2506
              }
2235
2507
            }
2236
2508
          }
2237
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2509
          close(seckey_fd);
2238
2510
        }
2239
2511
      }
2240
 
    
 
2512
      
2241
2513
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2242
2514
        int pubkey_fd = open(pubkey, O_RDONLY);
2243
2515
        if(pubkey_fd == -1){
2255
2527
              }
2256
2528
            }
2257
2529
          }
2258
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
2259
 
        }
2260
 
      }
2261
 
    
 
2530
          close(pubkey_fd);
 
2531
        }
 
2532
      }
 
2533
      
 
2534
      if(dh_params_file != NULL
 
2535
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
 
2536
        int dhparams_fd = open(dh_params_file, O_RDONLY);
 
2537
        if(dhparams_fd == -1){
 
2538
          perror_plus("open");
 
2539
        } else {
 
2540
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
 
2541
          if(ret == -1){
 
2542
            perror_plus("fstat");
 
2543
          } else {
 
2544
            if(S_ISREG(st.st_mode)
 
2545
               and st.st_uid == 0 and st.st_gid == 0){
 
2546
              ret = fchown(dhparams_fd, uid, gid);
 
2547
              if(ret == -1){
 
2548
                perror_plus("fchown");
 
2549
              }
 
2550
            }
 
2551
          }
 
2552
          close(dhparams_fd);
 
2553
        }
 
2554
      }
 
2555
      
2262
2556
      /* Lower privileges */
2263
2557
      ret_errno = lower_privileges();
2264
2558
      if(ret_errno != 0){
2438
2732
      errno = bring_up_interface(interface, delay);
2439
2733
      if(not interface_was_up){
2440
2734
        if(errno != 0){
2441
 
          perror_plus("Failed to bring up interface");
 
2735
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
 
2736
                       " %s\n", interface, strerror(errno));
2442
2737
        } else {
2443
2738
          errno = argz_add(&interfaces_to_take_down,
2444
2739
                           &interfaces_to_take_down_size,
2467
2762
    goto end;
2468
2763
  }
2469
2764
  
2470
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2765
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
2471
2766
  if(ret == -1){
2472
2767
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2473
2768
    exitcode = EX_UNAVAILABLE;
2662
2957
  
2663
2958
  if(gnutls_initialized){
2664
2959
    gnutls_certificate_free_credentials(mc.cred);
2665
 
    gnutls_global_deinit();
2666
2960
    gnutls_dh_params_deinit(mc.dh_params);
2667
2961
  }
2668
2962
  
2733
3027
  /* Removes the GPGME temp directory and all files inside */
2734
3028
  if(tempdir != NULL){
2735
3029
    struct dirent **direntries = NULL;
2736
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY |
2737
 
                                                  O_NOFOLLOW));
 
3030
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
 
3031
                                                  | O_NOFOLLOW
 
3032
                                                  | O_DIRECTORY
 
3033
                                                  | O_PATH));
2738
3034
    if(tempdir_fd == -1){
2739
3035
      perror_plus("open");
2740
3036
    } else {
2741
 
#ifdef __GLIBC__
2742
 
#if __GLIBC_PREREQ(2, 15)
2743
3037
      int numentries = scandirat(tempdir_fd, ".", &direntries,
2744
3038
                                 notdotentries, alphasort);
2745
 
#else  /* not __GLIBC_PREREQ(2, 15) */
2746
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2747
 
                               alphasort);
2748
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
2749
 
#else   /* not __GLIBC__ */
2750
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2751
 
                               alphasort);
2752
 
#endif  /* not __GLIBC__ */
2753
3039
      if(numentries >= 0){
2754
3040
        for(int i = 0; i < numentries; i++){
2755
3041
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
2771
3057
          perror_plus("rmdir");
2772
3058
        }
2773
3059
      }
2774
 
      TEMP_FAILURE_RETRY(close(tempdir_fd));
 
3060
      close(tempdir_fd);
2775
3061
    }
2776
3062
  }
2777
3063