/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: 2015-07-02 18:22:22 UTC
  • mto: This revision was merged to the branch mainline in revision 759.
  • Revision ID: teddy@recompile.se-20150702182222-034v03mb8orwhezn
mandos-client: Minor changes to check for more error conditions.

* mandos-client.c (add_remove_local_route): Do TEMP_FAILURE_RETRY
                                            around closing of
                                            /dev/null.  Check return
                                            value when opening helper
                                            directory and helper
                                            executable.
  (run_network_hooks): Cast return value of TEMP_FAILURE_RETRY to int.
                       Do TEMP_FAILURE_RETRY around closing of
                       /dev/null.

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-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
 
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
23
21
 * WITHOUT ANY WARRANTY; without even the implied warranty of
24
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25
23
 * General Public License for more details.
26
24
 * 
27
25
 * You should have received a copy of the GNU General Public License
28
 
 * along with Mandos.  If not, see <http://www.gnu.org/licenses/>.
 
26
 * along with this program.  If not, see
 
27
 * <http://www.gnu.org/licenses/>.
29
28
 * 
30
29
 * Contact the authors at <mandos@recompile.se>.
31
30
 */
47
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
48
47
                                   strtof(), abort() */
49
48
#include <stdbool.h>            /* bool, false, true */
50
 
#include <string.h>             /* strcmp(), strlen(), strerror(),
51
 
                                   asprintf(), strncpy(), strsignal()
52
 
                                */
 
49
#include <string.h>             /* memset(), strcmp(), strlen(),
 
50
                                   strerror(), asprintf(), strcpy() */
53
51
#include <sys/ioctl.h>          /* ioctl */
54
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
55
53
                                   sockaddr_in6, PF_INET6,
59
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
60
58
                                   inet_pton(), connect(),
61
59
                                   getnameinfo() */
62
 
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
 
60
#include <fcntl.h>              /* open(), unlinkat() */
63
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
64
62
                                 */
65
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
66
64
                                   strtoimax() */
67
 
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
68
 
                                   EAI_SYSTEM, ENETUNREACH,
69
 
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
70
 
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
71
 
                                   ENOTEMPTY,
 
65
#include <errno.h>              /* perror(), errno,
72
66
                                   program_invocation_short_name */
73
67
#include <time.h>               /* nanosleep(), time(), sleep() */
74
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
311
305
      return false;
312
306
    }
313
307
    
314
 
    ret = close(fd);
 
308
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
315
309
    if(ret == -1){
316
310
      perror_plus("close");
317
311
    }
420
414
      if(result == NULL){
421
415
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
422
416
      } else {
423
 
        if(result->unsupported_algorithm != NULL) {
424
 
          fprintf_plus(stderr, "Unsupported algorithm: %s\n",
425
 
                       result->unsupported_algorithm);
426
 
        }
 
417
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
418
                     result->unsupported_algorithm);
427
419
        fprintf_plus(stderr, "Wrong key usage: %u\n",
428
420
                     result->wrong_key_usage);
429
421
        if(result->file_name != NULL){
501
493
  return plaintext_length;
502
494
}
503
495
 
504
 
__attribute__((warn_unused_result, const))
505
 
static const char *safe_string(const char *str){
506
 
  if(str == NULL)
507
 
    return "(unknown)";
508
 
  return str;
509
 
}
510
 
 
511
496
__attribute__((warn_unused_result))
512
497
static const char *safer_gnutls_strerror(int value){
513
498
  const char *ret = gnutls_strerror(value);
514
 
  return safe_string(ret);
 
499
  if(ret == NULL)
 
500
    ret = "(unknown)";
 
501
  return ret;
515
502
}
516
503
 
517
504
/* GnuTLS log function callback */
521
508
  fprintf_plus(stderr, "GnuTLS: %s", string);
522
509
}
523
510
 
524
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
 
