/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: 2018-02-19 21:32:07 UTC
  • Revision ID: teddy@recompile.se-20180219213207-0un0ylegx390pftq
Client bug fixes: Fix file descriptor leaks

* plugin-helpers/mandos-client.c (init_gnutls_global, get_flags):
  Always close files and sockets after they are used.

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-2015 Teddy Hogeborn
13
 
 * Copyright © 2008-2015 Björn Påhlsson
14
 
 * 
15
 
 * This program is free software: you can redistribute it and/or
16
 
 * modify it under the terms of the GNU General Public License as
17
 
 * published by the Free Software Foundation, either version 3 of the
18
 
 * License, or (at your option) any later version.
19
 
 * 
20
 
 * This program is distributed in the hope that it will be useful, but
 
12
 * Copyright © 2008-2018 Teddy Hogeborn
 
13
 * Copyright © 2008-2018 Björn Påhlsson
 
14
 * 
 
15
 * This file is part of Mandos.
 
16
 * 
 
17
 * Mandos is free software: you can redistribute it and/or modify it
 
18
 * under the terms of the GNU General Public License as published by
 
19
 * the Free Software Foundation, either version 3 of the License, or
 
20
 * (at your option) any later version.
 
21
 * 
 
22
 * Mandos is distributed in the hope that it will be useful, but
21
23
 * WITHOUT ANY WARRANTY; without even the implied warranty of
22
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23
25
 * General Public License for more details.
24
26
 * 
25
27
 * You should have received a copy of the GNU General Public License
26
 
 * along with this program.  If not, see
27
 
 * <http://www.gnu.org/licenses/>.
 
28
 * along with Mandos.  If not, see <http://www.gnu.org/licenses/>.
28
29
 * 
29
30
 * Contact the authors at <mandos@recompile.se>.
30
31
 */
46
47
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
48
                                   strtof(), abort() */
48
49
#include <stdbool.h>            /* bool, false, true */
49
 
#include <string.h>             /* memset(), strcmp(), strlen(),
50
 
                                   strerror(), asprintf(), strcpy() */
 
50
#include <string.h>             /* strcmp(), strlen(), strerror(),
 
51
                                   asprintf(), strncpy(), strsignal()
 
52
                                */
51
53
#include <sys/ioctl.h>          /* ioctl */
52
54
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
55
                                   sockaddr_in6, PF_INET6,
57
59
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
60
                                   inet_pton(), connect(),
59
61
                                   getnameinfo() */
60
 
#include <fcntl.h>              /* open(), unlinkat() */
 
62
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
61
63
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
64
                                 */
63
65
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
64
66
                                   strtoimax() */
65
 
#include <errno.h>              /* perror(), errno,
 
67
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
 
68
                                   EAI_SYSTEM, ENETUNREACH,
 
69
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
 
70
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
 
71
                                   ENOTEMPTY,
66
72
                                   program_invocation_short_name */
67
73
#include <time.h>               /* nanosleep(), time(), sleep() */
68
74
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
305
311
      return false;
306
312
    }
307
313
    
308
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
 
314
    ret = close(fd);
309
315
    if(ret == -1){
310
316
      perror_plus("close");
311
317
    }
513
519
  fprintf_plus(stderr, "GnuTLS: %s", string);
514
520
}
515
521
 
516
 
__attribute__((nonnull, warn_unused_result))
 
522
__attribute__((nonnull(1, 2, 4), warn_unused_result))
517
523
static int init_gnutls_global(const char *pubkeyfilename,
518
524
                              const char *seckeyfilename,
 
525
                              const char *dhparamsfilename,
519
526
                              mandos_context *mc){
520
527
  int ret;
521
528
  unsigned int uret;
524
531
    fprintf_plus(stderr, "Initializing GnuTLS\n");
525
532
  }
