/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: 2014-07-12 13:13:28 UTC
  • Revision ID: teddy@recompile.se-20140712131328-gdkvcea7f9rov7bn
mandos-client: Fix minor memory leak on memory full or clock failure.

* plugins.d/mandos-client.c (add_server): On any errors, free
                                          new_server and its contents
                                          before returning.

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-2016 Teddy Hogeborn
13
 
 * Copyright © 2008-2016 Björn Påhlsson
 
12
 * Copyright © 2008-2014 Teddy Hogeborn
 
13
 * Copyright © 2008-2014 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>             /* strcmp(), strlen(), strerror(),
50
 
                                   asprintf(), strncpy() */
 
49
#include <string.h>             /* memset(), strcmp(), strlen(),
 
50
                                   strerror(), asprintf(), strcpy() */
51
51
#include <sys/ioctl.h>          /* ioctl */
52
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
53
                                   sockaddr_in6, PF_INET6,
240
240
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
241
241
  if(ret == -1){
242
242
    perror_plus("clock_gettime");
243
 
#ifdef __GNUC__
244
 
#pragma GCC diagnostic push
245
 
#pragma GCC diagnostic ignored "-Wcast-qual"
246
 
#endif
247
 
    free((char *)(new_server->ip));
248
 
#ifdef __GNUC__
249
 
#pragma GCC diagnostic pop
250
 
#endif
 
243
    free(new_server->ip);
251
244
    free(new_server);
252
245
    return false;
253
246
  }
305
298
      return false;
306
299
    }
307
300
    
308
 
    ret = close(fd);
 
301
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
309
302
    if(ret == -1){
310
303
      perror_plus("close");
311
304
    }
493
486
  return plaintext_length;
494
487
}
495
488
 
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
 
 
503
489
__attribute__((warn_unused_result))
504
490
static const char *safer_gnutls_strerror(int value){
505
491
  const char *ret = gnutls_strerror(value);
506
 
  return safe_string(ret);
 
492
  if(ret == NULL)
 
493
    ret = "(unknown)";
 
494
  return ret;
507
495
}
508
496
 
509
497
/* GnuTLS log function callback */
513
501
  fprintf_plus(stderr, "GnuTLS: %s", string);
514
502
}
515
503
 
516
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
 
504
__attribute__((nonnull, warn_unused_result))
517
505
static int init_gnutls_global(const char *pubkeyfilename,
518
506
                              const char *seckeyfilename,
519
 
                              const char *dhparamsfilename,
520
507
                              mandos_context *mc){
521
508
  int ret;
522
 
  unsigned int uret;
523
509
  
524
510
  if(debug){
525
511
    fprintf_plus(stderr, "Initializing GnuTLS\n");
526
512
  }
527
513
  
 
514
  ret = gnutls_global_init();
 
515
  if(ret != GNUTLS_E_SUCCESS){
 
516
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
517
                 safer_gnutls_strerror(ret));
 
518
    return -1;
 
519
  }
 
520
  
528
521
  if(debug){
529
522
    /* "Use a log level over 10 to enable all debugging options."
530
523
     * - GnuTLS manual
538
531
  if(ret != GNUTLS_E_SUCCESS){
539
532
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
540
533
                 safer_gnutls_strerror(ret));
 
534
    gnutls_global_deinit();
541
535
    return -1;
542
536
  }
543
537
  
568
562
                 safer_gnutls_strerror(ret));
569
563
    goto globalfail;
570
564
  }
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
 
  }
 
565
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
566
  if(ret != GNUTLS_E_SUCCESS){
 
567
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
568
                 safer_gnutls_strerror(ret));
 
569
    goto globalfail;
 
570
  }
 
571
  
743
572
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
744
573
  
745
574
  return 0;
747
576
 globalfail:
748
577
  
749
578
  gnutls_certificate_free_credentials(mc->cred);
 
579
  gnutls_global_deinit();
750
580
  gnutls_dh_params_deinit(mc->dh_params);
751
581
  return -1;
752
582
}
804
634
  /* ignore client certificate if any. */
805
635
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
806
636
  
 
637
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
638
  
807
639
  return 0;
808
640
}
809
641
 
