/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-05-23 20:18:34 UTC
  • mto: This revision was merged to the branch mainline in revision 756.
  • Revision ID: teddy@recompile.se-20150523201834-e89ex4ito93yni8x
mandos: Use multiprocessing module to run checkers.

For a long time, the Mandos server has occasionally logged the message
"ERROR: Child process vanished".  This was never a fatal error, but it
has been annoying and slightly worrying, since a definite cause was
not found.  One potential cause could be the "multiprocessing" and
"subprocess" modules conflicting w.r.t. SIGCHLD.  To avoid this,
change the running of checkers from using subprocess.Popen
asynchronously to instead first create a multiprocessing.Process()
(which is asynchronous) calling a function, and have that function
then call subprocess.call() (which is synchronous).  In this way, the
only thing using any asynchronous subprocesses is the multiprocessing
module.

This makes it necessary to change one small thing in the D-Bus API,
since the subprocesses.call() function does not expose the raw wait(2)
status value.

DBUS-API (CheckerCompleted): Change the second value provided by this
                             D-Bus signal from the raw wait(2) status
                             to the actual terminating signal number.
mandos (subprocess_call_pipe): New function to be called by
                               multiprocessing.Process (starting a
                               separate process).
(Client.last_checker signal): New attribute for signal which
                              terminated last checker.  Like
                              last_checker_status, only not accessible
                              via D-Bus.
(Client.checker_callback): Take new "connection" argument and use it
                           to get returncode; set last_checker_signal.
                           Return False so gobject does not call this
                           callback again.
(Client.start_checker): Start checker using a multiprocessing.Process
                        instead of a subprocess.Popen.
(ClientDBus.checker_callback): Take new "connection" argument.        Call
                               Client.checker_callback early to have
                               it set last_checker_status and
                               last_checker_signal; use those.  Change
                               second value provided to D-Bus signal
                               CheckerCompleted to use
                               last_checker_signal if checker was
                               terminated by signal.
mandos-monitor: Update to reflect DBus API change.
(MandosClientWidget.checker_completed): Take "signal" instead of
                                        "condition" argument.  Use it
                                        accordingly.  Remove dead code
                                        (os.WCOREDUMP case).

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(), strsignal()
51
 
                                */
 
49
#include <string.h>             /* memset(), strcmp(), strlen(),
 
50
                                   strerror(), asprintf(), strcpy() */
52
51
#include <sys/ioctl.h>          /* ioctl */
53
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
54
53
                                   sockaddr_in6, PF_INET6,
58
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
59
58
                                   inet_pton(), connect(),
60
59
                                   getnameinfo() */
61
 
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
 
60
#include <fcntl.h>              /* open(), unlinkat() */
62
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
63
62
                                 */
64
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
65
64
                                   strtoimax() */
66
 
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
67
 
                                   EAI_SYSTEM, ENETUNREACH,
68
 
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
69
 
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
70
 
                                   ENOTEMPTY,
 
65
#include <errno.h>              /* perror(), errno,
71
66
                                   program_invocation_short_name */
72
67
#include <time.h>               /* nanosleep(), time(), sleep() */
73
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
310
305
      return false;
311
306
    }
312
307
    
313
 
    ret = close(fd);
 
308
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
314
309
    if(ret == -1){
315
310
      perror_plus("close");
316
311
    }
518
513
  fprintf_plus(stderr, "GnuTLS: %s", string);
519
514
}
520
515
 
521
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
 
516
__attribute__((nonnull, warn_unused_result))
522
517
static int init_gnutls_global(const char *pubkeyfilename,
523
518
                              const char *seckeyfilename,
524
 
                              const char *dhparamsfilename,
525
519
                              mandos_context *mc){
526
520
  int ret;
527
521
  unsigned int uret;
530
524
    fprintf_plus(stderr, "Initializing GnuTLS\n");
531
525
  }
532
526
  
 
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
  