526
533
  
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
534
  if(debug){
535
535
    /* "Use a log level over 10 to enable all debugging options."
536
536
     * - GnuTLS manual
544
544
  if(ret != GNUTLS_E_SUCCESS){
545
545
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
546
546
                 safer_gnutls_strerror(ret));
547
 
    gnutls_global_deinit();
548
547
    return -1;
549
548
  }
550
549
  
575
574
                 safer_gnutls_strerror(ret));
576
575
    goto globalfail;
577
576
  }
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;
 
577
  /* If a Diffie-Hellman parameters file was given, try to use it */
 
578
  if(dhparamsfilename != NULL){
 
579
    gnutls_datum_t params = { .data = NULL, .size = 0 };
 
580
    do {
 
581
      int dhpfile = open(dhparamsfilename, O_RDONLY);
 
582
      if(dhpfile == -1){
 
583
        perror_plus("open");
 
584
        dhparamsfilename = NULL;
 
585
        break;
 
586
      }
 
587
      size_t params_capacity = 0;
585
588
      while(true){
586
 
        buffer_capacity = incbuffer((char **)&buffer.data,
587
 
                                    (size_t)buffer.size,
588
 
                                    (size_t)buffer_capacity);
589
 
        if(buffer_capacity == 0){
 
589
        params_capacity = incbuffer((char **)&params.data,
 
590
                                    (size_t)params.size,
 
591
                                    (size_t)params_capacity);
 
592
        if(params_capacity == 0){
590
593
          perror_plus("incbuffer");
591
 
          free(buffer.data);
592
 
          buffer.data = NULL;
 
594
          free(params.data);
 
595
          params.data = NULL;
 
596
          dhparamsfilename = NULL;
593
597
          break;
594
598
        }
595
 
        ssize_t bytes_read = read(secfile, buffer.data + buffer.size,
 
599
        ssize_t bytes_read = read(dhpfile,
 
600
                                  params.data + params.size,
596
601
                                  BUFFER_SIZE);
597
602
        /* EOF */
598
603
        if(bytes_read == 0){
601
606
        /* check bytes_read for failure */
602
607
        if(bytes_read < 0){
603
608
          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);
 
609
          free(params.data);
 
610
          params.data = NULL;
 
611
          dhparamsfilename = NULL;
 
612
          break;
 
613
        }
 
614
        params.size += (unsigned int)bytes_read;
 
615
      }
 
616
      close(dhpfile);
 
617
      if(params.data == NULL){
 
618
        dhparamsfilename = NULL;
 
619
      }
 
620
      if(dhparamsfilename == NULL){
 
621
        break;
 
622
      }
 
623
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
 
624
                                          GNUTLS_X509_FMT_PEM);
 
625
      if(ret != GNUTLS_E_SUCCESS){
 
626
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
 
627
                     " \"%s\": %s\n", dhparamsfilename,
 
628
                     safer_gnutls_strerror(ret));
 
629
        dhparamsfilename = NULL;
 
630
      }
 
631
      free(params.data);
 
632
    } while(false);
 
633
  }
 
634
  if(dhparamsfilename == NULL){
 
635
    if(mc->dh_bits == 0){
 
636
      /* Find out the optimal number of DH bits */
 
637
      /* Try to read the private key file */
 
638
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
 
639
      do {
 
640
        int secfile = open(seckeyfilename, O_RDONLY);
 
641
        if(secfile == -1){
 
642
          perror_plus("open");
 
643
          break;
 
644
        }
 
645
        size_t buffer_capacity = 0;
 
646
        while(true){
 
647
          buffer_capacity = incbuffer((char **)&buffer.data,
 
648
                                      (size_t)buffer.size,
 
649
                                      (size_t)buffer_capacity);
 
650
          if(buffer_capacity == 0){
 
651
            perror_plus("incbuffer");
 
652
            free(buffer.data);
 
653
            buffer.data = NULL;
 
654
            break;
 
655
          }
 
656
          ssize_t bytes_read = read(secfile,
 
657
                                    buffer.data + buffer.size,
 
658
                                    BUFFER_SIZE);
 
659
          /* EOF */
 
660
          if(bytes_read == 0){
 
661
            break;
 
662
          }
 
663
          /* check bytes_read for failure */
 
664
          if(bytes_read < 0){
 
665
            perror_plus("read");
 
666
            free(buffer.data);
 
667
            buffer.data = NULL;
 
668
            break;
 
669
          }
 
670
          buffer.size += (unsigned int)bytes_read;
 
671
        }
 
672
        close(secfile);
 
673
      } while(false);
 
674
      /* If successful, use buffer to parse private key */
 
675
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
676
      if(buffer.data != NULL){
 
677
        {
 
678
          gnutls_openpgp_privkey_t privkey = NULL;
 
679
          ret = gnutls_openpgp_privkey_init(&privkey);
627
680
          if(ret != GNUTLS_E_SUCCESS){
628
 
            fprintf_plus(stderr, "Error importing OpenPGP key : %s",
 
681
            fprintf_plus(stderr, "Error initializing OpenPGP key"
 
682
                         " structure: %s",
629
683
                         safer_gnutls_strerror(ret));
630
 
            privkey = NULL;
 
684
            free(buffer.data);
 
685
            buffer.data = NULL;
 
686
          } else {
 
687
            ret = gnutls_openpgp_privkey_import
 
688
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
 
689
            if(ret != GNUTLS_E_SUCCESS){
 
690
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
 
691
                           safer_gnutls_strerror(ret));
 
692
              privkey = NULL;
 
693
            }
 
694
            free(buffer.data);
 
695
            buffer.data = NULL;
 
696
            if(privkey != NULL){
 
697
              /* Use private key to suggest an appropriate
 
698
                 sec_param */
 
699
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
 
700
              gnutls_openpgp_privkey_deinit(privkey);
 
701
              if(debug){
 
702
                fprintf_plus(stderr, "This OpenPGP key implies using"
 
703
                             " a GnuTLS security parameter \"%s\".\n",
 
704
                             safe_string(gnutls_sec_param_get_name
 
705
                                         (sec_param)));
 
706
              }
 
707
            }
631
708
          }
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
 
            }
 
709
        }
 
710
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
 
711
          /* Err on the side of caution */
 
712
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
713
          if(debug){
 
714
            fprintf_plus(stderr, "Falling back to security parameter"
 
715
                         " \"%s\"\n",
 
716
                         safe_string(gnutls_sec_param_get_name
 
717
                                     (sec_param)));
644
718
          }
645
719
        }
646
720
      }
647
 
      if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
648
 
        /* Err on the side of caution */
649
 
        sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
721
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
 
722
      if(uret != 0){
 
723
        mc->dh_bits = uret;
650
724
        if(debug){
651
 
          fprintf_plus(stderr, "Falling back to security parameter"
652
 
                       " \"%s\"\n",
 
725
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
 
726
                       " implies %u DH bits; using that.\n",
653
727
                       safe_string(gnutls_sec_param_get_name
654
 
                                   (sec_param)));
 
728
                                   (sec_param)),
 
729
                       mc->dh_bits);
655
730
        }
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",
 
