/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

  • Committer: Teddy Hogeborn
  • Date: 2016-02-28 20:34:59 UTC
  • mto: (237.7.594 trunk)
  • mto: This revision was merged to the branch mainline in revision 333.
  • 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
    }
493
493
  return plaintext_length;
494
494
}
495
495
 
 
496
__attribute__((warn_unused_result, const))
 
497
static const char *safe_string(const char *str){
 
498
  if(str == NULL)
 
499
    return "(unknown)";
 
500
  return str;
 
501
}
 
502
 
496
503
__attribute__((warn_unused_result))
497
504
static const char *safer_gnutls_strerror(int value){
498
505
  const char *ret = gnutls_strerror(value);
499
 
  if(ret == NULL)
500
 
    ret = "(unknown)";
501
 
  return ret;
 
506
  return safe_string(ret);
502
507
}
503
508
 
504
509
/* GnuTLS log function callback */
508
513
  fprintf_plus(stderr, "GnuTLS: %s", string);
509
514
}
510
515
 
511
 
__attribute__((nonnull, warn_unused_result))
 
516
__attribute__((nonnull(1, 2, 4), warn_unused_result))
512
517
static int init_gnutls_global(const char *pubkeyfilename,
513
518
                              const char *seckeyfilename,
 
519
                              const char *dhparamsfilename,
514
520
                              mandos_context *mc){
515
521
  int ret;
 
522
  unsigned int uret;
516
523
  
517
524
  if(debug){
518
525
    fprintf_plus(stderr, "Initializing GnuTLS\n");
519
526
  }
520
527
  
521
 
  ret = gnutls_global_init();
522
 
  if(ret != GNUTLS_E_SUCCESS){
523
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
524
 
                 safer_gnutls_strerror(ret));
525
 
    return -1;
526
 
  }
527
 
  
528
528
  if(debug){
529
529
    /* "Use a log level over 10 to enable all debugging options."
530
530
     * - GnuTLS manual
538
538
  if(ret != GNUTLS_E_SUCCESS){
539
539
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
540
540
                 safer_gnutls_strerror(ret));
541
 
    gnutls_global_deinit();
542
541
    return -1;
543
542
  }
544
543
  
569
568
                 safer_gnutls_strerror(ret));
570
569
    goto globalfail;
571
570
  }
572
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
573
 
  if(ret != GNUTLS_E_SUCCESS){
574
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
575
 
                 safer_gnutls_strerror(ret));
576
 
    goto globalfail;
577
 
  }
578
 
  
 
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;
 
582
      while(true){
 
583
        params_capacity = incbuffer((char **)&params.data,
 
584
                                    (size_t)params.size,
 
585
                                    (size_t)params_capacity);
 
586
        if(params_capacity == 0){
 
587
          perror_plus("incbuffer");
 
588
          free(params.data);
 
589
          params.data = NULL;
 
590
          dhparamsfilename = NULL;
 
591
          break;
 
592
        }
 
593
        ssize_t bytes_read = read(dhpfile,
 
594
                                  params.data + params.size,
 
595
                                  BUFFER_SIZE);
 
596
        /* EOF */
 
597
        if(bytes_read == 0){
 
598
          break;
 
599
        }
 
600
        /* check bytes_read for failure */
 
601
        if(bytes_read < 0){
 
602
          perror_plus("read");
 
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);
 
672
          if(ret != GNUTLS_E_SUCCESS){
 
673
            fprintf_plus(stderr, "Error initializing OpenPGP key"
 
674
                         " structure: %s",
 
675
                         safer_gnutls_strerror(ret));
 
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
            }
 
700
          }
 
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)));
 
710
          }
 
711
        }
 
712
      }
 
713
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
 
714
      if(uret != 0){
 
715
        mc->dh_bits = uret;
 
716
        if(debug){
 
717
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
 
718
                       " implies %u DH bits; using that.\n",
 
719
                       safe_string(gnutls_sec_param_get_name
 
720
                                   (sec_param)),
 
721
                       mc->dh_bits);
 
722
        }
 
723
      } else {
 
724
        fprintf_plus(stderr, "Failed to get implied number of DH"
 
725
                     " bits for security parameter \"%s\"): %s\n",
 
726
                     safe_string(gnutls_sec_param_get_name
 
727
                                 (sec_param)),
 
728
                     safer_gnutls_strerror(ret));
 
729
        goto globalfail;
 
730
      }
 
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,
 
739
                   safer_gnutls_strerror(ret));
 
740
      goto globalfail;
 
741
    }
 
742
  }
579
743
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
580
744
  
581
745
  return 0;
583
747
 globalfail:
584
748
  
585
749
  gnutls_certificate_free_credentials(mc->cred);