533
534
  if(debug){
534
535
    /* "Use a log level over 10 to enable all debugging options."
535
536
     * - GnuTLS manual
543
544
  if(ret != GNUTLS_E_SUCCESS){
544
545
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
545
546
                 safer_gnutls_strerror(ret));
 
547
    gnutls_global_deinit();
546
548
    return -1;
547
549
  }
548
550
  
573
575
                 safer_gnutls_strerror(ret));
574
576
    goto globalfail;
575
577
  }
576
 
  /* If a Diffie-Hellman parameters file was given, try to use it */
577
 
  if(dhparamsfilename != NULL){
578
 
    gnutls_datum_t params = { .data = NULL, .size = 0 };
579
 
    do {
580
 
      int dhpfile = open(dhparamsfilename, O_RDONLY);
581
 
      if(dhpfile == -1){
582
 
        perror_plus("open");
583
 
        dhparamsfilename = NULL;
584
 
        break;
585
 
      }
586
 
      size_t params_capacity = 0;
 
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;
587
585
      while(true){
588
 
        params_capacity = incbuffer((char **)&params.data,
589
 
                                    (size_t)params.size,
590
 
                                    (size_t)params_capacity);
591
 
        if(params_capacity == 0){
 
586
        buffer_capacity = incbuffer((char **)&buffer.data,
 
587
                                    (size_t)buffer.size,
 
588
                                    (size_t)buffer_capacity);
 
589
        if(buffer_capacity == 0){
592
590
          perror_plus("incbuffer");
593
 
          free(params.data);
594
 
          params.data = NULL;
595
 
          dhparamsfilename = NULL;
 
591
          free(buffer.data);
 
592
          buffer.data = NULL;
596
593
          break;
597
594
        }
598
 
        ssize_t bytes_read = read(dhpfile,
599
 
                                  params.data + params.size,
 
595
        ssize_t bytes_read = read(secfile, buffer.data + buffer.size,
600
596
                                  BUFFER_SIZE);
601
597
        /* EOF */
602
598
        if(bytes_read == 0){
605
601
        /* check bytes_read for failure */
606
602
        if(bytes_read < 0){
607
603
          perror_plus("read");
608
 
          free(params.data);
609
 
          params.data = NULL;
610
 
          dhparamsfilename = NULL;
611
 
          break;
612
 
        }
613
 
        params.size += (unsigned int)bytes_read;
614
 
      }
615
 
      if(params.data == NULL){
616
 
        dhparamsfilename = NULL;
617
 
      }
618
 
      if(dhparamsfilename == NULL){
619
 
        break;
620
 
      }
621
 
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
622
 
                                          GNUTLS_X509_FMT_PEM);
623
 
      if(ret != GNUTLS_E_SUCCESS){
624
 
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
625
 
                     " \"%s\": %s\n", dhparamsfilename,
626
 
                     safer_gnutls_strerror(ret));
627
 
        dhparamsfilename = NULL;
628
 
      }
629
 
      free(params.data);
630
 
    } while(false);
631
 
  }
632
 
  if(dhparamsfilename == NULL){
633
 
    if(mc->dh_bits == 0){
634
 
      /* Find out the optimal number of DH bits */
635
 
      /* Try to read the private key file */
636
 
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
637
 
      do {
638
 
        int secfile = open(seckeyfilename, O_RDONLY);
639
 
        if(secfile == -1){
640
 
          perror_plus("open");
641
 
          break;
642
 
        }
643
 
        size_t buffer_capacity = 0;
644
 
        while(true){
645
 
          buffer_capacity = incbuffer((char **)&buffer.data,
646
 
                                      (size_t)buffer.size,
647
 
                                      (size_t)buffer_capacity);
648
 
          if(buffer_capacity == 0){
649
 
            perror_plus("incbuffer");
650
 
            free(buffer.data);
651
 
            buffer.data = NULL;
652
 
            break;
653
 
          }
654
 
          ssize_t bytes_read = read(secfile,
655
 
                                    buffer.data + buffer.size,
656
 
                                    BUFFER_SIZE);
657
 
          /* EOF */
658
 
          if(bytes_read == 0){
659
 
            break;
660
 
          }
661
 
          /* check bytes_read for failure */
662
 
          if(bytes_read < 0){
663
 
            perror_plus("read");
664
 
            free(buffer.data);
665
 
            buffer.data = NULL;
666
 
            break;
667
 
          }
668
 
          buffer.size += (unsigned int)bytes_read;
669
 
        }
670
 
        close(secfile);
671
 
      } while(false);
672
 
      /* If successful, use buffer to parse private key */
673
 
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
674
 
      if(buffer.data != NULL){
675
 
        {
676
 
          gnutls_openpgp_privkey_t privkey = NULL;
677
 
          ret = gnutls_openpgp_privkey_init(&privkey);
 
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);
678
627
          if(ret != GNUTLS_E_SUCCESS){
679
 
            fprintf_plus(stderr, "Error initializing OpenPGP key"
680
 
                         " structure: %s",
 
628
            fprintf_plus(stderr, "Error importing OpenPGP key : %s",
681
629
                         safer_gnutls_strerror(ret));
682
 
            free(buffer.data);
683
 
            buffer.data = NULL;
684
 
          } else {
685
 
            ret = gnutls_openpgp_privkey_import
686
 
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
687
 
            if(ret != GNUTLS_E_SUCCESS){
688
 
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
689
 
                           safer_gnutls_strerror(ret));
690
 
              privkey = NULL;
691
 
            }
692
 
            free(buffer.data);
693
 
            buffer.data = NULL;
694
 
            if(privkey != NULL){
695
 
              /* Use private key to suggest an appropriate
696
 
                 sec_param */
697
 
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
698
 
              gnutls_openpgp_privkey_deinit(privkey);
699
 
              if(debug){
700
 
                fprintf_plus(stderr, "This OpenPGP key implies using"
701
 
                             " a GnuTLS security parameter \"%s\".\n",
702
 
                             safe_string(gnutls_sec_param_get_name
703
 
                                         (sec_param)));
704
 
              }
705
 
            }
 
630
            privkey = NULL;
706
631
          }
707
 
        }
708
 
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
709
 
          /* Err on the side of caution */
710
 
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
711
 
          if(debug){
712
 
            fprintf_plus(stderr, "Falling back to security parameter"
713
 
                         " \"%s\"\n",
714
 
                         safe_string(gnutls_sec_param_get_name
715
 
                                     (sec_param)));
 
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
            }
716
644
          }
717
645
        }
718
646
      }
719
 
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
720
 
      if(uret != 0){
721
 
        mc->dh_bits = uret;
 
647
      if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
 
648
        /* Err on the side of caution */
 
649
        sec_param = GNUTLS_SEC_PARAM_ULTRA;
722
650
        if(debug){
723
 
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
724
 
                       " implies %u DH bits; using that.\n",
 
651
          fprintf_plus(stderr, "Falling back to security parameter"
 
652
                       " \"%s\"\n",
725
653
                       safe_string(gnutls_sec_param_get_name
726
 
                                   (sec_param)),
727
 
                       mc->dh_bits);
 
654
                                   (sec_param)));
728
655
        }
729
 
      } else {
730
 
        fprintf_plus(stderr, "Failed to get implied number of DH"
731
 
                     " bits for security parameter \"%s\"): %s\n",
 
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",
732
664
                     safe_string(gnutls_sec_param_get_name
733
665
                                 (sec_param)),
734
 
                     safer_gnutls_strerror(ret));
735
 
        goto globalfail;
 
666
                     mc->dh_bits);
736
667
      }
737
 
    } else if(debug){
738
 
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
739
 
                   mc->dh_bits);
740
 
    }
741
 
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
742
 
    if(ret != GNUTLS_E_SUCCESS){
743
 
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
744
 
                   " bits): %s\n", mc->dh_bits,
 
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)),
745
672
                   safer_gnutls_strerror(ret));
746
673
      goto globalfail;
747
674
    }
748
 
  }
 
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
  
749
686
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
750
687
  
751
688
  return 0;
753
690
 globalfail:
754
691
  
755
692
  gnutls_certificate_free_credentials(mc->cred);
 
693
  gnutls_global_deinit();
756
694
  gnutls_dh_params_deinit(mc->dh_params);
757
695
  return -1;