511
__attribute__((nonnull, warn_unused_result))
525
512
static int init_gnutls_global(const char *pubkeyfilename,
526
513
                              const char *seckeyfilename,
527
 
                              const char *dhparamsfilename,
528
514
                              mandos_context *mc){
529
515
  int ret;
530
 
  unsigned int uret;
531
516
  
532
517
  if(debug){
533
518
    fprintf_plus(stderr, "Initializing GnuTLS\n");
534
519
  }
535
520
  
 
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
  
536
528
  if(debug){
537
529
    /* "Use a log level over 10 to enable all debugging options."
538
530
     * - GnuTLS manual
546
538
  if(ret != GNUTLS_E_SUCCESS){
547
539
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
548
540
                 safer_gnutls_strerror(ret));
 
541
    gnutls_global_deinit();
549
542
    return -1;
550
543
  }
551
544
  
576
569
                 safer_gnutls_strerror(ret));
577
570
    goto globalfail;
578
571
  }
579
 
  /* If a Diffie-Hellman parameters file was given, try to use it */
580
 
  if(dhparamsfilename != NULL){
581
 
    gnutls_datum_t params = { .data = NULL, .size = 0 };
582
 
    do {
583
 
      int dhpfile = open(dhparamsfilename, O_RDONLY);
584
 
      if(dhpfile == -1){
585
 
        perror_plus("open");
586
 
        dhparamsfilename = NULL;
587
 
        break;
588
 
      }
589
 
      size_t params_capacity = 0;
590
 
      while(true){
591
 
        params_capacity = incbuffer((char **)&params.data,
592
 
                                    (size_t)params.size,
593
 
                                    (size_t)params_capacity);
594
 
        if(params_capacity == 0){
595
 
          perror_plus("incbuffer");
596
 
          free(params.data);
597
 
          params.data = NULL;
598
 
          dhparamsfilename = NULL;
599
 
          break;
600
 
        }
601
 
        ssize_t bytes_read = read(dhpfile,
602
 
                                  params.data + params.size,
603
 
                                  BUFFER_SIZE);
604
 
        /* EOF */
605
 
        if(bytes_read == 0){
606
 
          break;
607
 
        }
608
 
        /* check bytes_read for failure */
609
 
        if(bytes_read < 0){
610
 
          perror_plus("read");
611
 
          free(params.data);
612
 
          params.data = NULL;
613
 
          dhparamsfilename = NULL;
614
 
          break;
615
 
        }
616
 
        params.size += (unsigned int)bytes_read;
617
 
      }
618
 
      ret = close(dhpfile);
619
 
      if(ret == -1){
620
 
        perror_plus("close");
621
 
      }
622
 
      if(params.data == NULL){
623
 
        dhparamsfilename = NULL;
624
 
      }
625
 
      if(dhparamsfilename == NULL){
626
 
        break;
627
 
      }
628
 
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
629
 
                                          GNUTLS_X509_FMT_PEM);
630
 
      if(ret != GNUTLS_E_SUCCESS){
631
 
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
632
 
                     " \"%s\": %s\n", dhparamsfilename,
633
 
                     safer_gnutls_strerror(ret));
634
 
        dhparamsfilename = NULL;
635
 
      }
636
 
      free(params.data);
637
 
    } while(false);
638
 
  }
639
 
  if(dhparamsfilename == NULL){
640
 
    if(mc->dh_bits == 0){
641
 
      /* Find out the optimal number of DH bits */
642
 
      /* Try to read the private key file */
643
 
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
644
 
      do {
645
 
        int secfile = open(seckeyfilename, O_RDONLY);
646
 
        if(secfile == -1){
647
 
          perror_plus("open");
648
 
          break;
649
 
        }
650
 
        size_t buffer_capacity = 0;
651
 
        while(true){
652
 
          buffer_capacity = incbuffer((char **)&buffer.data,
653
 
                                      (size_t)buffer.size,
654
 
                                      (size_t)buffer_capacity);
655
 
          if(buffer_capacity == 0){
656
 
            perror_plus("incbuffer");
657
 
            free(buffer.data);
658
 
            buffer.data = NULL;
659
 
            break;
660
 
          }
661
 
          ssize_t bytes_read = read(secfile,
662
 
                                    buffer.data + buffer.size,
663
 
                                    BUFFER_SIZE);
664
 
          /* EOF */
665
 
          if(bytes_read == 0){
666
 
            break;
667
 
          }
668
 
          /* check bytes_read for failure */
669
 
          if(bytes_read < 0){
670
 
            perror_plus("read");
671
 
            free(buffer.data);
672
 
            buffer.data = NULL;
673
 
            break;
674
 
          }
675
 
          buffer.size += (unsigned int)bytes_read;
676
 
        }
677
 
        close(secfile);
678
 
      } while(false);
679
 
      /* If successful, use buffer to parse private key */
680
 
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
681
 
      if(buffer.data != NULL){
682
 
        {
683
 
          gnutls_openpgp_privkey_t privkey = NULL;
684
 
          ret = gnutls_openpgp_privkey_init(&privkey);
685
 
          if(ret != GNUTLS_E_SUCCESS){
686
 
            fprintf_plus(stderr, "Error initializing OpenPGP key"
687
 
                         " structure: %s",
688
 
                         safer_gnutls_strerror(ret));
689
 
            free(buffer.data);
690
 
            buffer.data = NULL;
691
 
          } else {
692
 
            ret = gnutls_openpgp_privkey_import
693
 
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
694
 
            if(ret != GNUTLS_E_SUCCESS){
695
 
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
696
 
                           safer_gnutls_strerror(ret));
697
 
              privkey = NULL;
698
 
            }
699
 
            free(buffer.data);
700
 
            buffer.data = NULL;
701
 
            if(privkey != NULL){
702
 
              /* Use private key to suggest an appropriate
703
 
                 sec_param */
704
 
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
705
 
              gnutls_openpgp_privkey_deinit(privkey);
706
 
              if(debug){
707
 
                fprintf_plus(stderr, "This OpenPGP key implies using"
708
 
                             " a GnuTLS security parameter \"%s\".\n",
709
 
                             safe_string(gnutls_sec_param_get_name
710
 
                                         (sec_param)));
711
 
              }
712
 
            }
713
 
          }
714
 
        }
715
 
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
716
 
          /* Err on the side of caution */
717
 
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
718
 
          if(debug){
719
 
            fprintf_plus(stderr, "Falling back to security parameter"
720
 
                         " \"%s\"\n",
721
 
                         safe_string(gnutls_sec_param_get_name
722
 
                                     (sec_param)));
723
 
          }
724
 
        }
725
 
      }