731
      } else {
 
732
        fprintf_plus(stderr, "Failed to get implied number of DH"
 
733
                     " bits for security parameter \"%s\"): %s\n",
664
734
                     safe_string(gnutls_sec_param_get_name
665
735
                                 (sec_param)),
666
 
                     mc->dh_bits);
 
736
                     safer_gnutls_strerror(ret));
 
737
        goto globalfail;
667
738
      }
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)),
 
739
    } else if(debug){
 
740
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
 
741
                   mc->dh_bits);
 
742
    }
 
743
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
744
    if(ret != GNUTLS_E_SUCCESS){
 
745
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
 
746
                   " bits): %s\n", mc->dh_bits,
672
747
                   safer_gnutls_strerror(ret));
673
748
      goto globalfail;
674
749
    }
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
 
  
 
750
  }
686
751
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
687
752
  
688
753
  return 0;
690
755
 globalfail:
691
756
  
692
757
  gnutls_certificate_free_credentials(mc->cred);
693
 
  gnutls_global_deinit();
694
758
  gnutls_dh_params_deinit(mc->dh_params);
695
759
  return -1;
696
760
}
748
812
  /* ignore client certificate if any. */
749
813
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
750
814
  
751
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
752
 
  
753
815
  return 0;
754
816
}
755
817
 
759
821
 
760
822
/* Set effective uid to 0, return errno */
761
823
__attribute__((warn_unused_result))
762
 