758
696
}
810
748
  /* ignore client certificate if any. */
811
749
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
812
750
  
 
751
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
752
  
813
753
  return 0;
814
754
}
815
755
 
817
757
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
818
758
                      __attribute__((unused)) const char *txt){}
819
759
 
820
 
/* Set effective uid to 0, return errno */
821
 
__attribute__((warn_unused_result))
822
 
int raise_privileges(void){
823
 
  int old_errno = errno;
824
 
  int ret = 0;
825
 
  if(seteuid(0) == -1){
826
 
    ret = errno;
827
 
  }
828
 
  errno = old_errno;
829
 
  return ret;
830
 
}
831
 
 
832
 
/* Set effective and real user ID to 0.  Return errno. */
833
 
__attribute__((warn_unused_result))
834
 
int raise_privileges_permanently(void){
835
 
  int old_errno = errno;
836
 
  int ret = raise_privileges();
837
 
  if(ret != 0){
838
 
    errno = old_errno;
839
 
    return ret;
840
 
  }
841
 
  if(setuid(0) == -1){
842
 
    ret = errno;
843
 
  }
844
 
  errno = old_errno;
845
 
  return ret;
846
 
}
847
 
 
848
 
/* Set effective user ID to unprivileged saved user ID */
849
 
__attribute__((warn_unused_result))
850
 
int lower_privileges(void){
851
 
  int old_errno = errno;
852
 
  int ret = 0;
853
 
  if(seteuid(uid) == -1){
854
 
    ret = errno;
855
 
  }
856
 
  errno = old_errno;
857
 
  return ret;
858
 
}
859
 
 
860
 
/* Lower privileges permanently */
861
 
__attribute__((warn_unused_result))
862
 
int lower_privileges_permanently(void){
863
 
  int old_errno = errno;
864
 
  int ret = 0;
865
 
  if(setuid(uid) == -1){
866
 
    ret = errno;
867
 
  }
868
 
  errno = old_errno;
869
 
  return ret;
870
 
}
871
 
 
872
 
/* Helper function to add_local_route() and delete_local_route() */
873
 
__attribute__((nonnull, warn_unused_result))
874
 
static bool add_delete_local_route(const bool add,
875
 
                                   const char *address,
876
 
                                   AvahiIfIndex if_index){
877
 
  int ret;
878
 
  char helper[] = "mandos-client-iprouteadddel";
879
 
  char add_arg[] = "add";
880
 
  char delete_arg[] = "delete";
881
 
  char debug_flag[] = "--debug";
882
 
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
883
 
  if(pluginhelperdir == NULL){
884
 
    if(debug){
885
 
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
886
 
                   " variable not set; cannot run helper\n");
887
 
    }
888
 
    return false;
889
 
  }
890
 
  
891
 
  char interface[IF_NAMESIZE];
892
 
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
893
 
    perror_plus("if_indextoname");
894
 
    return false;
895
 
  }
896
 
  
897
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
898
 
  if(devnull == -1){
899
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
900
 
    return false;
901
 
  }
902
 
  pid_t pid = fork();
903
 
  if(pid == 0){
904
 
    /* Child */
905
 
    /* Raise privileges */
906
 
    errno = raise_privileges_permanently();
907
 
    if(errno != 0){
908
 
      perror_plus("Failed to raise privileges");
909
 
      /* _exit(EX_NOPERM); */
910
 
    } else {
911
 
      /* Set group */
912
 
      errno = 0;
913
 
      ret = setgid(0);
914
 
      if(ret == -1){
915
 
        perror_plus("setgid");
916
 
        _exit(EX_NOPERM);
917
 
      }
918
 
      /* Reset supplementary groups */
919
 
      errno = 0;
920
 
      ret = setgroups(0, NULL);
921
 
      if(ret == -1){
922
 
        perror_plus("setgroups");
923
 
        _exit(EX_NOPERM);
924
 
      }
925
 
    }
926
 
    ret = dup2(devnull, STDIN_FILENO);
927
 
    if(ret == -1){
928
 
      perror_plus("dup2(devnull, STDIN_FILENO)");
929
 
      _exit(EX_OSERR);
930
 
    }
931
 
    ret = close(devnull);
932
 
    if(ret == -1){
933
 
      perror_plus("close");
934
 
      _exit(EX_OSERR);
935
 
    }
936
 
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
937
 
    if(ret == -1){
938
 
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
939
 
      _exit(EX_OSERR);
940
 
    }
941
 
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
942
 
                                                    O_RDONLY
943
 
                                                    | O_DIRECTORY
944
 
                                                    | O_PATH
945
 
                                                    | O_CLOEXEC));
946
 
    if(helperdir_fd == -1){
947
 
      perror_plus("open");
948
 
      _exit(EX_UNAVAILABLE);
949
 
    }
950
 
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
951
 
                                                   helper, O_RDONLY));
952
 
    if(helper_fd == -1){
953
 
      perror_plus("openat");
954
 
      close(helperdir_fd);
955
 
      _exit(EX_UNAVAILABLE);
956
 
    }
957
 
    close(helperdir_fd);
958
 
#ifdef __GNUC__
959
 
#pragma GCC diagnostic push
960
 
#pragma GCC diagnostic ignored "-Wcast-qual"
961
 
#endif
962
 
    if(fexecve(helper_fd, (char *const [])
963
 
               { helper, add ? add_arg : delete_arg, (char *)address,
964
 
                   interface, debug ? debug_flag : NULL, NULL },
965
 
               environ) == -1){
966
 
#ifdef __GNUC__
967
 
#pragma GCC diagnostic pop
968
 
#endif
969
 
      perror_plus("fexecve");
970
 
      _exit(EXIT_FAILURE);
971
 
    }
972
 
  }
973
 
  if(pid == -1){
974
 
    perror_plus("fork");
975
 
    return false;
976
 
  }
977
 
  int status;
978
 
  pid_t pret = -1;
979
 
  errno = 0;