726
 
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
727
 
      if(uret != 0){
728
 
        mc->dh_bits = uret;
729
 
        if(debug){
730
 
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
731
 
                       " implies %u DH bits; using that.\n",
732
 
                       safe_string(gnutls_sec_param_get_name
733
 
                                   (sec_param)),
734
 
                       mc->dh_bits);
735
 
        }
736
 
      } else {
737
 
        fprintf_plus(stderr, "Failed to get implied number of DH"
738
 
                     " bits for security parameter \"%s\"): %s\n",
739
 
                     safe_string(gnutls_sec_param_get_name
740
 
                                 (sec_param)),
741
 
                     safer_gnutls_strerror(ret));
742
 
        goto globalfail;
743
 
      }
744
 
    } else if(debug){
745
 
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
746
 
                   mc->dh_bits);
747
 
    }
748
 
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
749
 
    if(ret != GNUTLS_E_SUCCESS){
750
 
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
751
 
                   " bits): %s\n", mc->dh_bits,
752
 
                   safer_gnutls_strerror(ret));
753
 
      goto globalfail;
754
 
    }
755
 
  }
 
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
  
756
579
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
757
580
  
758
581
  return 0;
760
583
 globalfail:
761
584
  
762
585
  gnutls_certificate_free_credentials(mc->cred);
 
586
  gnutls_global_deinit();
763
587
  gnutls_dh_params_deinit(mc->dh_params);
764
588
  return -1;
765
589
}
817
641
  /* ignore client certificate if any. */
818
642
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
819
643
  
 
644
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
645
  
820
646
  return 0;
821
647
}
822
648
 
826
652
 
827
653
/* Set effective uid to 0, return errno */
828
654
__attribute__((warn_unused_result))
829
 