811
643
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
812
644
                      __attribute__((unused)) const char *txt){}
813
645
 
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
 
 
1032
646
/* Called when a Mandos server is found */
1033
647
__attribute__((nonnull, warn_unused_result))
1034
648
static int start_mandos_communication(const char *ip, in_port_t port,
1045
659
  int retval = -1;
1046
660
  gnutls_session_t session;
1047
661
  int pf;                       /* Protocol family */
1048
 
  bool route_added = false;
1049
662
  
1050
663
  errno = 0;
1051
664
  
1109
722
                 PRIuMAX "\n", ip, (uintmax_t)port);
1110
723
  }
1111
724
  
1112
 
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
 
725
  tcp_sd = socket(pf, SOCK_STREAM, 0);
1113
726
  if(tcp_sd < 0){
1114
727
    int e = errno;
1115
728
    perror_plus("socket");
1122
735
    goto mandos_end;
1123
736
  }
1124
737
  
 
738
  memset(&to, 0, sizeof(to));
1125
739
  if(af == AF_INET6){
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);
 
740
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
741
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
1129
742
  } else {                      /* IPv4 */
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);
 
743
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
744
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
1133
745
  }
1134
746
  if(ret < 0 ){
1135
747
    int e = errno;
1205
817
    goto mandos_end;
1206
818
  }
1207
819
  
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;
 
820
  if(af == AF_INET6){
 
821
    ret = connect(tcp_sd, (struct sockaddr *)&to,
 
822
                  sizeof(struct sockaddr_in6));
 
823
  } else {
 
824
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
825
                  sizeof(struct sockaddr_in));
 
826
  }
 
827
  if(ret < 0){
 
828
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
829
      int e = errno;
 
830
      perror_plus("connect");
 
831
      errno = e;
 
832
    }
 
833
    goto mandos_end;
 
834
  }
 
835
  
 
836
  if(quit_now){
 
837
    errno = EINTR;
 
838
    goto mandos_end;
1263
839
  }
1264
840
  
1265
841
  const char *out = mandos_protocol_version;
1448
1024
  
1449
1025
 mandos_end:
1450
1026
  {
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
 
    }
1457
1027
    int e = errno;
1458
1028
    free(decrypted_buffer);
1459
1029
    free(buffer);
1460
1030
    if(tcp_sd >= 0){
1461
 
      ret = close(tcp_sd);
 
1031
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1462
1032
    }