980
 
  do {
981
 
    pret = waitpid(pid, &status, 0);
982
 
    if(pret == -1 and errno == EINTR and quit_now){
983
 
      int errno_raising = 0;
984
 
      if((errno = raise_privileges()) != 0){
985
 
        errno_raising = errno;
986
 
        perror_plus("Failed to raise privileges in order to"
987
 
                    " kill helper program");
988
 
      }
989
 
      if(kill(pid, SIGTERM) == -1){
990
 
        perror_plus("kill");
991
 
      }
992
 
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
993
 
        perror_plus("Failed to lower privileges after killing"
994
 
                    " helper program");
995
 
      }
996
 
      return false;
997
 
    }
998
 
  } while(pret == -1 and errno == EINTR);
999
 
  if(pret == -1){
1000
 
    perror_plus("waitpid");
1001
 
    return false;
1002
 
  }
1003
 
  if(WIFEXITED(status)){
1004
 
    if(WEXITSTATUS(status) != 0){
1005
 
      fprintf_plus(stderr, "Error: iprouteadddel exited"
1006
 
                   " with status %d\n", WEXITSTATUS(status));
1007
 
      return false;
1008
 
    }
1009
 
    return true;
1010
 
  }
1011
 
  if(WIFSIGNALED(status)){
1012
 
    fprintf_plus(stderr, "Error: iprouteadddel died by"
1013
 
                 " signal %d\n", WTERMSIG(status));
1014
 
    return false;
1015
 
  }
1016
 
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
1017
 
  return false;
1018
 
}
1019
 
 
1020
 
__attribute__((nonnull, warn_unused_result))
1021
 
static bool add_local_route(const char *address,
1022
 
                            AvahiIfIndex if_index){
1023
 
  if(debug){
1024
 
    fprintf_plus(stderr, "Adding route to %s\n", address);
1025
 
  }
1026
 
  return add_delete_local_route(true, address, if_index);
1027
 
}
1028
 
 
1029
 
__attribute__((nonnull, warn_unused_result))
1030
 
static bool delete_local_route(const char *address,
1031
 
                               AvahiIfIndex if_index){
1032
 
  if(debug){
1033
 
    fprintf_plus(stderr, "Removing route to %s\n", address);
1034
 
  }
1035
 
  return add_delete_local_route(false, address, if_index);
1036
 
}
1037
 
 
1038
760
/* Called when a Mandos server is found */
1039
761
__attribute__((nonnull, warn_unused_result))
1040
762
static int start_mandos_communication(const char *ip, in_port_t port,
1051
773
  int retval = -1;
1052
774
  gnutls_session_t session;
1053
775
  int pf;                       /* Protocol family */
1054
 
  bool route_added = false;
1055
776
  
1056
777
  errno = 0;
1057
778
  
1115
836
                 PRIuMAX "\n", ip, (uintmax_t)port);
1116
837
  }
1117
838
  
1118
 
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
 
839
  tcp_sd = socket(pf, SOCK_STREAM, 0);
1119
840
  if(tcp_sd < 0){
1120
841
    int e = errno;
1121
842
    perror_plus("socket");
1128
849
    goto mandos_end;
1129
850
  }
1130
851
  
 
852
  memset(&to, 0, sizeof(to));
1131
853
  if(af == AF_INET6){
1132
 
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
1133
 
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
1134
 
    ret = inet_pton(af, ip, &to6->sin6_addr);
 
854
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
855
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
1135
856
  } else {                      /* IPv4 */
1136
 
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
1137
 
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
1138
 
    ret = inet_pton(af, ip, &to4->sin_addr);
 
857
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
858
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
1139
859
  }
1140
860
  if(ret < 0 ){
1141
861
    int e = errno;
1211
931
    goto mandos_end;
1212
932
  }
1213
933
  
1214
 
  while(true){
1215
 
    if(af == AF_INET6){
1216
 
      ret = connect(tcp_sd, (struct sockaddr *)&to,
1217
 
                    sizeof(struct sockaddr_in6));
1218
 
    } else {
1219
 
      ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
1220
 
                    sizeof(struct sockaddr_in));
1221
 
    }
1222
 
    if(ret < 0){
1223
 
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
1224
 
         and if_index != AVAHI_IF_UNSPEC
1225
 
         and connect_to == NULL
1226
 
         and not route_added and
1227
 
         ((af == AF_INET6 and not
1228
 
           IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
1229
 
                                    &to)->sin6_addr)))
1230
 
          or (af == AF_INET and
1231
 
              /* Not a a IPv4LL address */
1232
 
              (ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
1233
 
               & 0xFFFF0000L) != 0xA9FE0000L))){
1234
 
        /* Work around Avahi bug - Avahi does not announce link-local
1235
 
           addresses if it has a global address, so local hosts with
1236
 
           *only* a link-local address (e.g. Mandos clients) cannot
1237
 
           connect to a Mandos server announced by Avahi on a server
1238
 
           host with a global address.  Work around this by retrying
1239
 
           with an explicit route added with the server's address.
1240
 
           
1241
 
           Avahi bug reference:
1242
 
           https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1243
 
           https://bugs.debian.org/587961
1244
 
        */
1245
 
        if(debug){
1246
 
          fprintf_plus(stderr, "Mandos server unreachable, trying"
1247
 
                       " direct route\n");
1248
 
        }
1249
 
        int e = errno;
1250
 
        route_added = add_local_route(ip, if_index);
1251
 
        if(route_added){
1252
 
          continue;
1253
 
        }
1254
 
        errno = e;
1255
 
      }
1256
 
      if(errno != ECONNREFUSED or debug){
1257
 
        int e = errno;
1258
 
        perror_plus("connect");
1259
 
        errno = e;
1260
 
      }
1261
 
      goto mandos_end;
1262
 
    }
1263
 
    
1264
 
    if(quit_now){
1265
 
      errno = EINTR;
1266
 
      goto mandos_end;
1267
 
    }
1268
 
    break;
 
934
  if(af == AF_INET6){
 
935
    ret = connect(tcp_sd, (struct sockaddr *)&to,
 
936
                  sizeof(struct sockaddr_in6));
 
937
  } else {
 
938
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
939
                  sizeof(struct sockaddr_in));
 
940
  }
 
941
  if(ret < 0){
 
942
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
943
      int e = errno;
 
944
      perror_plus("connect");
 
945
      errno = e;
 
946
    }
 