error_t raise_privileges(void){
763
 
  error_t old_errno = errno;
764
 
  error_t ret_errno = 0;
 
824
int raise_privileges(void){
 
825
  int old_errno = errno;
 
826
  int ret = 0;
765
827
  if(seteuid(0) == -1){
766
 
    ret_errno = errno;
 
828
    ret = errno;
767
829
  }
768
830
  errno = old_errno;
769
 
  return ret_errno;
 
831
  return ret;
770
832
}
771
833
 
772
834
/* Set effective and real user ID to 0.  Return errno. */
773
835
__attribute__((warn_unused_result))
774
 
error_t raise_privileges_permanently(void){
775
 
  error_t old_errno = errno;
776
 
  error_t ret_errno = raise_privileges();
777
 
  if(ret_errno != 0){
 
836
int raise_privileges_permanently(void){
 
837
  int old_errno = errno;
 
838
  int ret = raise_privileges();
 
839
  if(ret != 0){
778
840
    errno = old_errno;
779
 
    return ret_errno;
 
841
    return ret;
780
842
  }
781
843
  if(setuid(0) == -1){
782
 
    ret_errno = errno;
 
844
    ret = errno;
783
845
  }
784
846
  errno = old_errno;
785
 
  return ret_errno;
 
847
  return ret;
786
848
}
787
849
 
788
850
/* Set effective user ID to unprivileged saved user ID */
789
851
__attribute__((warn_unused_result))
790
 
error_t lower_privileges(void){
791
 
  error_t old_errno = errno;
792
 
  error_t ret_errno = 0;
 
852
int lower_privileges(void){
 
853
  int old_errno = errno;
 
854
  int ret = 0;
793
855
  if(seteuid(uid) == -1){
794
 
    ret_errno = errno;
 
856
    ret = errno;
795
857
  }
796
858
  errno = old_errno;
797
 
  return ret_errno;
 
859
  return ret;
798
860
}
799
861
 
800
862
/* Lower privileges permanently */
801
863
__attribute__((warn_unused_result))
802
 
error_t lower_privileges_permanently(void){
803
 
  error_t old_errno = errno;
804
 
  error_t ret_errno = 0;
 
864
int lower_privileges_permanently(void){
 
865
  int old_errno = errno;
 
866
  int ret = 0;
805
867
  if(setuid(uid) == -1){
806
 
    ret_errno = errno;
 
868
    ret = errno;
807
869
  }
808
870
  errno = old_errno;
809
 
  return ret_errno;
 
871
  return ret;
810
872
}
811
873
 
812
874
/* Helper function to add_local_route() and delete_local_route() */
868
930
      perror_plus("dup2(devnull, STDIN_FILENO)");
869
931
      _exit(EX_OSERR);
870
932
    }
871
 
    ret = (int)TEMP_FAILURE_RETRY(close(devnull));
 
933
    ret = close(devnull);
872
934
    if(ret == -1){
873
935
      perror_plus("close");
874
936
      _exit(EX_OSERR);
891
953
                                                   helper, O_RDONLY));
892
954
    if(helper_fd == -1){
893
955
      perror_plus("openat");
 
956
      close(helperdir_fd);
894
957
      _exit(EX_UNAVAILABLE);
895
958
    }
896
 
    TEMP_FAILURE_RETRY(close(helperdir_fd));
 
959
    close(helperdir_fd);
897
960
#ifdef __GNUC__
898
961
#pragma GCC diagnostic push
899
962
#pragma GCC diagnostic ignored "-Wcast-qual"
1018
1081
    bool match = false;
1019
1082
    {
1020
1083
      char *interface = NULL;
1021
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
1022
 
                                 interface))){
 
1084
      while((interface = argz_next(mc->interfaces,
 
1085
                                   mc->interfaces_size,
 
1086
                                   interface))){
1023
1087
        if(if_nametoindex(interface) == (unsigned int)if_index){
1024
1088
          match = true;
1025
1089
          break;
1067
1131
    goto mandos_end;
1068
1132
  }
1069
1133
  
1070
 
  memset(&to, 0, sizeof(to));
1071
1134
  if(af == AF_INET6){
1072
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
1073
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
1135
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
 
1136
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
 
1137
    ret = inet_pton(af, ip, &to6->sin6_addr);
1074
1138
  } else {                      /* IPv4 */
1075
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
1076
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
1139
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
 
1140
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
 
1141
    ret = inet_pton(af, ip, &to4->sin_addr);
1077
1142
  }
1078
1143
  if(ret < 0 ){
1079
1144
    int e = errno;
1158
1223
                    sizeof(struct sockaddr_in));
1159
1224
    }
1160
1225
    if(ret < 0){
1161
 
      if(errno == ENETUNREACH
 
1226
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
1162
1227
         and if_index != AVAHI_IF_UNSPEC
1163
1228
         and connect_to == NULL
1164
1229
         and not route_added and
1177
1242
           with an explicit route added with the server's address.
1178
1243
           
1179
1244
           Avahi bug reference:
1180
 
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
 
1245
           https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1181
1246
           https://bugs.debian.org/587961
1182
1247
        */
1183
1248
        if(debug){
1363
1428
                                               &decrypted_buffer, mc);
1364
1429
    if(decrypted_buffer_size >= 0){
1365
1430
      
 
1431
      clearerr(stdout);
1366
1432
      written = 0;
1367
1433
      while(written < (size_t) decrypted_buffer_size){
1368
1434
        if(quit_now){
1384
1450
        }
1385
1451
        written += (size_t)ret;
1386
1452
      }
 
1453
      ret = fflush(stdout);
 
1454
      if(ret != 0){
 
1455
        int e = errno;
 
1456
        if(debug){
 
1457
          fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
1458
                       strerror(errno));
 
1459
        }
 
1460
        errno = e;
 
1461
        goto mandos_end;
 
1462
      }
1387
1463
      retval = 0;
1388
1464
    }
1389
1465
  }
1402
1478
    free(decrypted_buffer);
1403
1479
    free(buffer);
1404
1480
    if(tcp_sd >= 0){
1405
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
1481
      ret = close(tcp_sd);
1406
1482
    }
1407
1483
    if(ret == -1){
1408
1484
      if(e == 0){
1420
1496
  return retval;
1421
1497
}
1422
1498
 
1423
 
__attribute__((nonnull))
1424
1499
static void resolve_callback(AvahiSServiceResolver *r,
1425
1500
                             AvahiIfIndex interface,
1426
1501
                             AvahiProtocol proto,
1563
1638
__attribute__((nonnull, warn_unused_result))
1564
1639
bool get_flags(const char *ifname, struct ifreq *ifr){
1565
1640
  int ret;
1566
 
  error_t ret_errno;
 
1641
  int old_errno;
1567
1642
  
1568
1643
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1569
1644
  if(s < 0){
1570
 
    ret_errno = errno;
 
1645
    old_errno = errno;
1571
1646
    perror_plus("socket");
1572
 
    errno = ret_errno;
 
1647
    errno = old_errno;
1573
1648
    return false;
1574
1649
  }
1575
 
  strcpy(ifr->ifr_name, ifname);
 
1650
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
 
1651
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1576
1652
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1577
1653
  if(ret == -1){
1578
1654
    if(debug){
1579
 
      ret_errno = errno;
 
1655
      old_errno = errno;
1580
1656
      perror_plus("ioctl SIOCGIFFLAGS");
1581
 
      errno = ret_errno;
 
1657
      errno = old_errno;
1582
1658
    }
 
1659
    close(s);
1583
1660
    return false;
1584
1661
  }
 
1662
  close(s);
1585
1663
  return true;
1586
1664
}
1587
1665
 
1848
1926
      return;
1849
1927
    }
1850
1928
  }
1851
 
#ifdef __GLIBC__
1852
 
#if __GLIBC_PREREQ(2, 15)
 
1929
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
1930
  if(devnull == -1){
 
1931
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
1932
    return;
 
1933
  }
1853
1934
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1854
1935
                           runnable_hook, alphasort);
1855
 
#else  /* not __GLIBC_PREREQ(2, 15) */
1856
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1857
 
                         alphasort);