1463
1033
    if(ret == -1){
1464
1034
      if(e == 0){
1499
1069
     timed out */
1500
1070
  
1501
1071
  if(quit_now){
1502
 
    avahi_s_service_resolver_free(r);
1503
1072
    return;
1504
1073
  }
1505
1074
  
1628
1197
    errno = ret_errno;
1629
1198
    return false;
1630
1199
  }
1631
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1632
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
 
1200
  strcpy(ifr->ifr_name, ifname);
1633
1201
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1634
1202
  if(ret == -1){
1635
1203
    if(debug){
1886
1454
  }
1887
1455
}
1888
1456
 
 
1457
/* Set effective uid to 0, return errno */
 
1458
__attribute__((warn_unused_result))
 
1459
error_t raise_privileges(void){
 
1460
  error_t old_errno = errno;
 
1461
  error_t ret_errno = 0;
 
1462
  if(seteuid(0) == -1){
 
1463
    ret_errno = errno;
 
1464
  }
 
1465
  errno = old_errno;
 
1466
  return ret_errno;
 
1467
}
 
1468
 
 
1469
/* Set effective and real user ID to 0.  Return errno. */
 
1470
__attribute__((warn_unused_result))
 
1471
error_t raise_privileges_permanently(void){
 
1472
  error_t old_errno = errno;
 
1473
  error_t ret_errno = raise_privileges();
 
1474
  if(ret_errno != 0){
 
1475
    errno = old_errno;
 
1476
    return ret_errno;
 
1477
  }
 
1478
  if(setuid(0) == -1){
 
1479
    ret_errno = errno;
 
1480
  }
 
1481
  errno = old_errno;
 
1482
  return ret_errno;
 
1483
}
 
1484
 
 
1485
/* Set effective user ID to unprivileged saved user ID */
 
1486
__attribute__((warn_unused_result))
 
1487
error_t lower_privileges(void){
 
1488
  error_t old_errno = errno;
 
1489
  error_t ret_errno = 0;
 
1490
  if(seteuid(uid) == -1){
 
1491
    ret_errno = errno;
 
1492
  }
 
1493
  errno = old_errno;
 
1494
  return ret_errno;
 
1495
}
 
1496
 
 
1497
/* Lower privileges permanently */
 
1498
__attribute__((warn_unused_result))
 
1499
error_t lower_privileges_permanently(void){
 
1500
  error_t old_errno = errno;
 
1501
  error_t ret_errno = 0;
 
1502
  if(setuid(uid) == -1){
 
1503
    ret_errno = errno;
 
1504
  }
 
1505
  errno = old_errno;
 
1506
  return ret_errno;
 
1507
}
 
1508
 
1889
1509
__attribute__((nonnull))
1890
1510
void run_network_hooks(const char *mode, const char *interface,
1891
1511
                       const float delay){
1892
1512
  struct dirent **direntries = NULL;
1893
1513
  if(hookdir_fd == -1){
1894
 
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
1895
 
                      | O_CLOEXEC);
 
1514
    hookdir_fd = open(hookdir, O_RDONLY);
1896
1515
    if(hookdir_fd == -1){
1897
1516
      if(errno == ENOENT){
1898
1517
        if(debug){
1905
1524
      return;
1906
1525
    }
1907
1526
  }
 
1527
#ifdef __GLIBC__
 
1528
#if __GLIBC_PREREQ(2, 15)
1908
1529
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1909
1530
                           runnable_hook, alphasort);
 
1531
#else  /* not __GLIBC_PREREQ(2, 15) */
 
1532
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1533
                         alphasort);
 
1534
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
1535
#else   /* not __GLIBC__ */
 
1536
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1537
                         alphasort);
 
1538
#endif  /* not __GLIBC__ */
1910
1539
  if(numhooks == -1){
1911
1540
    perror_plus("scandir");
1912
1541
    return;
1913
1542
  }
1914
1543
  struct dirent *direntry;
1915
1544
  int ret;
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
 
  }
 
1545
  int devnull = open("/dev/null", O_RDONLY);
1921
1546
  for(int i = 0; i < numhooks; i++){
1922
1547
    direntry = direntries[i];
1923
1548
    if(debug){
1947
1572
        perror_plus("setgroups");
1948
1573
        _exit(EX_NOPERM);
1949
1574
      }
 
1575
      ret = dup2(devnull, STDIN_FILENO);
 
1576
      if(ret == -1){
 
1577
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
1578
        _exit(EX_OSERR);
 
1579
      }
 
1580
      ret = close(devnull);
 
1581
      if(ret == -1){
 
1582
        perror_plus("close");
 
1583
        _exit(EX_OSERR);
 
1584
      }
 
1585
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
1586
      if(ret == -1){
 
1587
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
1588
        _exit(EX_OSERR);
 
1589
      }
1950
1590
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1951
1591
      if(ret == -1){
1952
1592
        perror_plus("setenv");
1987
1627
          _exit(EX_OSERR);
1988
1628
        }
1989
1629
      }
1990
 
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
1991
 
                                                   direntry->d_name,
1992
 
                                                   O_RDONLY));
 
1630
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
1993
1631
      if(hook_fd == -1){
1994
1632
        perror_plus("openat");
1995
1633
        _exit(EXIT_FAILURE);
1996
1634
      }
1997
 
      if(close(hookdir_fd) == -1){
 
1635
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
1998
1636
        perror_plus("close");
1999
1637
        _exit(EXIT_FAILURE);
2000
1638
      }
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
 
      }
2016
1639
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
2017
1640
                 environ) == -1){
2018
1641
        perror_plus("fexecve");
2019
1642
        _exit(EXIT_FAILURE);
2020
1643
      }
2021
1644
    } else {
2022
 
      if(hook_pid == -1){
2023
 
        perror_plus("fork");
2024
 
        free(direntry);
2025
 
        continue;
2026
 
      }
2027
1645
      int status;
2028
1646
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
2029
1647
        perror_plus("waitpid");
2030
 
        free(direntry);
2031
1648
        continue;
2032
1649
      }