947
    goto mandos_end;
 
948
  }
 
949
  
 
950
  if(quit_now){
 
951
    errno = EINTR;
 
952
    goto mandos_end;
1269
953
  }
1270
954
  
1271
955
  const char *out = mandos_protocol_version;
1425
1109
                                               &decrypted_buffer, mc);
1426
1110
    if(decrypted_buffer_size >= 0){
1427
1111
      
1428
 
      clearerr(stdout);
1429
1112
      written = 0;
1430
1113
      while(written < (size_t) decrypted_buffer_size){
1431
1114
        if(quit_now){
1447
1130
        }
1448
1131
        written += (size_t)ret;
1449
1132
      }
1450
 
      ret = fflush(stdout);
1451
 
      if(ret != 0){
1452
 
        int e = errno;
1453
 
        if(debug){
1454
 
          fprintf_plus(stderr, "Error writing encrypted data: %s\n",
1455
 
                       strerror(errno));
1456
 
        }
1457
 
        errno = e;
1458
 
        goto mandos_end;
1459
 
      }
1460
1133
      retval = 0;
1461
1134
    }
1462
1135
  }
1465
1138
  
1466
1139
 mandos_end:
1467
1140
  {
1468
 
    if(route_added){
1469
 
      if(not delete_local_route(ip, if_index)){
1470
 
        fprintf_plus(stderr, "Failed to delete local route to %s on"
1471
 
                     " interface %d", ip, if_index);
1472
 
      }
1473
 
    }
1474
1141
    int e = errno;
1475
1142
    free(decrypted_buffer);
1476
1143
    free(buffer);
1477
1144
    if(tcp_sd >= 0){
1478
 
      ret = close(tcp_sd);
 
1145
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1479
1146
    }
1480
1147
    if(ret == -1){
1481
1148
      if(e == 0){
1636
1303
__attribute__((nonnull, warn_unused_result))
1637
1304
bool get_flags(const char *ifname, struct ifreq *ifr){
1638
1305
  int ret;
1639
 
  int old_errno;
 
1306
  error_t ret_errno;
1640
1307
  
1641
1308
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1642
1309
  if(s < 0){
1643
 
    old_errno = errno;
 
1310
    ret_errno = errno;
1644
1311
    perror_plus("socket");
1645
 
    errno = old_errno;
 
1312
    errno = ret_errno;
1646
1313
    return false;
1647
1314
  }
1648
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1649
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
 
1315
  strcpy(ifr->ifr_name, ifname);
1650
1316
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1651
1317
  if(ret == -1){
1652
1318
    if(debug){
1653
 
      old_errno = errno;
 
1319
      ret_errno = errno;
1654
1320
      perror_plus("ioctl SIOCGIFFLAGS");
1655
 
      errno = old_errno;
 
1321
      errno = ret_errno;
1656
1322
    }
1657
1323
    return false;
1658
1324
  }
1903
1569
  }
1904
1570
}
1905
1571
 
 
1572
/* Set effective uid to 0, return errno */
 
1573
__attribute__((warn_unused_result))
 
1574
error_t raise_privileges(void){
 
1575
  error_t old_errno = errno;
 
1576
  error_t ret_errno = 0;
 
1577
  if(seteuid(0) == -1){
 
1578
    ret_errno = errno;
 
1579
  }
 
1580
  errno = old_errno;
 
1581
  return ret_errno;
 
1582
}
 
1583
 
 
1584
/* Set effective and real user ID to 0.  Return errno. */
 
1585
__attribute__((warn_unused_result))
 
1586
error_t raise_privileges_permanently(void){
 
1587
  error_t old_errno = errno;
 
1588
  error_t ret_errno = raise_privileges();
 
1589
  if(ret_errno != 0){
 
1590
    errno = old_errno;
 
1591
    return ret_errno;
 
1592
  }
 
1593
  if(setuid(0) == -1){
 
1594
    ret_errno = errno;
 
1595
  }
 
1596
  errno = old_errno;
 
1597
  return ret_errno;
 
1598
}
 
1599
 
 
1600
/* Set effective user ID to unprivileged saved user ID */
 
1601
__attribute__((warn_unused_result))
 
1602
error_t lower_privileges(void){
 
1603
  error_t old_errno = errno;
 
1604
  error_t ret_errno = 0;
 
1605
  if(seteuid(uid) == -1){
 
1606
    ret_errno = errno;
 
1607
  }
 
1608
  errno = old_errno;
 
1609
  return ret_errno;
 
1610
}
 
1611
 
 
1612
/* Lower privileges permanently */
 
1613
__attribute__((warn_unused_result))
 
1614
error_t lower_privileges_permanently(void){
 
1615
  error_t old_errno = errno;
 
1616
  error_t ret_errno = 0;
 
1617
  if(setuid(uid) == -1){
 
1618
    ret_errno = errno;
 
1619
  }
 
1620
  errno = old_errno;
 
1621
  return ret_errno;
 
1622
}
 
1623
 
1906
1624
__attribute__((nonnull))
1907
1625
void run_network_hooks(const char *mode, const char *interface,
1908
1626
                       const float delay){
1909
1627
  struct dirent **direntries = NULL;
1910
1628
  if(hookdir_fd == -1){
1911
 
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
1912
 
                      | O_CLOEXEC);
 
1629
    hookdir_fd = open(hookdir, O_RDONLY);
1913
1630
    if(hookdir_fd == -1){
1914
1631
      if(errno == ENOENT){
1915
1632
        if(debug){
1922
1639
      return;
1923
1640
    }
1924
1641
  }
 
1642
#ifdef __GLIBC__
 
1643
#if __GLIBC_PREREQ(2, 15)
1925
1644
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1926
1645
                           runnable_hook, alphasort);
 
1646
#else  /* not __GLIBC_PREREQ(2, 15) */
 
1647
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1648
                         alphasort);
 
1649
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
1650
#else   /* not __GLIBC__ */
 
1651
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1652
                         alphasort);
 
1653
#endif  /* not __GLIBC__ */
1927
1654
  if(numhooks == -1){
1928
1655
    perror_plus("scandir");
1929
1656
    return;
1930
1657
  }
1931
1658
  struct dirent *direntry;
1932
1659
  int ret;
1933
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
1934
 
  if(devnull == -1){
1935
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
1936
 
    return;
1937
 
  }
 
1660
  int devnull = open("/dev/null", O_RDONLY);
1938
1661
  for(int i = 0; i < numhooks; i++){
1939
1662
    direntry = direntries[i];
1940
1663
    if(debug){
1964
1687
        perror_plus("setgroups");
1965
1688
        _exit(EX_NOPERM);
1966
1689
      }
 
1690
      ret = dup2(devnull, STDIN_FILENO);
 
1691
      if(ret == -1){
 
1692
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
1693
        _exit(EX_OSERR);
 
1694
      }
 
1695
      ret = close(devnull);
 
1696
      if(ret == -1){
 
1697
        perror_plus("close");
 
1698
        _exit(EX_OSERR);
 
1699
      }
 
1700
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
1701
      if(ret == -1){
 
1702
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
1703
        _exit(EX_OSERR);
 
1704
      }
1967
1705
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1968
1706
      if(ret == -1){
1969
1707
        perror_plus("setenv");
2004
1742
          _exit(EX_OSERR);
2005
1743
        }
2006
1744
      }
2007
 
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
2008
 
                                                   direntry->d_name,
2009
 
                                                   O_RDONLY));
 