586
 
  gnutls_global_deinit();
587
750
  gnutls_dh_params_deinit(mc->dh_params);
588
751
  return -1;
589
752
}
641
804
  /* ignore client certificate if any. */
642
805
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
643
806
  
644
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
645
 
  
646
807
  return 0;
647
808
}
648
809
 
650
811
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
651
812
                      __attribute__((unused)) const char *txt){}
652
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
 
653
1032
/* Called when a Mandos server is found */
654
1033
__attribute__((nonnull, warn_unused_result))
655
1034
static int start_mandos_communication(const char *ip, in_port_t port,
666
1045
  int retval = -1;
667
1046
  gnutls_session_t session;
668
1047
  int pf;                       /* Protocol family */
 
1048
  bool route_added = false;
669
1049
  
670
1050
  errno = 0;
671
1051
  
729
1109
                 PRIuMAX "\n", ip, (uintmax_t)port);
730
1110
  }
731
1111
  
732
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
1112
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
733
1113
  if(tcp_sd < 0){
734
1114
    int e = errno;
735
1115
    perror_plus("socket");
742
1122
    goto mandos_end;
743
1123
  }
744
1124
  
745
 
  memset(&to, 0, sizeof(to));
746
1125
  if(af == AF_INET6){
747
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
748
 
    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);
749
1129
  } else {                      /* IPv4 */
750
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
751
 
    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);
752
1133
  }
753
1134
  if(ret < 0 ){
754
1135
    int e = errno;
824
1205
    goto mandos_end;
825
1206
  }
826
1207
  
827
 
  if(af == AF_INET6){
828
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
829
 
                  sizeof(struct sockaddr_in6));
830
 
  } else {
831
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
832
 
                  sizeof(struct sockaddr_in));
833
 
  }
834
 
  if(ret < 0){
835
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
836
 
      int e = errno;
837
 
      perror_plus("connect");
838
 
      errno = e;
839
 
    }
840
 
    goto mandos_end;
841
 
  }
842
 
  
843
 
  if(quit_now){
844
 
    errno = EINTR;
845
 
    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;
846
1263
  }
847
1264
  
848
1265
  const char *out = mandos_protocol_version;
1031
1448
  
1032
1449
 mandos_end:
1033
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
    }
1034
1457
    int e = errno;
1035
1458
    free(decrypted_buffer);
1036
1459
    free(buffer);
1037
1460
    if(tcp_sd >= 0){
1038
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
1461
      ret = close(tcp_sd);
1039
1462
    }
1040
1463
    if(ret == -1){
1041
1464
      if(e == 0){
1205
1628
    errno = ret_errno;
1206
1629
    return false;
1207
1630
  }
1208
 
  strcpy(ifr->ifr_name, ifname);
 
1631
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
 
1632
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1209
1633
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1210
1634
  if(ret == -1){
1211
1635
    if(debug){
1462
1886
  }
1463
1887
}
1464
1888
 
1465
 
/* Set effective uid to 0, return errno */
1466
 
__attribute__((warn_unused_result))
1467
 
error_t raise_privileges(void){
1468
 
  error_t old_errno = errno;
1469
 
  error_t ret_errno = 0;
1470
 
  if(seteuid(0) == -1){
1471
 
    ret_errno = errno;
1472
 
  }
1473
 
  errno = old_errno;
1474
 
  return ret_errno;
1475
 
}
1476
 
 
1477
 
/* Set effective and real user ID to 0.  Return errno. */
1478
 
__attribute__((warn_unused_result))
1479
 
error_t raise_privileges_permanently(void){
1480
 
  error_t old_errno = errno;
1481
 
  error_t ret_errno = raise_privileges();
1482
 
  if(ret_errno != 0){
1483
 
    errno = old_errno;
1484
 
    return ret_errno;
1485
 
  }
1486
 
  if(setuid(0) == -1){
1487
 
    ret_errno = errno;
1488
 
  }
1489
 
  errno = old_errno;
1490
 
  return ret_errno;
1491
 
}
1492
 
 
1493
 
/* Set effective user ID to unprivileged saved user ID */
1494
 
__attribute__((warn_unused_result))
1495
 
error_t lower_privileges(void){
1496
 
  error_t old_errno = errno;
1497
 
  error_t ret_errno = 0;
1498
 
  if(seteuid(uid) == -1){
1499
 
    ret_errno = errno;
1500
 
  }
1501
 
  errno = old_errno;
1502
 
  return ret_errno;
1503
 
}
1504
 
 
1505
 
/* Lower privileges permanently */
1506
 
__attribute__((warn_unused_result))
1507
 
error_t lower_privileges_permanently(void){
1508
 
  error_t old_errno = errno;
1509
 
  error_t ret_errno = 0;
1510
 
  if(setuid(uid) == -1){
1511
 
    ret_errno = errno;
1512
 
  }
1513
 
  errno = old_errno;
1514
 
  return ret_errno;
1515
 
}
1516
 
 
1517
1889
__attribute__((nonnull))
1518
1890
void run_network_hooks(const char *mode, const char *interface,
1519
1891
                       const float delay){
1520
1892
  struct dirent **direntries = NULL;
1521
1893
  if(hookdir_fd == -1){
1522
 
    hookdir_fd = open(hookdir, O_RDONLY);
 
1894
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
 
1895
                      | O_CLOEXEC);
1523
1896
    if(hookdir_fd == -1){
1524
1897
      if(errno == ENOENT){
1525
1898
        if(debug){
1532
1905
      return;
1533
1906
    }
1534
1907
  }
1535
 
#ifdef __GLIBC__
1536
 
#if __GLIBC_PREREQ(2, 15)
1537
1908
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1538
1909
                           runnable_hook, alphasort);
1539
 
#else  /* not __GLIBC_PREREQ(2, 15) */
1540
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1541
 
                         alphasort);
1542
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
1543
 
#else   /* not __GLIBC__ */
1544
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1545
 
                         alphasort);