1858
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
1859
 
#else   /* not __GLIBC__ */
1860
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1861
 
                         alphasort);
1862
 
#endif  /* not __GLIBC__ */
1863
1936
  if(numhooks == -1){
1864
1937
    perror_plus("scandir");
 
1938
    close(devnull);
1865
1939
    return;
1866
1940
  }
1867
1941
  struct dirent *direntry;
1868
1942
  int ret;
1869
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
1870
 
  if(devnull == -1){
1871
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
1872
 
    return;
1873
 
  }
1874
1943
  for(int i = 0; i < numhooks; i++){
1875
1944
    direntry = direntries[i];
1876
1945
    if(debug){
1947
2016
        perror_plus("openat");
1948
2017
        _exit(EXIT_FAILURE);
1949
2018
      }
1950
 
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2019
      if(close(hookdir_fd) == -1){
1951
2020
        perror_plus("close");
1952
2021
        _exit(EXIT_FAILURE);
1953
2022
      }
1956
2025
        perror_plus("dup2(devnull, STDIN_FILENO)");
1957
2026
        _exit(EX_OSERR);
1958
2027
      }
1959
 
      ret = (int)TEMP_FAILURE_RETRY(close(devnull));
 
2028
      ret = close(devnull);
1960
2029
      if(ret == -1){
1961
2030
        perror_plus("close");
1962
2031
        _exit(EX_OSERR);
2011
2080
    free(direntry);
2012
2081
  }
2013
2082
  free(direntries);
2014
 
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2083
  if(close(hookdir_fd) == -1){
2015
2084
    perror_plus("close");
2016
2085
  } else {
2017
2086
    hookdir_fd = -1;
2020
2089
}
2021
2090
 
2022
2091
__attribute__((nonnull, warn_unused_result))
2023
 