1745
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
2010
1746
      if(hook_fd == -1){
2011
1747
        perror_plus("openat");
2012
1748
        _exit(EXIT_FAILURE);
2013
1749
      }
2014
 
      if(close(hookdir_fd) == -1){
 
1750
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2015
1751
        perror_plus("close");
2016
1752
        _exit(EXIT_FAILURE);
2017
1753
      }
2018
 
      ret = dup2(devnull, STDIN_FILENO);
2019
 
      if(ret == -1){
2020
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
2021
 
        _exit(EX_OSERR);
2022
 
      }
2023
 
      ret = close(devnull);
2024
 
      if(ret == -1){
2025
 
        perror_plus("close");
2026
 
        _exit(EX_OSERR);
2027
 
      }
2028
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
2029
 
      if(ret == -1){
2030
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
2031
 
        _exit(EX_OSERR);
2032
 
      }
2033
1754
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
2034
1755
                 environ) == -1){
2035
1756
        perror_plus("fexecve");
2075
1796
    free(direntry);
2076
1797
  }
2077
1798
  free(direntries);
2078
 
  if(close(hookdir_fd) == -1){
 
1799
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2079
1800
    perror_plus("close");
2080
1801
  } else {
2081
1802
    hookdir_fd = -1;
2084
1805
}
2085
1806
 
2086
1807
__attribute__((nonnull, warn_unused_result))
2087
 
int bring_up_interface(const char *const interface,
2088
 
                       const float delay){
2089
 
  int old_errno = errno;
 
1808
error_t bring_up_interface(const char *const interface,
 
1809
                           const float delay){
 
1810
  error_t old_errno = errno;
2090
1811
  int ret;
2091
1812
  struct ifreq network;
2092
1813
  unsigned int if_index = if_nametoindex(interface);
2102
1823
  }
2103
1824
  
2104
1825
  if(not interface_is_up(interface)){
2105
 
    int ret_errno = 0;
2106
 
    int ioctl_errno = 0;
 
1826
    error_t ret_errno = 0, ioctl_errno = 0;
2107
1827
    if(not get_flags(interface, &network)){
2108
1828
      ret_errno = errno;
2109
1829
      fprintf_plus(stderr, "Failed to get flags for interface "
2122
1842
    }
2123
1843
    
2124
1844
    if(quit_now){
2125
 
      ret = close(sd);
 
1845
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2126
1846
      if(ret == -1){
2127
1847
        perror_plus("close");
2128
1848
      }
2178
1898
    }
2179
1899
    
2180
1900
    /* Close the socket */
2181
 
    ret = close(sd);
 
1901
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
2182
1902
    if(ret == -1){
2183
1903
      perror_plus("close");
2184
1904
    }
2212
1932
}
2213
1933
 
2214
1934
__attribute__((nonnull, warn_unused_result))
2215
 
int take_down_interface(const char *const interface){
2216
 
  int old_errno = errno;
 
1935
error_t take_down_interface(const char *const interface){
 
1936
  error_t old_errno = errno;
2217
1937
  struct ifreq network;
2218
1938
  unsigned int if_index = if_nametoindex(interface);
2219
1939
  if(if_index == 0){
2222
1942
    return ENXIO;
2223
1943
  }
2224
1944
  if(interface_is_up(interface)){
2225
 
    int ret_errno = 0;
2226
 
    int ioctl_errno = 0;
 
1945
    error_t ret_errno = 0, ioctl_errno = 0;
2227
1946
    if(not get_flags(interface, &network) and debug){
2228
1947
      ret_errno = errno;
2229
1948
      fprintf_plus(stderr, "Failed to get flags for interface "
2267
1986
    }
2268
1987
    
2269
1988
    /* Close the socket */
2270
 
    int ret = close(sd);
 
1989
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
2271
1990
    if(ret == -1){
2272
1991
      perror_plus("close");
2273
1992
    }
2289
2008
 
2290
2009
int main(int argc, char *argv[]){
2291
2010
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2292
 
                        .priority = "SECURE256:!CTYPE-X.509"
2293
 
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
2294
 
                        .current_server = NULL, .interfaces = NULL,
2295
 
                        .interfaces_size = 0 };
 
2011
                        .priority = "SECURE256:!CTYPE-X.509:"
 
2012
                        "+CTYPE-OPENPGP:!RSA", .current_server = NULL,
 
2013
                        .interfaces = NULL, .interfaces_size = 0 };
2296
2014
  AvahiSServiceBrowser *sb = NULL;
2297
2015
  error_t ret_errno;
2298
2016
  int ret;
2307
2025
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2308
2026
  const char *seckey = PATHDIR "/" SECKEY;
2309
2027
  const char *pubkey = PATHDIR "/" PUBKEY;
2310
 
  const char *dh_params_file = NULL;
2311
2028
  char *interfaces_hooks = NULL;
2312
2029
  
2313
2030
  bool gnutls_initialized = false;
2366
2083
        .doc = "Bit length of the prime number used in the"
2367
2084
        " Diffie-Hellman key exchange",
2368
2085
        .group = 2 },
2369
 
      { .name = "dh-params", .key = 134,
2370
 
        .arg = "FILE",
2371
 
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
2372
 
        " for the Diffie-Hellman key exchange",
2373
 
        .group = 2 },
2374
2086
      { .name = "priority", .key = 130,
2375
2087
        .arg = "STRING",
2376
2088
        .doc = "GnuTLS priority string for the TLS handshake",
2431
2143
        }
2432
2144
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2433
2145
        break;
2434
 
      case 134:                 /* --dh-params */
2435
 
        dh_params_file = arg;
2436
 
        break;
2437
2146
      case 130:                 /* --priority */
2438
2147
        mc.priority = arg;
2439
2148
        break;
2479
2188
                         .args_doc = "",
2480
2189
                         .doc = "Mandos client -- Get and decrypt"
2481
2190
                         " passwords from a Mandos server" };
2482
 
    ret_errno = argp_parse(&argp, argc, argv,
2483
 
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2484
 
    switch(ret_errno){
 
2191
    ret = argp_parse(&argp, argc, argv,
 
2192
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2193
    switch(ret){
2485
2194
    case 0:
2486
2195
      break;
2487
2196
    case ENOMEM:
2488
2197
    default:
2489
 
      errno = ret_errno;
 
2198
      errno = ret;
2490
2199
      perror_plus("argp_parse");
2491
2200
      exitcode = EX_OSERR;
2492
2201
      goto end;
2495
2204
      goto end;
2496
2205
    }
2497
2206
  }
2498
 
  
 
2207
    
2499
2208
  {
2500
2209
    /* Work around Debian bug #633582:
2501
 
       <https://bugs.debian.org/633582> */
 
2210
       <http://bugs.debian.org/633582> */
2502
2211
    
2503
2212
    /* Re-raise privileges */
2504
 
    ret = raise_privileges();
2505
 
    if(ret != 0){
2506
 
      errno = ret;
 
2213
    ret_errno = raise_privileges();
 
2214
    if(ret_errno != 0){
 
2215
      errno = ret_errno;
2507
2216
      perror_plus("Failed to raise privileges");
2508
2217
    } else {
2509
2218
      struct stat st;
2525
2234
              }
2526
2235
            }
2527
2236
          }
2528
 
          close(seckey_fd);
 
2237
          TEMP_FAILURE_RETRY(close(seckey_fd));
2529
2238
        }
2530
2239
      }
2531
 
      
 
2240
    
2532
2241
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2533
2242
        int pubkey_fd = open(pubkey, O_RDONLY);
2534
2243
        if(pubkey_fd == -1){
2546
2255
              }
2547
2256
            }
2548
2257
          }
2549
 
          close(pubkey_fd);
2550
 
        }