1546
 
#endif  /* not __GLIBC__ */
1547
1910
  if(numhooks == -1){
1548
1911
    perror_plus("scandir");
1549
1912
    return;
1550
1913
  }
1551
1914
  struct dirent *direntry;
1552
1915
  int ret;
1553
 
  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
  }
1554
1921
  for(int i = 0; i < numhooks; i++){
1555
1922
    direntry = direntries[i];
1556
1923
    if(debug){
1580
1947
        perror_plus("setgroups");
1581
1948
        _exit(EX_NOPERM);
1582
1949
      }
1583
 
      ret = dup2(devnull, STDIN_FILENO);
1584
 
      if(ret == -1){
1585
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
1586
 
        _exit(EX_OSERR);
1587
 
      }
1588
 
      ret = close(devnull);
1589
 
      if(ret == -1){
1590
 
        perror_plus("close");
1591
 
        _exit(EX_OSERR);
1592
 
      }
1593
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1594
 
      if(ret == -1){
1595
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1596
 
        _exit(EX_OSERR);
1597
 
      }
1598
1950
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1599
1951
      if(ret == -1){
1600
1952
        perror_plus("setenv");
1635
1987
          _exit(EX_OSERR);
1636
1988
        }
1637
1989
      }
1638
 
      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));
1639
1993
      if(hook_fd == -1){
1640
1994
        perror_plus("openat");
1641
1995
        _exit(EXIT_FAILURE);
1642
1996
      }
1643
 
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1997
      if(close(hookdir_fd) == -1){
1644
1998
        perror_plus("close");
1645
1999
        _exit(EXIT_FAILURE);
1646
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
      }
1647
2016
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
1648
2017
                 environ) == -1){
1649
2018
        perror_plus("fexecve");
1650
2019
        _exit(EXIT_FAILURE);
1651
2020
      }
1652
2021
    } else {
 
2022
      if(hook_pid == -1){
 
2023
        perror_plus("fork");
 
2024
        free(direntry);
 
2025
        continue;
 
2026
      }
1653
2027
      int status;
1654
2028
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1655
2029
        perror_plus("waitpid");
1684
2058
    free(direntry);
1685
2059
  }
1686
2060
  free(direntries);
1687
 
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2061
  if(close(hookdir_fd) == -1){
1688
2062
    perror_plus("close");
1689
2063
  } else {
1690
2064
    hookdir_fd = -1;
1730
2104
    }
1731
2105
    
1732
2106
    if(quit_now){
1733
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2107
      ret = close(sd);
1734
2108
      if(ret == -1){
1735
2109
        perror_plus("close");
1736
2110
      }
1786
2160
    }
1787
2161
    
1788
2162
    /* Close the socket */
1789
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2163
    ret = close(sd);
1790
2164
    if(ret == -1){
1791
2165
      perror_plus("close");
1792
2166
    }
1874
2248
    }
1875
2249
    
1876
2250
    /* Close the socket */
1877
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2251
    int ret = close(sd);
1878
2252
    if(ret == -1){
1879
2253
      perror_plus("close");
1880
2254
    }
1895
2269
}
1896
2270
 
1897
2271
int main(int argc, char *argv[]){
1898
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1899
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1900
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1901
 
                        .interfaces = NULL, .interfaces_size = 0 };
 