error_t bring_up_interface(const char *const interface,
2024
 
                           const float delay){
2025
 
  error_t old_errno = errno;
 
2092
int bring_up_interface(const char *const interface,
 
2093
                       const float delay){
 
2094
  int old_errno = errno;
2026
2095
  int ret;
2027
2096
  struct ifreq network;
2028
2097
  unsigned int if_index = if_nametoindex(interface);
2038
2107
  }
2039
2108
  
2040
2109
  if(not interface_is_up(interface)){
2041
 
    error_t ret_errno = 0, ioctl_errno = 0;
 
2110
    int ret_errno = 0;
 
2111
    int ioctl_errno = 0;
2042
2112
    if(not get_flags(interface, &network)){
2043
2113
      ret_errno = errno;
2044
2114
      fprintf_plus(stderr, "Failed to get flags for interface "
2057
2127
    }
2058
2128
    
2059
2129
    if(quit_now){
2060
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2130
      ret = close(sd);
2061
2131
      if(ret == -1){
2062
2132
        perror_plus("close");
2063
2133
      }
2113
2183
    }
2114
2184
    
2115
2185
    /* Close the socket */
2116
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2186
    ret = close(sd);
2117
2187
    if(ret == -1){
2118
2188
      perror_plus("close");
2119
2189
    }
2131
2201
  
2132
2202
  /* Sleep checking until interface is running.
2133
2203
     Check every 0.25s, up to total time of delay */
2134
 
  for(int i=0; i < delay * 4; i++){
 
2204
  for(int i = 0; i < delay * 4; i++){
2135
2205
    if(interface_is_running(interface)){
2136
2206
      break;
2137
2207
    }
2147
2217
}
2148
2218
 
2149
2219
__attribute__((nonnull, warn_unused_result))
2150
 
error_t take_down_interface(const char *const interface){
2151
 
  error_t old_errno = errno;
 
2220
int take_down_interface(const char *const interface){
 
2221
  int old_errno = errno;
2152
2222
  struct ifreq network;
2153
2223
  unsigned int if_index = if_nametoindex(interface);
2154
2224
  if(if_index == 0){
2157
2227
    return ENXIO;
2158
2228
  }
2159
2229
  if(interface_is_up(interface)){
2160
 
    error_t ret_errno = 0, ioctl_errno = 0;
 
2230
    int ret_errno = 0;
 
2231
    int ioctl_errno = 0;
2161
2232
    if(not get_flags(interface, &network) and debug){
2162
2233
      ret_errno = errno;
2163
2234
      fprintf_plus(stderr, "Failed to get flags for interface "
2201
2272
    }
2202
2273
    
2203
2274
    /* Close the socket */
2204
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2275
    int ret = close(sd);
2205
2276
    if(ret == -1){
2206
2277
      perror_plus("close");
2207
2278
    }
2223
2294
 
2224
2295
int main(int argc, char *argv[]){
2225
2296
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2226
 
                        .priority = "SECURE256:!CTYPE-X.509:"
2227
 
                        "+CTYPE-OPENPGP:!RSA", .current_server = NULL,
2228
 
                        .interfaces = NULL, .interfaces_size = 0 };
 
2297
                        .priority = "SECURE256:!CTYPE-X.509"
 
2298
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
 
2299
                        .current_server = NULL, .interfaces = NULL,
 
2300
                        .interfaces_size = 0 };
2229
2301
  AvahiSServiceBrowser *sb = NULL;
2230
2302
  error_t ret_errno;
2231
2303
  int ret;
2240
2312
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2241
2313
  const char *seckey = PATHDIR "/" SECKEY;
2242
2314
  const char *pubkey = PATHDIR "/" PUBKEY;
 
2315
  const char *dh_params_file = NULL;
2243
2316
  char *interfaces_hooks = NULL;
2244
2317
  
2245
2318
  bool gnutls_initialized = false;
2298
2371
        .doc = "Bit length of the prime number used in the"
2299
2372
        " Diffie-Hellman key exchange",
2300
2373
        .group = 2 },
 
2374
      { .name = "dh-params", .key = 134,
 
2375
        .arg = "FILE",
 
2376
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
 
2377
        " for the Diffie-Hellman key exchange",
 
2378
        .group = 2 },
2301
2379
      { .name = "priority", .key = 130,
2302
2380
        .arg = "STRING",
2303
2381
        .doc = "GnuTLS priority string for the TLS handshake",
2358
2436
        }
2359
2437
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2360
2438
        break;
 
2439
      case 134:                 /* --dh-params */
 
2440
        dh_params_file = arg;
 
2441
        break;
2361
2442
      case 130:                 /* --priority */
2362
2443
        mc.priority = arg;
2363
2444
        break;
2403
2484
                         .args_doc = "",
2404
2485
                         .doc = "Mandos client -- Get and decrypt"
2405
2486
                         " passwords from a Mandos server" };
2406
 
    ret = argp_parse(&argp, argc, argv,
2407
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2408
 
    switch(ret){
 
2487
    ret_errno = argp_parse(&argp, argc, argv,
 
2488
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2489
    switch(ret_errno){
2409
2490
    case 0:
2410
2491
      break;
2411
2492
    case ENOMEM:
2412
2493
    default:
2413
 
      errno = ret;
 
2494
      errno = ret_errno;
2414
2495
      perror_plus("argp_parse");
2415
2496
      exitcode = EX_OSERR;
2416
2497
      goto end;
2422
2503
  
2423
2504
  {
2424
2505
    /* Work around Debian bug #633582:
2425
 
       <http://bugs.debian.org/633582> */
 
2506
       <https://bugs.debian.org/633582> */
2426
2507
    
2427
2508
    /* Re-raise privileges */
2428
 
    ret_errno = raise_privileges();
2429
 
    if(ret_errno != 0){
2430
 
      errno = ret_errno;
 
2509
    ret = raise_privileges();
 
2510
    if(ret != 0){
 
2511
      errno = ret;
2431
2512
      perror_plus("Failed to raise privileges");
2432
2513
    } else {
2433
2514
      struct stat st;
2449
2530
              }
2450
2531
            }
2451
2532
          }
2452
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2533
          close(seckey_fd);
2453
2534
        }
2454
2535
      }
2455
2536
      
2470
2551
              }
2471
2552
            }
2472
2553
          }
2473
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2554
          close(pubkey_fd);
 
2555
        }
 
2556
      }
 
2557
      
 
2558
      if(dh_params_file != NULL
 
2559
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
 
2560
        int dhparams_fd = open(dh_params_file, O_RDONLY);
 
2561
        if(dhparams_fd == -1){
 
2562
          perror_plus("open");
 
2563
        } else {
 
2564
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
 
2565
          if(ret == -1){
 
2566
            perror_plus("fstat");
 
2567
          } else {
 
2568
            if(S_ISREG(st.st_mode)
 
2569
               and st.st_uid == 0 and st.st_gid == 0){
 
2570
              ret = fchown(dhparams_fd, uid, gid);
 
2571
              if(ret == -1){
 
2572
                perror_plus("fchown");
 
2573
              }
 
2574
            }
 
2575
          }
 
2576
          close(dhparams_fd);
2474
2577
        }
2475
2578
      }
2476
2579
      
2477
2580
      /* Lower privileges */
2478
 
      ret_errno = lower_privileges();
2479
 
      if(ret_errno != 0){
2480
 
        errno = ret_errno;
 
2581
      ret = lower_privileges();
 
2582
      if(ret != 0){
 
2583
        errno = ret;
2481
2584
        perror_plus("Failed to lower privileges");
2482
2585
      }
2483
2586
    }
2653
2756
      errno = bring_up_interface(interface, delay);
2654
2757
      if(not interface_was_up){
2655
2758
        if(errno != 0){
2656
 
          perror_plus("Failed to bring up interface");
 
2759
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
 
2760
                       " %s\n", interface, strerror(errno));
2657
2761
        } else {
2658
2762
          errno = argz_add(&interfaces_to_take_down,
2659
2763
                           &interfaces_to_take_down_size,
2682
2786
    goto end;
2683
2787
  }
2684
2788
  
2685
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2789
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
2686
2790
  if(ret == -1){
2687
2791
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2688
2792
    exitcode = EX_UNAVAILABLE;
2810
2914
    
2811
2915
    /* Allocate a new server */
2812
2916
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2813
 
                                 &config, NULL, NULL, &ret_errno);
 
2917
                                 &config, NULL, NULL, &ret);
2814
2918
    
2815
2919
    /* Free the Avahi configuration data */
2816
2920
    avahi_server_config_free(&config);
2819
2923
  /* Check if creating the Avahi server object succeeded */
2820
2924
  if(mc.server == NULL){
2821
2925
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2822
 
                 avahi_strerror(ret_errno));
 
2926
                 avahi_strerror(ret));
2823
2927
    exitcode = EX_UNAVAILABLE;
2824
2928
    goto end;
2825
2929
  }