2551
 
      }
2552
 
      
2553
 
      if(dh_params_file != NULL
2554
 
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
2555
 
        int dhparams_fd = open(dh_params_file, O_RDONLY);
2556
 
        if(dhparams_fd == -1){
2557
 
          perror_plus("open");
2558
 
        } else {
2559
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
2560
 
          if(ret == -1){
2561
 
            perror_plus("fstat");
2562
 
          } else {
2563
 
            if(S_ISREG(st.st_mode)
2564
 
               and st.st_uid == 0 and st.st_gid == 0){
2565
 
              ret = fchown(dhparams_fd, uid, gid);
2566
 
              if(ret == -1){
2567
 
                perror_plus("fchown");
2568
 
              }
2569
 
            }
2570
 
          }
2571
 
          close(dhparams_fd);
2572
 
        }
2573
 
      }
2574
 
      
 
2258
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2259
        }
 
2260
      }
 
2261
    
2575
2262
      /* Lower privileges */
2576
 
      ret = lower_privileges();
2577
 
      if(ret != 0){
2578
 
        errno = ret;
 
2263
      ret_errno = lower_privileges();
 
2264
      if(ret_errno != 0){
 
2265
        errno = ret_errno;
2579
2266
        perror_plus("Failed to lower privileges");
2580
2267
      }
2581
2268
    }
2751
2438
      errno = bring_up_interface(interface, delay);
2752
2439
      if(not interface_was_up){
2753
2440
        if(errno != 0){
2754
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2755
 
                       " %s\n", interface, strerror(errno));
 
2441
          perror_plus("Failed to bring up interface");
2756
2442
        } else {
2757
2443
          errno = argz_add(&interfaces_to_take_down,
2758
2444
                           &interfaces_to_take_down_size,
2781
2467
    goto end;
2782
2468
  }
2783
2469
  
2784
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
2470
  ret = init_gnutls_global(pubkey, seckey, &mc);
2785
2471
  if(ret == -1){
2786
2472
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2787
2473
    exitcode = EX_UNAVAILABLE;
2909
2595
    
2910
2596
    /* Allocate a new server */
2911
2597
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2912
 
                                 &config, NULL, NULL, &ret);
 
2598
                                 &config, NULL, NULL, &ret_errno);
2913
2599
    
2914
2600
    /* Free the Avahi configuration data */
2915
2601
    avahi_server_config_free(&config);
2918
2604
  /* Check if creating the Avahi server object succeeded */
2919
2605
  if(mc.server == NULL){
2920
2606
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2921
 
                 avahi_strerror(ret));
 
2607
                 avahi_strerror(ret_errno));
2922
2608
    exitcode = EX_UNAVAILABLE;
2923
2609
    goto end;
2924
2610
  }
2959
2645
 end:
2960
2646
  
2961
2647
  if(debug){
2962
 
    if(signal_received){
2963
 
      fprintf_plus(stderr, "%s exiting due to signal %d: %s\n",
2964
 
                   argv[0], signal_received,
2965
 
                   strsignal(signal_received));
2966
 
    } else {
2967
 
      fprintf_plus(stderr, "%s exiting\n", argv[0]);
2968
 
    }
 
2648
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2969
2649
  }