int raise_privileges(void){
830
 
  int old_errno = errno;
831
 
  int ret = 0;
 
655
error_t raise_privileges(void){
 
656
  error_t old_errno = errno;
 
657
  error_t ret_errno = 0;
832
658
  if(seteuid(0) == -1){
833
 
    ret = errno;
 
659
    ret_errno = errno;
834
660
  }
835
661
  errno = old_errno;
836
 
  return ret;
 
662
  return ret_errno;
837
663
}
838
664
 
839
665
/* Set effective and real user ID to 0.  Return errno. */
840
666
__attribute__((warn_unused_result))
841
 
int raise_privileges_permanently(void){
842
 
  int old_errno = errno;
843
 
  int ret = raise_privileges();
844
 
  if(ret != 0){
 
667
error_t raise_privileges_permanently(void){
 
668
  error_t old_errno = errno;
 
669
  error_t ret_errno = raise_privileges();
 
670
  if(ret_errno != 0){
845
671
    errno = old_errno;
846
 
    return ret;
 
672
    return ret_errno;
847
673
  }
848
674
  if(setuid(0) == -1){
849
 
    ret = errno;
 
675
    ret_errno = errno;
850
676
  }
851
677
  errno = old_errno;
852
 
  return ret;
 
678
  return ret_errno;
853
679
}
854
680
 
855
681
/* Set effective user ID to unprivileged saved user ID */
856
682
__attribute__((warn_unused_result))
857
 
int lower_privileges(void){
858
 
  int old_errno = errno;
859
 
  int ret = 0;
 
683
error_t lower_privileges(void){
 
684
  error_t old_errno = errno;
 
685
  error_t ret_errno = 0;
860
686
  if(seteuid(uid) == -1){
861
 
    ret = errno;
 
687
    ret_errno = errno;
862
688
  }
863
689
  errno = old_errno;
864
 
  return ret;
 
690
  return ret_errno;
865
691
}
866
692
 
867
693
/* Lower privileges permanently */
868
694
__attribute__((warn_unused_result))
869
 
int lower_privileges_permanently(void){
870
 
  int old_errno = errno;
871
 
  int ret = 0;
 
695
error_t lower_privileges_permanently(void){
 
696
  error_t old_errno = errno;
 
697
  error_t ret_errno = 0;
872
698
  if(setuid(uid) == -1){
873
 
    ret = errno;
 
699
    ret_errno = errno;
874
700
  }
875
701
  errno = old_errno;
876
 
  return ret;
 
702
  return ret_errno;
877
703
}
878
704
 
879
 
/* Helper function to add_local_route() and delete_local_route() */
 
705
/* Helper function to add_local_route() and remove_local_route() */
880
706
__attribute__((nonnull, warn_unused_result))
881
 
static bool add_delete_local_route(const bool add,
 
707
static bool add_remove_local_route(const bool add,
882
708
                                   const char *address,
883
709
                                   AvahiIfIndex if_index){
884
710
  int ret;
885
711
  char helper[] = "mandos-client-iprouteadddel";
886
712
  char add_arg[] = "add";
887
 
  char delete_arg[] = "delete";
888
 
  char debug_flag[] = "--debug";
 
713
  char remove_arg[] = "remove";
889
714
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
890
715
  if(pluginhelperdir == NULL){
891
716
    if(debug){
935
760
      perror_plus("dup2(devnull, STDIN_FILENO)");
936
761
      _exit(EX_OSERR);
937
762
    }
938
 
    ret = close(devnull);
 
763
    ret = (int)TEMP_FAILURE_RETRY(close(devnull));
939
764
    if(ret == -1){
940
765
      perror_plus("close");
941
766
      _exit(EX_OSERR);
958
783
                                                   helper, O_RDONLY));
959
784
    if(helper_fd == -1){
960
785
      perror_plus("openat");
961
 
      close(helperdir_fd);
962
786
      _exit(EX_UNAVAILABLE);
963
787
    }
964
 
    close(helperdir_fd);
 
788
    TEMP_FAILURE_RETRY(close(helperdir_fd));
965
789
#ifdef __GNUC__
966
790
#pragma GCC diagnostic push
967
791
#pragma GCC diagnostic ignored "-Wcast-qual"
968
792
#endif
969
793
    if(fexecve(helper_fd, (char *const [])
970
 
               { helper, add ? add_arg : delete_arg, (char *)address,
971
 
                   interface, debug ? debug_flag : NULL, NULL },
972
 
               environ) == -1){
 
794
               { helper, add ? add_arg : remove_arg, (char *)address,
 
795
                   interface, NULL }, environ) == -1){
973
796
#ifdef __GNUC__
974
797
#pragma GCC diagnostic pop
975
798
#endif
1027
850
__attribute__((nonnull, warn_unused_result))
1028
851
static bool add_local_route(const char *address,
1029
852
                            AvahiIfIndex if_index){
1030
 
  if(debug){
1031
 
    fprintf_plus(stderr, "Adding route to %s\n", address);
1032
 
  }
1033
 
  return add_delete_local_route(true, address, if_index);
 
853
  return add_remove_local_route(true, address, if_index);
1034
854
}
1035
855
 
1036
856
__attribute__((nonnull, warn_unused_result))
1037
 
static bool delete_local_route(const char *address,
 
857
static bool remove_local_route(const char *address,
1038
858
                               AvahiIfIndex if_index){
1039
 
  if(debug){
1040
 
    fprintf_plus(stderr, "Removing route to %s\n", address);
1041
 
  }
1042
 
  return add_delete_local_route(false, address, if_index);
 
859
  return add_remove_local_route(false, address, if_index);
1043
860
}
1044
861
 
1045
862
/* Called when a Mandos server is found */
1086
903
    bool match = false;
1087
904
    {
1088
905
      char *interface = NULL;
1089
 
      while((interface = argz_next(mc->interfaces,
1090
 
                                   mc->interfaces_size,
1091
 
                                   interface))){
 
906
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
907
                                 interface))){
1092
908
        if(if_nametoindex(interface) == (unsigned int)if_index){
1093
909
          match = true;
1094
910
          break;
1136
952
    goto mandos_end;
1137
953
  }
1138
954
  
 
955
  memset(&to, 0, sizeof(to));
1139
956
  if(af == AF_INET6){
1140
 
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
1141
 
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
1142
 
    ret = inet_pton(af, ip, &to6->sin6_addr);
 
957
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
958
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
1143
959
  } else {                      /* IPv4 */
1144
 
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
1145
 
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
1146
 
    ret = inet_pton(af, ip, &to4->sin_addr);
 
960
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
961
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
1147
962
  }
1148
963
  if(ret < 0 ){
1149
964
    int e = errno;
1228
1043
                    sizeof(struct sockaddr_in));
1229
1044
    }
1230
1045
    if(ret < 0){
1231
 
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
 
1046
      if(errno == ENETUNREACH
1232
1047
         and if_index != AVAHI_IF_UNSPEC
1233
1048
         and connect_to == NULL
1234
1049
         and not route_added and
1247
1062
           with an explicit route added with the server's address.
1248
1063
           
1249
1064
           Avahi bug reference:
1250
 
           https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
 
1065
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1251
1066
           https://bugs.debian.org/587961
1252
1067
        */
1253
 
        if(debug){
1254
 
          fprintf_plus(stderr, "Mandos server unreachable, trying"
1255
 
                       " direct route\n");
1256
 
        }
1257
1068
        int e = errno;
1258
1069
        route_added = add_local_route(ip, if_index);
1259
1070
        if(route_added){
1433
1244
                                               &decrypted_buffer, mc);
1434
1245
    if(decrypted_buffer_size >= 0){
1435
1246
      
1436
 
      clearerr(stdout);
1437
1247
      written = 0;
1438
1248
      while(written < (size_t) decrypted_buffer_size){
1439
1249
        if(quit_now){
1455
1265
        }
1456
1266
        written += (size_t)ret;
1457
1267
      }
1458
 
      ret = fflush(stdout);
1459
 
      if(ret != 0){
1460
 
        int e = errno;
1461
 
        if(debug){
1462
 
          fprintf_plus(stderr, "Error writing encrypted data: %s\n",
1463
 
                       strerror(errno));
1464
 
        }
1465
 
        errno = e;
1466
 
        goto mandos_end;
1467
 
      }
1468
1268
      retval = 0;
1469
1269
    }
1470
1270
  }
1474
1274
 mandos_end:
1475
1275
  {
1476
1276
    if(route_added){
1477
 
      if(not delete_local_route(ip, if_index)){
1478
 
        fprintf_plus(stderr, "Failed to delete local route to %s on"
 
1277
      if(not remove_local_route(ip, if_index)){
 
1278
        fprintf_plus(stderr, "Failed to remove local route to %s on"
1479
1279
                     " interface %d", ip, if_index);
1480
1280
      }
1481
1281
    }
1483
1283
    free(decrypted_buffer);
1484
1284
    free(buffer);
1485
1285
    if(tcp_sd >= 0){
1486
 
      ret = close(tcp_sd);
 
1286
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1487
1287
    }
1488
1288
    if(ret == -1){
1489
1289
      if(e == 0){
1501
1301
  return retval;
1502
1302
}
1503
1303
 
 
1304
__attribute__((nonnull))
1504
1305
static void resolve_callback(AvahiSServiceResolver *r,
1505
1306
                             AvahiIfIndex interface,
1506
1307
                             AvahiProtocol proto,
1643
1444
__attribute__((nonnull, warn_unused_result))
1644
1445
bool get_flags(const char *ifname, struct ifreq *ifr){
1645
1446
  int ret;
1646
 
  int old_errno;
 
1447
  error_t ret_errno;
1647
1448
  
1648
1449
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1649
1450
  if(s < 0){
1650
 
    old_errno = errno;
 
1451
    ret_errno = errno;
1651
1452
    perror_plus("socket");
1652
 
    errno = old_errno;
 
1453
    errno = ret_errno;
1653
1454
    return false;
1654
1455
  }
1655
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1656
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
 
1456
  strcpy(ifr->ifr_name, ifname);
1657
1457
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1658
1458
  if(ret == -1){
1659
1459
    if(debug){
1660
 
      old_errno = errno;
 
1460
      ret_errno = errno;
1661
1461
      perror_plus("ioctl SIOCGIFFLAGS");
1662
 
      errno = old_errno;
1663
 
    }
1664
 
    if((close(s) == -1) and debug){
1665
 
      old_errno = errno;
1666
 
      perror_plus("close");
1667
 
      errno = old_errno;
 
1462
      errno = ret_errno;
1668
1463
    }
1669
1464
    return false;
1670
1465
  }
1671
 
  if((close(s) == -1) and debug){
1672
 
    old_errno = errno;
1673
 
    perror_plus("close");
1674
 
    errno = old_errno;
1675
 
  }
1676
1466
  return true;
1677
1467
}
1678
1468
 
1939
1729
      return;
1940
1730
    }
1941
1731
  }
1942
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
1943
 
  if(devnull == -1){
1944
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
1945
 
    return;
1946
 
  }
 
1732
#ifdef __GLIBC__
 
1733
#if __GLIBC_PREREQ(2, 15)
1947
1734
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1948
1735
                           runnable_hook, alphasort);
 
1736
#else  /* not __GLIBC_PREREQ(2, 15) */
 
1737
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1738
                         alphasort);
 
1739
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
1740
#else   /* not __GLIBC__ */
 
1741
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1742
                         alphasort);
 
1743
#endif  /* not __GLIBC__ */
1949
1744
  if(numhooks == -1){
1950
1745
    perror_plus("scandir");
1951
 
    close(devnull);
1952
1746
    return;
1953
1747
  }
1954
1748
  struct dirent *direntry;
1955
1749
  int ret;
 
1750
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
1751
  if(devnull == -1){
 
1752
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
1753
    return;
 
1754
  }
1956
1755
  for(int i = 0; i < numhooks; i++){
1957
1756
    direntry = direntries[i];
1958
1757
    if(debug){
2029
1828
        perror_plus("openat");
2030
1829
        _exit(EXIT_FAILURE);
2031
1830
      }
2032
 
      if(close(hookdir_fd) == -1){
 
1831
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2033
1832
        perror_plus("close");
2034
1833
        _exit(EXIT_FAILURE);
2035
1834
      }
2038
1837
        perror_plus("dup2(devnull, STDIN_FILENO)");
2039
1838
        _exit(EX_OSERR);
2040
1839
      }
2041
 
      ret = close(devnull);
 
1840
      ret = (int)TEMP_FAILURE_RETRY(close(devnull));
2042
1841
      if(ret == -1){
2043
1842
        perror_plus("close");
2044
1843
        _exit(EX_OSERR);
2093
1892
    free(direntry);
2094
1893
  }
2095
1894
  free(direntries);
2096
 
  if(close(hookdir_fd) == -1){
 
1895
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2097
1896
    perror_plus("close");
2098
1897
  } else {
2099
1898
    hookdir_fd = -1;
2102
1901
}
2103
1902
 
2104
1903
__attribute__((nonnull, warn_unused_result))
2105
 
int bring_up_interface(const char *const interface,
2106
 
                       const float delay){
2107
 
  int old_errno = errno;
 
1904
error_t bring_up_interface(const char *const interface,
 
1905
                           const float delay){
 
1906
  error_t old_errno = errno;
2108
1907
  int ret;
2109
1908
  struct ifreq network;
2110
1909
  unsigned int if_index = if_nametoindex(interface);
2120
1919
  }
2121
1920
  
2122
1921
  if(not interface_is_up(interface)){
2123
 
    int ret_errno = 0;
2124
 
    int ioctl_errno = 0;
 
1922
    error_t ret_errno = 0, ioctl_errno = 0;
2125
1923
    if(not get_flags(interface, &network)){
2126
1924
      ret_errno = errno;
2127
1925
      fprintf_plus(stderr, "Failed to get flags for interface "
2140
1938
    }
2141
1939
    
2142
1940
    if(quit_now){
2143
 
      ret = close(sd);
 
1941
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2144
1942
      if(ret == -1){
2145
1943
        perror_plus("close");
2146
1944
      }
2196
1994
    }
2197
1995
    
2198
1996
    /* Close the socket */
2199
 
    ret = close(sd);
 
1997
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
2200
1998
    if(ret == -1){
2201
1999
      perror_plus("close");
2202
2000
    }
2214
2012
  
2215
2013
  /* Sleep checking until interface is running.
2216
2014
     Check every 0.25s, up to total time of delay */
2217
 
  for(int i = 0; i < delay * 4; i++){
 
2015
  for(int i=0; i < delay * 4; i++){
2218
2016
    if(interface_is_running(interface)){
2219
2017
      break;
2220
2018
    }
2230
2028
}
2231
2029
 
2232
2030
__attribute__((nonnull, warn_unused_result))
2233
 
int take_down_interface(const char *const interface){
2234
 
  int old_errno = errno;
 
2031
error_t take_down_interface(const char *const interface){
 
2032
  error_t old_errno = errno;
2235
2033
  struct ifreq network;
2236
2034
  unsigned int if_index = if_nametoindex(interface);
2237
2035
  if(if_index == 0){
2240
2038
    return ENXIO;
2241
2039
  }
2242
2040
  if(interface_is_up(interface)){
2243
 
    int ret_errno = 0;
2244
 
    int ioctl_errno = 0;
 
2041
    error_t ret_errno = 0, ioctl_errno = 0;
2245
2042
    if(not get_flags(interface, &network) and debug){
2246
2043
      ret_errno = errno;
2247
2044
      fprintf_plus(stderr, "Failed to get flags for interface "
2285
2082
    }
2286
2083
    
2287
2084
    /* Close the socket */
2288
 
    int ret = close(sd);
 
2085
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
2289
2086
    if(ret == -1){
2290
2087
      perror_plus("close");
2291
2088
    }
2306
2103
}
2307
2104
 
2308
2105
int main(int argc, char *argv[]){
2309
 
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2310
 
                        .priority = "SECURE256:!CTYPE-X.509"
2311
 
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
2312
 
                        .current_server = NULL, .interfaces = NULL,
2313
 
                        .interfaces_size = 0 };
 
2106
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
2107
                        .priority = "SECURE256:!CTYPE-X.509:"
 
2108
                        "+CTYPE-OPENPGP", .current_server = NULL,
 
2109
                        .interfaces = NULL, .interfaces_size = 0 };
2314
2110
  AvahiSServiceBrowser *sb = NULL;
2315
2111
  error_t ret_errno;
2316
2112
  int ret;
2325
2121
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2326
2122
  const char *seckey = PATHDIR "/" SECKEY;
2327
2123
  const char *pubkey = PATHDIR "/" PUBKEY;
2328
 
  const char *dh_params_file = NULL;
2329
2124
  char *interfaces_hooks = NULL;
2330
2125
  
2331
2126
  bool gnutls_initialized = false;
2384
2179
        .doc = "Bit length of the prime number used in the"
2385
2180
        " Diffie-Hellman key exchange",
2386
2181
        .group = 2 },
2387
 
      { .name = "dh-params", .key = 134,
2388
 
        .arg = "FILE",
2389
 
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
2390
 
        " for the Diffie-Hellman key exchange",
2391
 
        .group = 2 },
2392
2182
      { .name = "priority", .key = 130,
2393
2183
        .arg = "STRING",
2394
2184
        .doc = "GnuTLS priority string for the TLS handshake",
2449
2239
        }
2450
2240
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2451
2241
        break;
2452
 
      case 134:                 /* --dh-params */
2453
 
        dh_params_file = arg;
2454
 
        break;
2455
2242
      case 130:                 /* --priority */
2456
2243
        mc.priority = arg;
2457
2244
        break;
2497
2284
                         .args_doc = "",
2498
2285
                         .doc = "Mandos client -- Get and decrypt"
2499
2286
                         " passwords from a Mandos server" };
2500
 
    ret_errno = argp_parse(&argp, argc, argv,
2501
 
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2502
 
    switch(ret_errno){
 
2287
    ret = argp_parse(&argp, argc, argv,
 
2288
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2289
    switch(ret){
2503
2290
    case 0:
2504
2291
      break;
2505
2292
    case ENOMEM:
2506
2293
    default:
2507
 
      errno = ret_errno;
 
2294
      errno = ret;
2508
2295
      perror_plus("argp_parse");
2509
2296
      exitcode = EX_OSERR;
2510
2297
      goto end;
2516
2303
  
2517
2304
  {
2518
2305
    /* Work around Debian bug #633582:
2519
 
       <https://bugs.debian.org/633582> */
 
2306
       <http://bugs.debian.org/633582> */
2520
2307
    
2521
2308
    /* Re-raise privileges */
2522
 
    ret = raise_privileges();
2523
 
    if(ret != 0){
2524
 
      errno = ret;
 
2309
    ret_errno = raise_privileges();
 
2310
    if(ret_errno != 0){
 
2311
      errno = ret_errno;
2525
2312
      perror_plus("Failed to raise privileges");
2526
2313
    } else {
2527
2314
      struct stat st;
2543
2330
              }
2544
2331
            }
2545
2332
          }
2546
 
          close(seckey_fd);
 
2333
          TEMP_FAILURE_RETRY(close(seckey_fd));
2547
2334
        }
2548
2335
      }
2549
2336
      
2564
2351
              }
2565
2352
            }
2566
2353
          }
2567
 
          close(pubkey_fd);
2568
 
        }
2569
 
      }
2570
 
      
2571
 
      if(dh_params_file != NULL
2572
 
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
2573
 
        int dhparams_fd = open(dh_params_file, O_RDONLY);
2574
 
        if(dhparams_fd == -1){
2575
 
          perror_plus("open");
2576
 
        } else {
2577
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
2578
 
          if(ret == -1){
2579
 
            perror_plus("fstat");
2580
 
          } else {
2581
 
            if(S_ISREG(st.st_mode)
2582
 
               and st.st_uid == 0 and st.st_gid == 0){
2583
 
              ret = fchown(dhparams_fd, uid, gid);
2584
 
              if(ret == -1){
2585
 
                perror_plus("fchown");
2586
 
              }
2587
 
            }
2588
 
          }
2589
 
          close(dhparams_fd);
 
2354
          TEMP_FAILURE_RETRY(close(pubkey_fd));
2590
2355
        }
2591
2356
      }
2592
2357
      
2593
2358
      /* Lower privileges */
2594
 
      ret = lower_privileges();
2595
 
      if(ret != 0){
2596
 
        errno = ret;
 
2359
      ret_errno = lower_privileges();
 
2360
      if(ret_errno != 0){
 
2361
        errno = ret_errno;
2597
2362
        perror_plus("Failed to lower privileges");
2598
2363
      }
2599
2364
    }
2769
2534
      errno = bring_up_interface(interface, delay);
2770
2535
      if(not interface_was_up){
2771
2536
        if(errno != 0){
2772
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2773
 
                       " %s\n", interface, strerror(errno));
 
2537
          perror_plus("Failed to bring up interface");
2774
2538
        } else {
2775
2539
          errno = argz_add(&interfaces_to_take_down,
2776
2540
                           &interfaces_to_take_down_size,
2799
2563
    goto end;
2800
2564
  }
2801
2565
  
2802
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
2566
  ret = init_gnutls_global(pubkey, seckey, &mc);
2803
2567
  if(ret == -1){
2804
2568
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2805
2569
    exitcode = EX_UNAVAILABLE;
2927
2691
    
2928
2692
    /* Allocate a new server */
2929
2693
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2930
 
                                 &config, NULL, NULL, &ret);
 
2694
                                 &config, NULL, NULL, &ret_errno);
2931
2695
    
2932
2696
    /* Free the Avahi configuration data */
2933
2697
    avahi_server_config_free(&config);
2936
2700
  /* Check if creating the Avahi server object succeeded */
2937
2701
  if(mc.server == NULL){
2938
2702
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2939
 
                 avahi_strerror(ret));
 
2703
                 avahi_strerror(ret_errno));
2940
2704
    exitcode = EX_UNAVAILABLE;
2941
2705
    goto end;
2942
2706
  }
2977
2741
 end:
2978
2742
  
2979
2743
  if(debug){
2980
 
    if(signal_received){
2981
 
      fprintf_plus(stderr, "%s exiting due to signal %d: %s\n",
2982
 
                   argv[0], signal_received,
2983
 
                   strsignal(signal_received));
2984
 
    } else {
2985
 
      fprintf_plus(stderr, "%s exiting\n", argv[0]);
2986
 
    }
 
2744
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2987
2745
  }
2988
2746
  
2989
2747
  /* Cleanup things */
3000
2758
  
3001
2759
  if(gnutls_initialized){
3002
2760
    gnutls_certificate_free_credentials(mc.cred);
 
2761
    gnutls_global_deinit();
3003
2762
    gnutls_dh_params_deinit(mc.dh_params);
3004
2763
  }
3005
2764
  
3028
2787
  
3029
2788
  /* Re-raise privileges */
3030
2789
  {
3031
 
    ret = raise_privileges();
3032
 
    if(ret != 0){
3033
 
      errno = ret;
 
2790
    ret_errno = raise_privileges();
 
2791
    if(ret_errno != 0){
 
2792
      errno = ret_errno;
3034
2793
      perror_plus("Failed to raise privileges");
3035
2794
    } else {
3036
2795
      
3041
2800
      /* Take down the network interfaces which were brought up */
3042
2801
      {
3043
2802
        char *interface = NULL;
3044
 
        while((interface = argz_next(interfaces_to_take_down,
3045
 
                                     interfaces_to_take_down_size,
3046
 
                                     interface))){
3047
 
          ret = take_down_interface(interface);
3048
 
          if(ret != 0){
3049
 
            errno = ret;
 
2803
        while((interface=argz_next(interfaces_to_take_down,
 
2804
                                   interfaces_to_take_down_size,
 
2805
                                   interface))){
 
2806
          ret_errno = take_down_interface(interface);
 
2807
          if(ret_errno != 0){
 
2808
            errno = ret_errno;
3050
2809
            perror_plus("Failed to take down interface");
3051
2810
          }
3052
2811
        }
3057
2816
      }
3058
2817
    }
3059
2818
    
3060
 
    ret = lower_privileges_permanently();
3061
 
    if(ret != 0){
3062
 
      errno = ret;
 
2819
    ret_errno = lower_privileges_permanently();
 
2820
    if(ret_errno != 0){
 
2821
      errno = ret_errno;
3063
2822
      perror_plus("Failed to lower privileges permanently");
3064
2823
    }
3065
2824
  }
3067
2826
  free(interfaces_to_take_down);
3068
2827
  free(interfaces_hooks);
3069
2828
  
3070
 
  void clean_dir_at(int base, const char * const dirname,
3071
 
                    uintmax_t level){
3072
 
    struct dirent **direntries = NULL;
3073
 
    int dret;
3074
 
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
3075
 
                                                O_RDONLY
3076
 
                                                | O_NOFOLLOW
3077
 
                                                | O_DIRECTORY
3078
 
                                                | O_PATH));
3079
 
    if(dir_fd == -1){
3080
 
      perror_plus("open");
3081
 
      return;
3082
 
    }
3083
 
    int numentries = scandirat(dir_fd, ".", &direntries,
3084
 
                               notdotentries, alphasort);
3085
 
    if(numentries >= 0){
3086
 
      for(int i = 0; i < numentries; i++){
3087
 
        if(debug){
3088
 
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
3089
 
                       dirname, direntries[i]->d_name);
3090
 
        }
3091
 
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
3092
 
        if(dret == -1){
3093
 
          if(errno == EISDIR){
3094
 
              dret = unlinkat(dir_fd, direntries[i]->d_name,
3095
 
                              AT_REMOVEDIR);
3096
 
          }         
3097
 
          if((dret == -1) and (errno == ENOTEMPTY)
3098
 
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
3099
 
                  == 0) and (level == 0)){
3100
 
            /* Recurse only in this special case */
3101
 
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
3102
 
            dret = 0;
3103
 
          }
3104
 
          if((dret == -1) and (errno != ENOENT)){
3105
 
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
3106
 
                         direntries[i]->d_name, strerror(errno));
3107
 
          }
3108
 
        }
3109
 
        free(direntries[i]);
3110
 
      }
3111
 
      
3112
 
      /* need to clean even if 0 because man page doesn't specify */
3113
 
      free(direntries);
3114
 
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
3115
 
      if(dret == -1 and errno != ENOENT){
3116
 
        perror_plus("rmdir");
3117
 
      }
3118
 
    } else {
3119
 
      perror_plus("scandirat");
3120
 
    }
3121
 
    close(dir_fd);
3122
 
  }
3123
 
  
3124
2829
  /* Removes the GPGME temp directory and all files inside */
3125
2830
  if(tempdir != NULL){
3126
 
    clean_dir_at(-1, tempdir, 0);
 
2831
    struct dirent **direntries = NULL;
 
2832
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
 
2833
                                                  | O_NOFOLLOW
 
2834
                                                  | O_DIRECTORY
 
2835
                                                  | O_PATH));
 
2836
    if(tempdir_fd == -1){
 
2837
      perror_plus("open");
 
2838
    } else {
 
2839
#ifdef __GLIBC__
 
2840
#if __GLIBC_PREREQ(2, 15)
 
2841
      int numentries = scandirat(tempdir_fd, ".", &direntries,
 
2842
                                 notdotentries, alphasort);
 
2843
#else  /* not __GLIBC_PREREQ(2, 15) */
 
2844
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2845
                               alphasort);
 
2846
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
2847
#else   /* not __GLIBC__ */
 
2848
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2849
                               alphasort);
 
2850
#endif  /* not __GLIBC__ */
 
2851
      if(numentries >= 0){
 
2852
        for(int i = 0; i < numentries; i++){
 
2853
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
 
2854
          if(ret == -1){
 
2855
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
 
2856
                         " \"%s\", 0): %s\n", tempdir,
 
2857
                         direntries[i]->d_name, strerror(errno));
 
2858
          }
 
2859
          free(direntries[i]);
 
2860
        }
 
2861
        
 
2862
        /* need to clean even if 0 because man page doesn't specify */
 
2863
        free(direntries);
 
2864
        if(numentries == -1){
 
2865
          perror_plus("scandir");
 
2866
        }
 
2867
        ret = rmdir(tempdir);
 
2868
        if(ret == -1 and errno != ENOENT){
 
2869
          perror_plus("rmdir");
 
2870
        }
 
2871
      }
 
2872
      TEMP_FAILURE_RETRY(close(tempdir_fd));
 
2873
    }
3127
2874
  }
3128
2875
  
3129
2876
  if(quit_now){