2860
2964
 end:
2861
2965
  
2862
2966
  if(debug){
2863
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2967
    if(signal_received){
 
2968
      fprintf_plus(stderr, "%s exiting due to signal %d: %s\n",
 
2969
                   argv[0], signal_received,
 
2970
                   strsignal(signal_received));
 
2971
    } else {
 
2972
      fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2973
    }
2864
2974
  }
2865
2975
  
2866
2976
  /* Cleanup things */
2877
2987
  
2878
2988
  if(gnutls_initialized){
2879
2989
    gnutls_certificate_free_credentials(mc.cred);
2880
 
    gnutls_global_deinit();
2881
2990
    gnutls_dh_params_deinit(mc.dh_params);
2882
2991
  }
2883
2992
  
2906
3015
  
2907
3016
  /* Re-raise privileges */
2908
3017
  {
2909
 
    ret_errno = raise_privileges();
2910
 
    if(ret_errno != 0){
2911
 
      errno = ret_errno;
 
3018
    ret = raise_privileges();
 
3019
    if(ret != 0){
 
3020
      errno = ret;
2912
3021
      perror_plus("Failed to raise privileges");
2913
3022
    } else {
2914
3023
      
2919
3028
      /* Take down the network interfaces which were brought up */
2920
3029
      {
2921
3030
        char *interface = NULL;
2922
 
        while((interface=argz_next(interfaces_to_take_down,
2923
 
                                   interfaces_to_take_down_size,
2924
 
                                   interface))){
2925
 
          ret_errno = take_down_interface(interface);
2926
 
          if(ret_errno != 0){
2927
 
            errno = ret_errno;
 
3031
        while((interface = argz_next(interfaces_to_take_down,
 
3032
                                     interfaces_to_take_down_size,
 
3033
                                     interface))){
 
3034
          ret = take_down_interface(interface);
 
3035
          if(ret != 0){
 
3036
            errno = ret;
2928
3037
            perror_plus("Failed to take down interface");
2929
3038
          }
2930
3039
        }
2935
3044
      }
2936
3045
    }
2937
3046
    
2938
 
    ret_errno = lower_privileges_permanently();
2939
 
    if(ret_errno != 0){
2940
 
      errno = ret_errno;
 
3047
    ret = lower_privileges_permanently();
 
3048
    if(ret != 0){
 
3049
      errno = ret;
2941
3050
      perror_plus("Failed to lower privileges permanently");
2942
3051
    }
2943
3052
  }
2945
3054
  free(interfaces_to_take_down);
2946
3055
  free(interfaces_hooks);
2947
3056
  
 
3057
  void clean_dir_at(int base, const char * const dirname,
 
3058
                    uintmax_t level){
 
3059
    struct dirent **direntries = NULL;
 
3060
    int dret;
 
3061
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
 
3062
                                                O_RDONLY
 
3063
                                                | O_NOFOLLOW
 
3064
                                                | O_DIRECTORY
 
3065
                                                | O_PATH));
 
3066
    if(dir_fd == -1){
 
3067
      perror_plus("open");
 
3068
      return;
 
3069
    }
 
3070
    int numentries = scandirat(dir_fd, ".", &direntries,
 
3071
                               notdotentries, alphasort);
 
3072
    if(numentries >= 0){
 
3073
      for(int i = 0; i < numentries; i++){
 
3074
        if(debug){
 
3075
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
 
3076
                       dirname, direntries[i]->d_name);
 
3077
        }
 
3078
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
 
3079
        if(dret == -1){
 
3080
          if(errno == EISDIR){
 
3081
              dret = unlinkat(dir_fd, direntries[i]->d_name,
 
3082
                              AT_REMOVEDIR);
 
3083
          }         
 
3084
          if((dret == -1) and (errno == ENOTEMPTY)
 
3085
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
 
3086
                  == 0) and (level == 0)){
 
3087
            /* Recurse only in this special case */
 
3088
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
 
3089
            dret = 0;
 
3090
          }
 
3091
          if((dret == -1) and (errno != ENOENT)){
 
3092
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
 
3093
                         direntries[i]->d_name, strerror(errno));
 
3094
          }
 
3095
        }
 
3096
        free(direntries[i]);
 
3097
      }
 
3098
      
 
3099
      /* need to clean even if 0 because man page doesn't specify */
 
3100
      free(direntries);
 
3101
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
 
3102
      if(dret == -1 and errno != ENOENT){
 
3103
        perror_plus("rmdir");
 
3104
      }
 
3105
    } else {
 
3106
      perror_plus("scandirat");
 
3107
    }
 