2033
1650
      if(WIFEXITED(status)){
2035
1652
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
2036
1653
                       " with status %d\n", direntry->d_name,
2037
1654
                       WEXITSTATUS(status));
2038
 
          free(direntry);
2039
1655
          continue;
2040
1656
        }
2041
1657
      } else if(WIFSIGNALED(status)){
2042
1658
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
2043
1659
                     " signal %d\n", direntry->d_name,
2044
1660
                     WTERMSIG(status));
2045
 
        free(direntry);
2046
1661
        continue;
2047
1662
      } else {
2048
1663
        fprintf_plus(stderr, "Warning: network hook \"%s\""
2049
1664
                     " crashed\n", direntry->d_name);
2050
 
        free(direntry);
2051
1665
        continue;
2052
1666
      }
2053
1667
    }
2055
1669
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
2056
1670
                   direntry->d_name);
2057
1671
    }
2058
 
    free(direntry);
2059
1672
  }
2060
1673
  free(direntries);
2061
 
  if(close(hookdir_fd) == -1){
 
1674
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2062
1675
    perror_plus("close");
2063
1676
  } else {
2064
1677
    hookdir_fd = -1;
2104
1717
    }
2105
1718
    
2106
1719
    if(quit_now){
2107
 
      ret = close(sd);
 
1720
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2108
1721
      if(ret == -1){
2109
1722
        perror_plus("close");
2110
1723
      }
2160
1773
    }
2161
1774
    
2162
1775
    /* Close the socket */
2163
 
    ret = close(sd);
 
1776
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
2164
1777
    if(ret == -1){
2165
1778
      perror_plus("close");
2166
1779
    }
2248
1861
    }
2249
1862
    
2250
1863
    /* Close the socket */
2251
 
    int ret = close(sd);
 
1864
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
2252
1865
    if(ret == -1){
2253
1866
      perror_plus("close");
2254
1867
    }
2269
1882
}
2270
1883
 
2271
1884
int main(int argc, char *argv[]){
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 };
 
1885
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1886
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1887
                        "+CTYPE-OPENPGP", .current_server = NULL,
 
1888
                        .interfaces = NULL, .interfaces_size = 0 };
2277
1889
  AvahiSServiceBrowser *sb = NULL;
2278
1890
  error_t ret_errno;
2279
1891
  int ret;
2288
1900
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2289
1901
  const char *seckey = PATHDIR "/" SECKEY;
2290
1902
  const char *pubkey = PATHDIR "/" PUBKEY;
2291
 
  const char *dh_params_file = NULL;
2292
1903
  char *interfaces_hooks = NULL;
2293
1904
  
2294
1905
  bool gnutls_initialized = false;
2347
1958
        .doc = "Bit length of the prime number used in the"
2348
1959
        " Diffie-Hellman key exchange",
2349
1960
        .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 },
2355
1961
      { .name = "priority", .key = 130,
2356
1962
        .arg = "STRING",
2357
1963
        .doc = "GnuTLS priority string for the TLS handshake",
2412
2018
        }
2413
2019
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2414
2020
        break;
2415
 
      case 134:                 /* --dh-params */
2416
 
        dh_params_file = arg;
2417
 
        break;
2418
2021
      case 130:                 /* --priority */
2419
2022
        mc.priority = arg;
2420
2023
        break;
2476
2079
      goto end;
2477
2080
    }
2478
2081
  }
2479
 
  
 
2082
    
2480
2083
  {
2481
2084
    /* Work around Debian bug #633582:
2482
2085
       <http://bugs.debian.org/633582> */
2506
2109
              }
2507
2110
            }
2508
2111
          }
2509
 
          close(seckey_fd);
 
2112
          TEMP_FAILURE_RETRY(close(seckey_fd));
2510
2113
        }
2511
2114
      }
2512
 
      
 
2115
    
2513
2116
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2514
2117
        int pubkey_fd = open(pubkey, O_RDONLY);
2515
2118
        if(pubkey_fd == -1){
2527
2130
              }
2528
2131
            }