2970
2650
  
2971
2651
  /* Cleanup things */
2982
2662
  
2983
2663
  if(gnutls_initialized){
2984
2664
    gnutls_certificate_free_credentials(mc.cred);
 
2665
    gnutls_global_deinit();
2985
2666
    gnutls_dh_params_deinit(mc.dh_params);
2986
2667
  }
2987
2668
  
3010
2691
  
3011
2692
  /* Re-raise privileges */
3012
2693
  {
3013
 
    ret = raise_privileges();
3014
 
    if(ret != 0){
3015
 
      errno = ret;
 
2694
    ret_errno = raise_privileges();
 
2695
    if(ret_errno != 0){
 
2696
      errno = ret_errno;
3016
2697
      perror_plus("Failed to raise privileges");
3017
2698
    } else {
3018
2699
      
3026
2707
        while((interface=argz_next(interfaces_to_take_down,
3027
2708
                                   interfaces_to_take_down_size,
3028
2709
                                   interface))){
3029
 
          ret = take_down_interface(interface);
3030
 
          if(ret != 0){
3031
 
            errno = ret;
 
2710
          ret_errno = take_down_interface(interface);
 
2711
          if(ret_errno != 0){
 
2712
            errno = ret_errno;
3032
2713
            perror_plus("Failed to take down interface");
3033
2714
          }
3034
2715
        }
3039
2720
      }
3040
2721
    }
3041
2722
    
3042
 
    ret = lower_privileges_permanently();
3043
 
    if(ret != 0){
3044
 
      errno = ret;
 
2723
    ret_errno = lower_privileges_permanently();
 
2724
    if(ret_errno != 0){
 
2725
      errno = ret_errno;
3045
2726
      perror_plus("Failed to lower privileges permanently");
3046
2727
    }
3047
2728
  }
3049
2730
  free(interfaces_to_take_down);
3050
2731
  free(interfaces_hooks);
3051
2732
  
3052
 
  void clean_dir_at(int base, const char * const dirname,
3053
 
                    uintmax_t level){
3054
 
    struct dirent **direntries = NULL;
3055
 
    int dret;
3056
 
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
3057
 
                                                O_RDONLY
3058
 
                                                | O_NOFOLLOW
3059
 
                                                | O_DIRECTORY
3060
 
                                                | O_PATH));
3061
 
    if(dir_fd == -1){
3062
 
      perror_plus("open");
3063
 
    }
3064
 
    int numentries = scandirat(dir_fd, ".", &direntries,
3065
 
                               notdotentries, alphasort);
3066
 
    if(numentries >= 0){
3067
 
      for(int i = 0; i < numentries; i++){
3068
 
        if(debug){
3069
 
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
3070
 
                       dirname, direntries[i]->d_name);
3071
 
        }
3072
 
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
3073
 
        if(dret == -1){
3074
 
          if(errno == EISDIR){
3075
 
              dret = unlinkat(dir_fd, direntries[i]->d_name,
3076
 
                              AT_REMOVEDIR);
3077
 
          }         
3078
 
          if((dret == -1) and (errno == ENOTEMPTY)
3079
 
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
3080
 
                  == 0) and (level == 0)){
3081
 
            /* Recurse only in this special case */
3082
 
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
3083
 
            dret = 0;
3084
 
          }
3085
 
          if(dret == -1){
3086
 
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
3087
 
                         direntries[i]->d_name, strerror(errno));
3088
 
          }
3089
 
        }
3090
 
        free(direntries[i]);
3091
 
      }
3092
 
      
3093
 
      /* need to clean even if 0 because man page doesn't specify */
3094
 
      free(direntries);
3095
 
      if(numentries == -1){
3096
 
        perror_plus("scandirat");
3097
 
      }
3098
 
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
3099
 
      if(dret == -1 and errno != ENOENT){
3100
 
        perror_plus("rmdir");
3101
 
      }
3102
 
    } else {
3103
 
      perror_plus("scandirat");
3104
 
    }
3105
 
    close(dir_fd);
3106
 
  }
3107
 
  
3108
2733
  /* Removes the GPGME temp directory and all files inside */
3109
2734
  if(tempdir != NULL){
3110
 
    clean_dir_at(-1, tempdir, 0);
 
2735
    struct dirent **direntries = NULL;
 
2736
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY |
 
2737
                                                  O_NOFOLLOW));
 
2738
    if(tempdir_fd == -1){
 
2739
      perror_plus("open");
 
2740
    } else {
 
2741
#ifdef __GLIBC__
 
2742
#if __GLIBC_PREREQ(2, 15)
 
2743
      int numentries = scandirat(tempdir_fd, ".", &direntries,
 
2744
                                 notdotentries, alphasort);
 
2745
#else  /* not __GLIBC_PREREQ(2, 15) */
 
2746
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2747
                               alphasort);
 
2748
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
2749
#else   /* not __GLIBC__ */
 
2750
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2751
                               alphasort);
 
2752
#endif  /* not __GLIBC__ */
 
2753
      if(numentries >= 0){
 
2754
        for(int i = 0; i < numentries; i++){
 
2755
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
 
2756
          if(ret == -1){
 
2757
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
 
2758
                         " \"%s\", 0): %s\n", tempdir,
 
2759
                         direntries[i]->d_name, strerror(errno));
 
2760
          }
 
2761
          free(direntries[i]);
 
2762
        }
 
2763
        
 
2764
        /* need to clean even if 0 because man page doesn't specify */
 
2765
        free(direntries);
 
2766
        if(numentries == -1){
 
2767
          perror_plus("scandir");
 
2768
        }
 
2769
        ret = rmdir(tempdir);
 
2770
        if(ret == -1 and errno != ENOENT){
 
2771
          perror_plus("rmdir");
 
2772
        }
 
2773
      }
 
2774
      TEMP_FAILURE_RETRY(close(tempdir_fd));
 
2775
    }
3111
2776
  }
3112
2777
  
3113
2778
  if(quit_now){