3108
    close(dir_fd);
 
3109
  }
 
3110
  
2948
3111
  /* Removes the GPGME temp directory and all files inside */
2949
3112
  if(tempdir != NULL){
2950
 
    struct dirent **direntries = NULL;
2951
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
2952
 
                                                  | O_NOFOLLOW
2953
 
                                                  | O_DIRECTORY
2954
 
                                                  | O_PATH));
2955
 
    if(tempdir_fd == -1){
2956
 
      perror_plus("open");
2957
 
    } else {
2958
 
#ifdef __GLIBC__
2959
 
#if __GLIBC_PREREQ(2, 15)
2960
 
      int numentries = scandirat(tempdir_fd, ".", &direntries,
2961
 
                                 notdotentries, alphasort);
2962
 
#else  /* not __GLIBC_PREREQ(2, 15) */
2963
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2964
 
                               alphasort);
2965
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
2966
 
#else   /* not __GLIBC__ */
2967
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2968
 
                               alphasort);
2969
 
#endif  /* not __GLIBC__ */
2970
 
      if(numentries >= 0){
2971
 
        for(int i = 0; i < numentries; i++){
2972
 
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
2973
 
          if(ret == -1){
2974
 
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
2975
 
                         " \"%s\", 0): %s\n", tempdir,
2976
 
                         direntries[i]->d_name, strerror(errno));
2977
 
          }
2978
 
          free(direntries[i]);
2979
 
        }
2980
 
        
2981
 
        /* need to clean even if 0 because man page doesn't specify */
2982
 
        free(direntries);
2983
 
        if(numentries == -1){
2984
 
          perror_plus("scandir");
2985
 
        }
2986
 
        ret = rmdir(tempdir);
2987
 
        if(ret == -1 and errno != ENOENT){
2988
 
          perror_plus("rmdir");
2989
 
        }
2990
 
      }
2991
 
      TEMP_FAILURE_RETRY(close(tempdir_fd));
2992
 
    }
 
3113
    clean_dir_at(-1, tempdir, 0);
2993
3114
  }
2994
3115
  
2995
3116
  if(quit_now){