2529
2132
          }
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
 
      
 
2133
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2134
        }
 
2135
      }
 
2136
    
2556
2137
      /* Lower privileges */
2557
2138
      ret_errno = lower_privileges();
2558
2139
      if(ret_errno != 0){
2687
2268
        if(ret_errno != 0){
2688
2269
          errno = ret_errno;
2689
2270
          perror_plus("argz_add");
2690
 
          free(direntries[i]);
2691
2271
          continue;
2692
2272
        }
2693
2273
        if(debug){
2694
2274
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2695
2275
                       direntries[i]->d_name);
2696
2276
        }
2697
 
        free(direntries[i]);
2698
2277
      }
2699
2278
      free(direntries);
2700
2279
    } else {
2732
2311
      errno = bring_up_interface(interface, delay);
2733
2312
      if(not interface_was_up){
2734
2313
        if(errno != 0){
2735
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2736
 
                       " %s\n", interface, strerror(errno));
 
2314
          perror_plus("Failed to bring up interface");
2737
2315
        } else {
2738
2316
          errno = argz_add(&interfaces_to_take_down,
2739
2317
                           &interfaces_to_take_down_size,
2762
2340
    goto end;
2763
2341
  }
2764
2342
  
2765
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
2343
  ret = init_gnutls_global(pubkey, seckey, &mc);
2766
2344
  if(ret == -1){
2767
2345
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2768
2346
    exitcode = EX_UNAVAILABLE;
2957
2535
  
2958
2536
  if(gnutls_initialized){
2959
2537
    gnutls_certificate_free_credentials(mc.cred);
 
2538
    gnutls_global_deinit();
2960
2539
    gnutls_dh_params_deinit(mc.dh_params);
2961
2540
  }
2962
2541
  
2970
2549
    mc.current_server->prev->next = NULL;
2971
2550
    while(mc.current_server != NULL){
2972
2551
      server *next = mc.current_server->next;
2973
 
#ifdef __GNUC__
2974
 
#pragma GCC diagnostic push
2975
 
#pragma GCC diagnostic ignored "-Wcast-qual"
2976
 
#endif
2977
 
      free((char *)(mc.current_server->ip));
2978
 
#ifdef __GNUC__
2979
 
#pragma GCC diagnostic pop
2980
 
#endif
2981
2552
      free(mc.current_server);
2982
2553
      mc.current_server = next;
2983
2554
    }
3027
2598
  /* Removes the GPGME temp directory and all files inside */
3028
2599
  if(tempdir != NULL){
3029
2600
    struct dirent **direntries = NULL;
3030
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
3031
 
                                                  | O_NOFOLLOW
3032
 
                                                  | O_DIRECTORY
3033
 
                                                  | O_PATH));
 
2601
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY |
 
2602
                                                  O_NOFOLLOW));
3034
2603
    if(tempdir_fd == -1){
3035
2604
      perror_plus("open");
3036
2605
    } else {
 
2606
#ifdef __GLIBC__
 
2607
#if __GLIBC_PREREQ(2, 15)
3037
2608
      int numentries = scandirat(tempdir_fd, ".", &direntries,
3038
2609
                                 notdotentries, alphasort);
 
2610
#else  /* not __GLIBC_PREREQ(2, 15) */
 
2611
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2612
                               alphasort);
 
2613
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
2614
#else   /* not __GLIBC__ */
 
2615
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2616
                               alphasort);
 
2617
#endif  /* not __GLIBC__ */
3039
2618
      if(numentries >= 0){
3040
2619
        for(int i = 0; i < numentries; i++){
3041
2620
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
3044
2623
                         " \"%s\", 0): %s\n", tempdir,
3045
2624
                         direntries[i]->d_name, strerror(errno));
3046
2625
          }
3047
 
          free(direntries[i]);
3048
2626
        }
3049
2627
        
3050
2628
        /* need to clean even if 0 because man page doesn't specify */
3057
2635
          perror_plus("rmdir");
3058
2636
        }
3059
2637
      }
3060
 
      close(tempdir_fd);
 
2638
      TEMP_FAILURE_RETRY(close(tempdir_fd));
3061
2639
    }
3062
2640
  }
3063
2641