2272
  mandos_context mc = { .server = NULL, .dh_bits = 0,
 
2273
                        .priority = "SECURE256:!CTYPE-X.509"
 
2274
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
 
2275
                        .current_server = NULL, .interfaces = NULL,
 
2276
                        .interfaces_size = 0 };
1902
2277
  AvahiSServiceBrowser *sb = NULL;
1903
2278
  error_t ret_errno;
1904
2279
  int ret;
1913
2288
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1914
2289
  const char *seckey = PATHDIR "/" SECKEY;
1915
2290
  const char *pubkey = PATHDIR "/" PUBKEY;
 
2291
  const char *dh_params_file = NULL;
1916
2292
  char *interfaces_hooks = NULL;
1917
2293
  
1918
2294
  bool gnutls_initialized = false;
1971
2347
        .doc = "Bit length of the prime number used in the"
1972
2348
        " Diffie-Hellman key exchange",
1973
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 },
1974
2355
      { .name = "priority", .key = 130,
1975
2356
        .arg = "STRING",
1976
2357
        .doc = "GnuTLS priority string for the TLS handshake",
2031
2412
        }
2032
2413
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2033
2414
        break;
 
2415
      case 134:                 /* --dh-params */
 
2416
        dh_params_file = arg;
 
2417
        break;
2034
2418
      case 130:                 /* --priority */
2035
2419
        mc.priority = arg;
2036
2420
        break;
2092
2476
      goto end;
2093
2477
    }
2094
2478
  }
2095
 
    
 
2479
  
2096
2480
  {
2097
2481
    /* Work around Debian bug #633582:
2098
2482
       <http://bugs.debian.org/633582> */
2122
2506
              }
2123
2507
            }
2124
2508
          }
2125
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2509
          close(seckey_fd);
2126
2510
        }
2127
2511
      }
2128
 
    
 
2512
      
2129
2513
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2130
2514
        int pubkey_fd = open(pubkey, O_RDONLY);
2131
2515
        if(pubkey_fd == -1){
2143
2527
              }
2144
2528
            }
2145
2529
          }
2146
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
2147
 
        }
2148
 
      }
2149
 
    
 
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
      
2150
2556
      /* Lower privileges */
2151
2557
      ret_errno = lower_privileges();
2152
2558
      if(ret_errno != 0){
2326
2732
      errno = bring_up_interface(interface, delay);
2327
2733
      if(not interface_was_up){
2328
2734
        if(errno != 0){
2329
 
          perror_plus("Failed to bring up interface");
 
2735
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
 
2736
                       " %s\n", interface, strerror(errno));
2330
2737
        } else {
2331
2738
          errno = argz_add(&interfaces_to_take_down,
2332
2739
                           &interfaces_to_take_down_size,
2355
2762
    goto end;
2356
2763
  }
2357
2764
  
2358
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2765
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
2359
2766
  if(ret == -1){
2360
2767
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2361
2768
    exitcode = EX_UNAVAILABLE;
2550
2957
  
2551
2958
  if(gnutls_initialized){
2552
2959
    gnutls_certificate_free_credentials(mc.cred);
2553
 
    gnutls_global_deinit();
2554
2960
    gnutls_dh_params_deinit(mc.dh_params);
2555
2961
  }
2556
2962
  
2621
3027
  /* Removes the GPGME temp directory and all files inside */
2622
3028
  if(tempdir != NULL){
2623
3029
    struct dirent **direntries = NULL;
2624
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY |
2625
 
                                                  O_NOFOLLOW));
 
3030
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
 
3031
                                                  | O_NOFOLLOW
 
3032
                                                  | O_DIRECTORY
 
3033
                                                  | O_PATH));
2626
3034
    if(tempdir_fd == -1){
2627
3035
      perror_plus("open");
2628
3036
    } else {
2629
 
#ifdef __GLIBC__
2630
 
#if __GLIBC_PREREQ(2, 15)
2631
3037
      int numentries = scandirat(tempdir_fd, ".", &direntries,
2632
3038
                                 notdotentries, alphasort);
2633
 
#else  /* not __GLIBC_PREREQ(2, 15) */
2634
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2635
 
                               alphasort);
2636
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
2637
 
#else   /* not __GLIBC__ */
2638
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2639
 
                               alphasort);
2640
 
#endif  /* not __GLIBC__ */
2641
3039
      if(numentries >= 0){
2642
3040
        for(int i = 0; i < numentries; i++){
2643
3041
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
2659
3057
          perror_plus("rmdir");
2660
3058
        }
2661
3059
      }
2662
 
      TEMP_FAILURE_RETRY(close(tempdir_fd));
 
3060
      close(tempdir_fd);
2663
3061
    }
2664
3062
  }
2665
3063