/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

  • Committer: Teddy Hogeborn
  • Date: 2015-05-23 20:18:34 UTC
  • mto: (237.7.304 trunk)
  • mto: This revision was merged to the branch mainline in revision 325.
  • 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-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-2014 Teddy Hogeborn
 
13
 * Copyright © 2008-2014 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
    }
519
513
  fprintf_plus(stderr, "GnuTLS: %s", string);
520
514
}
521
515
 
522
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
 
516
__attribute__((nonnull, warn_unused_result))
523
517
static int init_gnutls_global(const char *pubkeyfilename,
524
518
                              const char *seckeyfilename,
525
 
                              const char *dhparamsfilename,
526
519
                              mandos_context *mc){
527
520
  int ret;
528
521
  unsigned int uret;
531
524
    fprintf_plus(stderr, "Initializing GnuTLS\n");
532
525
  }
533
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
  
534
534
  if(debug){
535
535
    /* "Use a log level over 10 to enable all debugging options."
536
536
     * - GnuTLS manual
544
544
  if(ret != GNUTLS_E_SUCCESS){
545
545
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
546
546
                 safer_gnutls_strerror(ret));
 
547
    gnutls_global_deinit();
547
548
    return -1;
548
549
  }
549
550
  
574
575
                 safer_gnutls_strerror(ret));
575
576
    goto globalfail;
576
577
  }
577
 
  /* If a Diffie-Hellman parameters file was given, try to use it */
578
 
  if(dhparamsfilename != NULL){
579
 
    gnutls_datum_t params = { .data = NULL, .size = 0 };
580
 
    do {
581
 
      int dhpfile = open(dhparamsfilename, O_RDONLY);
582
 
      if(dhpfile == -1){
583
 
        perror_plus("open");
584
 
        dhparamsfilename = NULL;
585
 
        break;
586
 
      }
587
 
      size_t params_capacity = 0;
 
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;
588
585
      while(true){
589
 
        params_capacity = incbuffer((char **)&params.data,
590
 
                                    (size_t)params.size,
591
 
                                    (size_t)params_capacity);
592
 
        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){
593
590
          perror_plus("incbuffer");
594
 
          free(params.data);
595
 
          params.data = NULL;
596
 
          dhparamsfilename = NULL;
 
591
          free(buffer.data);
 
592
          buffer.data = NULL;
597
593
          break;
598
594
        }
599
 
        ssize_t bytes_read = read(dhpfile,
600
 
                                  params.data + params.size,
 
595
        ssize_t bytes_read = read(secfile, buffer.data + buffer.size,
601
596
                                  BUFFER_SIZE);
602
597
        /* EOF */
603
598
        if(bytes_read == 0){
606
601
        /* check bytes_read for failure */
607
602
        if(bytes_read < 0){
608
603
          perror_plus("read");
609
 
          free(params.data);
610
 
          params.data = NULL;
611
 
          dhparamsfilename = NULL;
612
 
          break;
613
 
        }
614
 
        params.size += (unsigned int)bytes_read;
615
 
      }
616
 
      close(dhpfile);
617
 
      if(params.data == NULL){
618
 
        dhparamsfilename = NULL;
619
 
      }
620
 
      if(dhparamsfilename == NULL){
621
 
        break;
622
 
      }
623
 
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
624
 
                                          GNUTLS_X509_FMT_PEM);
625
 
      if(ret != GNUTLS_E_SUCCESS){
626
 
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
627
 
                     " \"%s\": %s\n", dhparamsfilename,
628
 
                     safer_gnutls_strerror(ret));
629
 
        dhparamsfilename = NULL;
630
 
      }
631
 
      free(params.data);
632
 
    } while(false);
633
 
  }
634
 
  if(dhparamsfilename == NULL){
635
 
    if(mc->dh_bits == 0){
636
 
      /* Find out the optimal number of DH bits */
637
 
      /* Try to read the private key file */
638
 
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
639
 
      do {
640
 
        int secfile = open(seckeyfilename, O_RDONLY);
641
 
        if(secfile == -1){
642
 
          perror_plus("open");
643
 
          break;
644
 
        }
645
 
        size_t buffer_capacity = 0;
646
 
        while(true){
647
 
          buffer_capacity = incbuffer((char **)&buffer.data,
648
 
                                      (size_t)buffer.size,
649
 
                                      (size_t)buffer_capacity);
650
 
          if(buffer_capacity == 0){
651
 
            perror_plus("incbuffer");
652
 
            free(buffer.data);
653
 
            buffer.data = NULL;
654
 
            break;
655
 
          }
656
 
          ssize_t bytes_read = read(secfile,
657
 
                                    buffer.data + buffer.size,
658
 
                                    BUFFER_SIZE);
659
 
          /* EOF */
660
 
          if(bytes_read == 0){
661
 
            break;
662
 
          }
663
 
          /* check bytes_read for failure */
664
 
          if(bytes_read < 0){
665
 
            perror_plus("read");
666
 
            free(buffer.data);
667
 
            buffer.data = NULL;
668
 
            break;
669
 
          }
670
 
          buffer.size += (unsigned int)bytes_read;
671
 
        }
672
 
        close(secfile);
673
 
      } while(false);
674
 
      /* If successful, use buffer to parse private key */
675
 
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
676
 
      if(buffer.data != NULL){
677
 
        {
678
 
          gnutls_openpgp_privkey_t privkey = NULL;
679
 
          ret = gnutls_openpgp_privkey_init(&privkey);
 
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);
680
627
          if(ret != GNUTLS_E_SUCCESS){
681
 
            fprintf_plus(stderr, "Error initializing OpenPGP key"
682
 
                         " structure: %s",
 
628
            fprintf_plus(stderr, "Error importing OpenPGP key : %s",
683
629
                         safer_gnutls_strerror(ret));
684
 
            free(buffer.data);
685
 
            buffer.data = NULL;
686
 
          } else {
687
 
            ret = gnutls_openpgp_privkey_import
688
 
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
689
 
            if(ret != GNUTLS_E_SUCCESS){
690
 
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
691
 
                           safer_gnutls_strerror(ret));
692
 
              privkey = NULL;
693
 
            }
694
 
            free(buffer.data);
695
 
            buffer.data = NULL;
696
 
            if(privkey != NULL){
697
 
              /* Use private key to suggest an appropriate
698
 
                 sec_param */
699
 
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
700
 
              gnutls_openpgp_privkey_deinit(privkey);
701
 
              if(debug){
702
 
                fprintf_plus(stderr, "This OpenPGP key implies using"
703
 
                             " a GnuTLS security parameter \"%s\".\n",
704
 
                             safe_string(gnutls_sec_param_get_name
705
 
                                         (sec_param)));
706
 
              }
707
 
            }
 
630
            privkey = NULL;
708
631
          }
709
 
        }
710
 
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
711
 
          /* Err on the side of caution */
712
 
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
713
 
          if(debug){
714
 
            fprintf_plus(stderr, "Falling back to security parameter"
715
 
                         " \"%s\"\n",
716
 
                         safe_string(gnutls_sec_param_get_name
717
 
                                     (sec_param)));
 
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
            }
718
644
          }
719
645
        }
720
646
      }
721
 
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
722
 
      if(uret != 0){
723
 
        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;
724
650
        if(debug){
725
 
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
726
 
                       " implies %u DH bits; using that.\n",
 
651
          fprintf_plus(stderr, "Falling back to security parameter"
 
652
                       " \"%s\"\n",
727
653
                       safe_string(gnutls_sec_param_get_name
728
 
                                   (sec_param)),
729
 
                       mc->dh_bits);
 
654
                                   (sec_param)));
730
655
        }
731
 
      } else {
732
 
        fprintf_plus(stderr, "Failed to get implied number of DH"
733
 
                     " 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",
734
664
                     safe_string(gnutls_sec_param_get_name
735
665
                                 (sec_param)),
736
 
                     safer_gnutls_strerror(ret));
737
 
        goto globalfail;
 
666
                     mc->dh_bits);
738
667
      }
739
 
    } else if(debug){
740
 
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
741
 
                   mc->dh_bits);
742
 
    }
743
 
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
744
 
    if(ret != GNUTLS_E_SUCCESS){
745
 
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
746
 
                   " bits): %s\n", mc->dh_bits,
 
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)),
747
672
                   safer_gnutls_strerror(ret));
748
673
      goto globalfail;
749
674
    }
750
 
  }
 
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
  
751
686
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
752
687
  
753
688
  return 0;
755
690
 globalfail:
756
691
  
757
692
  gnutls_certificate_free_credentials(mc->cred);
 
693
  gnutls_global_deinit();
758
694
  gnutls_dh_params_deinit(mc->dh_params);
759
695
  return -1;
760
696
}
812
748
  /* ignore client certificate if any. */
813
749
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
814
750
  
 
751
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
752
  
815
753
  return 0;
816
754
}
817
755
 
819
757
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
820
758
                      __attribute__((unused)) const char *txt){}
821
759
 
822
 
/* Set effective uid to 0, return errno */
823
 
__attribute__((warn_unused_result))
824
 
int raise_privileges(void){
825
 
  int old_errno = errno;
826
 
  int ret = 0;
827
 
  if(seteuid(0) == -1){
828
 
    ret = errno;
829
 
  }
830
 
  errno = old_errno;
831
 
  return ret;
832
 
}
833
 
 
834
 
/* Set effective and real user ID to 0.  Return errno. */
835
 
__attribute__((warn_unused_result))
836
 
int raise_privileges_permanently(void){
837
 
  int old_errno = errno;
838
 
  int ret = raise_privileges();
839
 
  if(ret != 0){
840
 
    errno = old_errno;
841
 
    return ret;
842
 
  }
843
 
  if(setuid(0) == -1){
844
 
    ret = errno;
845
 
  }
846
 
  errno = old_errno;
847
 
  return ret;
848
 
}
849
 
 
850
 
/* Set effective user ID to unprivileged saved user ID */
851
 
__attribute__((warn_unused_result))
852
 
int lower_privileges(void){
853
 
  int old_errno = errno;
854
 
  int ret = 0;
855
 
  if(seteuid(uid) == -1){
856
 
    ret = errno;
857
 
  }
858
 
  errno = old_errno;
859
 
  return ret;
860
 
}
861
 
 
862
 
/* Lower privileges permanently */
863
 
__attribute__((warn_unused_result))
864
 
int lower_privileges_permanently(void){
865
 
  int old_errno = errno;
866
 
  int ret = 0;
867
 
  if(setuid(uid) == -1){
868
 
    ret = errno;
869
 
  }
870
 
  errno = old_errno;
871
 
  return ret;
872
 
}
873
 
 
874
 
/* Helper function to add_local_route() and delete_local_route() */
875
 
__attribute__((nonnull, warn_unused_result))
876
 
static bool add_delete_local_route(const bool add,
877
 
                                   const char *address,
878
 
                                   AvahiIfIndex if_index){
879
 
  int ret;
880
 
  char helper[] = "mandos-client-iprouteadddel";
881
 
  char add_arg[] = "add";
882
 
  char delete_arg[] = "delete";
883
 
  char debug_flag[] = "--debug";
884
 
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
885
 
  if(pluginhelperdir == NULL){
886
 
    if(debug){
887
 
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
888
 
                   " variable not set; cannot run helper\n");
889
 
    }
890
 
    return false;
891
 
  }
892
 
  
893
 
  char interface[IF_NAMESIZE];
894
 
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
895
 
    perror_plus("if_indextoname");
896
 
    return false;
897
 
  }
898
 
  
899
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
900
 
  if(devnull == -1){
901
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
902
 
    return false;
903
 
  }
904
 
  pid_t pid = fork();
905
 
  if(pid == 0){
906
 
    /* Child */
907
 
    /* Raise privileges */
908
 
    errno = raise_privileges_permanently();
909
 
    if(errno != 0){
910
 
      perror_plus("Failed to raise privileges");
911
 
      /* _exit(EX_NOPERM); */
912
 
    } else {
913
 
      /* Set group */
914
 
      errno = 0;
915
 
      ret = setgid(0);
916
 
      if(ret == -1){
917
 
        perror_plus("setgid");
918
 
        _exit(EX_NOPERM);
919
 
      }
920
 
      /* Reset supplementary groups */
921
 
      errno = 0;
922
 
      ret = setgroups(0, NULL);
923
 
      if(ret == -1){
924
 
        perror_plus("setgroups");
925
 
        _exit(EX_NOPERM);
926
 
      }
927
 
    }
928
 
    ret = dup2(devnull, STDIN_FILENO);
929
 
    if(ret == -1){
930
 
      perror_plus("dup2(devnull, STDIN_FILENO)");
931
 
      _exit(EX_OSERR);
932
 
    }
933
 
    ret = close(devnull);
934
 
    if(ret == -1){
935
 
      perror_plus("close");
936
 
      _exit(EX_OSERR);
937
 
    }
938
 
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
939
 
    if(ret == -1){
940
 
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
941
 
      _exit(EX_OSERR);
942
 
    }
943
 
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
944
 
                                                    O_RDONLY
945
 
                                                    | O_DIRECTORY
946
 
                                                    | O_PATH
947
 
                                                    | O_CLOEXEC));
948
 
    if(helperdir_fd == -1){
949
 
      perror_plus("open");
950
 
      _exit(EX_UNAVAILABLE);
951
 
    }
952
 
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
953
 
                                                   helper, O_RDONLY));
954
 
    if(helper_fd == -1){
955
 
      perror_plus("openat");
956
 
      close(helperdir_fd);
957
 
      _exit(EX_UNAVAILABLE);
958
 
    }
959
 
    close(helperdir_fd);
960
 
#ifdef __GNUC__
961
 
#pragma GCC diagnostic push
962
 
#pragma GCC diagnostic ignored "-Wcast-qual"
963
 
#endif
964
 
    if(fexecve(helper_fd, (char *const [])
965
 
               { helper, add ? add_arg : delete_arg, (char *)address,
966
 
                   interface, debug ? debug_flag : NULL, NULL },
967
 
               environ) == -1){
968
 
#ifdef __GNUC__
969
 
#pragma GCC diagnostic pop
970
 
#endif
971
 
      perror_plus("fexecve");
972
 
      _exit(EXIT_FAILURE);
973
 
    }
974
 
  }
975
 
  if(pid == -1){
976
 
    perror_plus("fork");
977
 
    return false;
978
 
  }
979
 
  int status;
980
 
  pid_t pret = -1;
981
 
  errno = 0;
982
 
  do {
983
 
    pret = waitpid(pid, &status, 0);
984
 
    if(pret == -1 and errno == EINTR and quit_now){
985
 
      int errno_raising = 0;
986
 
      if((errno = raise_privileges()) != 0){
987
 
        errno_raising = errno;
988
 
        perror_plus("Failed to raise privileges in order to"
989
 
                    " kill helper program");
990
 
      }
991
 
      if(kill(pid, SIGTERM) == -1){
992
 
        perror_plus("kill");
993
 
      }
994
 
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
995
 
        perror_plus("Failed to lower privileges after killing"
996
 
                    " helper program");
997
 
      }
998
 
      return false;
999
 
    }
1000
 
  } while(pret == -1 and errno == EINTR);
1001
 
  if(pret == -1){
1002
 
    perror_plus("waitpid");
1003
 
    return false;
1004
 
  }
1005
 
  if(WIFEXITED(status)){
1006
 
    if(WEXITSTATUS(status) != 0){
1007
 
      fprintf_plus(stderr, "Error: iprouteadddel exited"
1008
 
                   " with status %d\n", WEXITSTATUS(status));
1009
 
      return false;
1010
 
    }
1011
 
    return true;
1012
 
  }
1013
 
  if(WIFSIGNALED(status)){
1014
 
    fprintf_plus(stderr, "Error: iprouteadddel died by"
1015
 
                 " signal %d\n", WTERMSIG(status));
1016
 
    return false;
1017
 
  }
1018
 
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
1019
 
  return false;
1020
 
}
1021
 
 
1022
 
__attribute__((nonnull, warn_unused_result))
1023
 
static bool add_local_route(const char *address,
1024
 
                            AvahiIfIndex if_index){
1025
 
  if(debug){
1026
 
    fprintf_plus(stderr, "Adding route to %s\n", address);
1027
 
  }
1028
 
  return add_delete_local_route(true, address, if_index);
1029
 
}
1030
 
 
1031
 
__attribute__((nonnull, warn_unused_result))
1032
 
static bool delete_local_route(const char *address,
1033
 
                               AvahiIfIndex if_index){
1034
 
  if(debug){
1035
 
    fprintf_plus(stderr, "Removing route to %s\n", address);
1036
 
  }
1037
 
  return add_delete_local_route(false, address, if_index);
1038
 
}
1039
 
 
1040
760
/* Called when a Mandos server is found */
1041
761
__attribute__((nonnull, warn_unused_result))
1042
762
static int start_mandos_communication(const char *ip, in_port_t port,
1053
773
  int retval = -1;
1054
774
  gnutls_session_t session;
1055
775
  int pf;                       /* Protocol family */
1056
 
  bool route_added = false;
1057
776
  
1058
777
  errno = 0;
1059
778
  
1081
800
    bool match = false;
1082
801
    {
1083
802
      char *interface = NULL;
1084
 
      while((interface = argz_next(mc->interfaces,
1085
 
                                   mc->interfaces_size,
1086
 
                                   interface))){
 
803
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
804
                                 interface))){
1087
805
        if(if_nametoindex(interface) == (unsigned int)if_index){
1088
806
          match = true;
1089
807
          break;
1118
836
                 PRIuMAX "\n", ip, (uintmax_t)port);
1119
837
  }
1120
838
  
1121
 
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
 
839
  tcp_sd = socket(pf, SOCK_STREAM, 0);
1122
840
  if(tcp_sd < 0){
1123
841
    int e = errno;
1124
842
    perror_plus("socket");
1131
849
    goto mandos_end;
1132
850
  }
1133
851
  
 
852
  memset(&to, 0, sizeof(to));
1134
853
  if(af == AF_INET6){
1135
 
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
1136
 
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
1137
 
    ret = inet_pton(af, ip, &to6->sin6_addr);
 
854
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
855
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
1138
856
  } else {                      /* IPv4 */
1139
 
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
1140
 
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
1141
 
    ret = inet_pton(af, ip, &to4->sin_addr);
 
857
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
858
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
1142
859
  }
1143
860
  if(ret < 0 ){
1144
861
    int e = errno;
1214
931
    goto mandos_end;
1215
932
  }
1216
933
  
1217
 
  while(true){
1218
 
    if(af == AF_INET6){
1219
 
      ret = connect(tcp_sd, (struct sockaddr *)&to,
1220
 
                    sizeof(struct sockaddr_in6));
1221
 
    } else {
1222
 
      ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
1223
 
                    sizeof(struct sockaddr_in));
1224
 
    }
1225
 
    if(ret < 0){
1226
 
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
1227
 
         and if_index != AVAHI_IF_UNSPEC
1228
 
         and connect_to == NULL
1229
 
         and not route_added and
1230
 
         ((af == AF_INET6 and not
1231
 
           IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
1232
 
                                    &to)->sin6_addr)))
1233
 
          or (af == AF_INET and
1234
 
              /* Not a a IPv4LL address */
1235
 
              (ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
1236
 
               & 0xFFFF0000L) != 0xA9FE0000L))){
1237
 
        /* Work around Avahi bug - Avahi does not announce link-local
1238
 
           addresses if it has a global address, so local hosts with
1239
 
           *only* a link-local address (e.g. Mandos clients) cannot
1240
 
           connect to a Mandos server announced by Avahi on a server
1241
 
           host with a global address.  Work around this by retrying
1242
 
           with an explicit route added with the server's address.
1243
 
           
1244
 
           Avahi bug reference:
1245
 
           https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1246
 
           https://bugs.debian.org/587961
1247
 
        */
1248
 
        if(debug){
1249
 
          fprintf_plus(stderr, "Mandos server unreachable, trying"
1250
 
                       " direct route\n");
1251
 
        }
1252
 
        int e = errno;
1253
 
        route_added = add_local_route(ip, if_index);
1254
 
        if(route_added){
1255
 
          continue;
1256
 
        }
1257
 
        errno = e;
1258
 
      }
1259
 
      if(errno != ECONNREFUSED or debug){
1260
 
        int e = errno;
1261
 
        perror_plus("connect");
1262
 
        errno = e;
1263
 
      }
1264
 
      goto mandos_end;
1265
 
    }
1266
 
    
1267
 
    if(quit_now){
1268
 
      errno = EINTR;
1269
 
      goto mandos_end;
1270
 
    }
1271
 
    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;
1272
953
  }
1273
954
  
1274
955
  const char *out = mandos_protocol_version;
1428
1109
                                               &decrypted_buffer, mc);
1429
1110
    if(decrypted_buffer_size >= 0){
1430
1111
      
1431
 
      clearerr(stdout);
1432
1112
      written = 0;
1433
1113
      while(written < (size_t) decrypted_buffer_size){
1434
1114
        if(quit_now){
1450
1130
        }
1451
1131
        written += (size_t)ret;
1452
1132
      }
1453
 
      ret = fflush(stdout);
1454
 
      if(ret != 0){
1455
 
        int e = errno;
1456
 
        if(debug){
1457
 
          fprintf_plus(stderr, "Error writing encrypted data: %s\n",
1458
 
                       strerror(errno));
1459
 
        }
1460
 
        errno = e;
1461
 
        goto mandos_end;
1462
 
      }
1463
1133
      retval = 0;
1464
1134
    }
1465
1135
  }
1468
1138
  
1469
1139
 mandos_end:
1470
1140
  {
1471
 
    if(route_added){
1472
 
      if(not delete_local_route(ip, if_index)){
1473
 
        fprintf_plus(stderr, "Failed to delete local route to %s on"
1474
 
                     " interface %d", ip, if_index);
1475
 
      }
1476
 
    }
1477
1141
    int e = errno;
1478
1142
    free(decrypted_buffer);
1479
1143
    free(buffer);
1480
1144
    if(tcp_sd >= 0){
1481
 
      ret = close(tcp_sd);
 
1145
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1482
1146
    }
1483
1147
    if(ret == -1){
1484
1148
      if(e == 0){
1496
1160
  return retval;
1497
1161
}
1498
1162
 
 
1163
__attribute__((nonnull))
1499
1164
static void resolve_callback(AvahiSServiceResolver *r,
1500
1165
                             AvahiIfIndex interface,
1501
1166
                             AvahiProtocol proto,
1638
1303
__attribute__((nonnull, warn_unused_result))
1639
1304
bool get_flags(const char *ifname, struct ifreq *ifr){
1640
1305
  int ret;
1641
 
  int old_errno;
 
1306
  error_t ret_errno;
1642
1307
  
1643
1308
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1644
1309
  if(s < 0){
1645
 
    old_errno = errno;
 
1310
    ret_errno = errno;
1646
1311
    perror_plus("socket");
1647
 
    errno = old_errno;
 
1312
    errno = ret_errno;
1648
1313
    return false;
1649
1314
  }
1650
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1651
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
 
1315
  strcpy(ifr->ifr_name, ifname);
1652
1316
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1653
1317
  if(ret == -1){
1654
1318
    if(debug){
1655
 
      old_errno = errno;
 
1319
      ret_errno = errno;
1656
1320
      perror_plus("ioctl SIOCGIFFLAGS");
1657
 
      errno = old_errno;
 
1321
      errno = ret_errno;
1658
1322
    }
1659
 
    close(s);
1660
1323
    return false;
1661
1324
  }
1662
 
  close(s);
1663
1325
  return true;
1664
1326
}
1665
1327
 
1907
1569
  }
1908
1570
}
1909
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
 
1910
1624
__attribute__((nonnull))
1911
1625
void run_network_hooks(const char *mode, const char *interface,
1912
1626
                       const float delay){
1913
1627
  struct dirent **direntries = NULL;
1914
1628
  if(hookdir_fd == -1){
1915
 
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
1916
 
                      | O_CLOEXEC);
 
1629
    hookdir_fd = open(hookdir, O_RDONLY);
1917
1630
    if(hookdir_fd == -1){
1918
1631
      if(errno == ENOENT){
1919
1632
        if(debug){
1926
1639
      return;
1927
1640
    }
1928
1641
  }
1929
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
1930
 
  if(devnull == -1){
1931
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
1932
 
    return;
1933
 
  }
 
1642
#ifdef __GLIBC__
 
1643
#if __GLIBC_PREREQ(2, 15)
1934
1644
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1935
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__ */
1936
1654
  if(numhooks == -1){
1937
1655
    perror_plus("scandir");
1938
 
    close(devnull);
1939
1656
    return;
1940
1657
  }
1941
1658
  struct dirent *direntry;
1942
1659
  int ret;
 
1660
  int devnull = open("/dev/null", O_RDONLY);
1943
1661
  for(int i = 0; i < numhooks; i++){
1944
1662
    direntry = direntries[i];
1945
1663
    if(debug){
1969
1687
        perror_plus("setgroups");
1970
1688
        _exit(EX_NOPERM);
1971
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
      }
1972
1705
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1973
1706
      if(ret == -1){
1974
1707
        perror_plus("setenv");
2009
1742
          _exit(EX_OSERR);
2010
1743
        }
2011
1744
      }
2012
 
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
2013
 
                                                   direntry->d_name,
2014
 
                                                   O_RDONLY));
 
1745
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
2015
1746
      if(hook_fd == -1){
2016
1747
        perror_plus("openat");
2017
1748
        _exit(EXIT_FAILURE);
2018
1749
      }
2019
 
      if(close(hookdir_fd) == -1){
 
1750
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2020
1751
        perror_plus("close");
2021
1752
        _exit(EXIT_FAILURE);
2022
1753
      }
2023
 
      ret = dup2(devnull, STDIN_FILENO);
2024
 
      if(ret == -1){
2025
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
2026
 
        _exit(EX_OSERR);
2027
 
      }
2028
 
      ret = close(devnull);
2029
 
      if(ret == -1){
2030
 
        perror_plus("close");
2031
 
        _exit(EX_OSERR);
2032
 
      }
2033
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
2034
 
      if(ret == -1){
2035
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
2036
 
        _exit(EX_OSERR);
2037
 
      }
2038
1754
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
2039
1755
                 environ) == -1){
2040
1756
        perror_plus("fexecve");
2080
1796
    free(direntry);
2081
1797
  }
2082
1798
  free(direntries);
2083
 
  if(close(hookdir_fd) == -1){
 
1799
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2084
1800
    perror_plus("close");
2085
1801
  } else {
2086
1802
    hookdir_fd = -1;
2089
1805
}
2090
1806
 
2091
1807
__attribute__((nonnull, warn_unused_result))
2092
 
int bring_up_interface(const char *const interface,
2093
 
                       const float delay){
2094
 
  int old_errno = errno;
 
1808
error_t bring_up_interface(const char *const interface,
 
1809
                           const float delay){
 
1810
  error_t old_errno = errno;
2095
1811
  int ret;
2096
1812
  struct ifreq network;
2097
1813
  unsigned int if_index = if_nametoindex(interface);
2107
1823
  }
2108
1824
  
2109
1825
  if(not interface_is_up(interface)){
2110
 
    int ret_errno = 0;
2111
 
    int ioctl_errno = 0;
 
1826
    error_t ret_errno = 0, ioctl_errno = 0;
2112
1827
    if(not get_flags(interface, &network)){
2113
1828
      ret_errno = errno;
2114
1829
      fprintf_plus(stderr, "Failed to get flags for interface "
2127
1842
    }
2128
1843
    
2129
1844
    if(quit_now){
2130
 
      ret = close(sd);
 
1845
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2131
1846
      if(ret == -1){
2132
1847
        perror_plus("close");
2133
1848
      }
2183
1898
    }
2184
1899
    
2185
1900
    /* Close the socket */
2186
 
    ret = close(sd);
 
1901
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
2187
1902
    if(ret == -1){
2188
1903
      perror_plus("close");
2189
1904
    }
2201
1916
  
2202
1917
  /* Sleep checking until interface is running.
2203
1918
     Check every 0.25s, up to total time of delay */
2204
 
  for(int i = 0; i < delay * 4; i++){
 
1919
  for(int i=0; i < delay * 4; i++){
2205
1920
    if(interface_is_running(interface)){
2206
1921
      break;
2207
1922
    }
2217
1932
}
2218
1933
 
2219
1934
__attribute__((nonnull, warn_unused_result))
2220
 
int take_down_interface(const char *const interface){
2221
 
  int old_errno = errno;
 
1935
error_t take_down_interface(const char *const interface){
 
1936
  error_t old_errno = errno;
2222
1937
  struct ifreq network;
2223
1938
  unsigned int if_index = if_nametoindex(interface);
2224
1939
  if(if_index == 0){
2227
1942
    return ENXIO;
2228
1943
  }
2229
1944
  if(interface_is_up(interface)){
2230
 
    int ret_errno = 0;
2231
 
    int ioctl_errno = 0;
 
1945
    error_t ret_errno = 0, ioctl_errno = 0;
2232
1946
    if(not get_flags(interface, &network) and debug){
2233
1947
      ret_errno = errno;
2234
1948
      fprintf_plus(stderr, "Failed to get flags for interface "
2272
1986
    }
2273
1987
    
2274
1988
    /* Close the socket */
2275
 
    int ret = close(sd);
 
1989
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
2276
1990
    if(ret == -1){
2277
1991
      perror_plus("close");
2278
1992
    }
2294
2008
 
2295
2009
int main(int argc, char *argv[]){
2296
2010
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2297
 
                        .priority = "SECURE256:!CTYPE-X.509"
2298
 
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
2299
 
                        .current_server = NULL, .interfaces = NULL,
2300
 
                        .interfaces_size = 0 };
 
2011
                        .priority = "SECURE256:!CTYPE-X.509:"
 
2012
                        "+CTYPE-OPENPGP:!RSA", .current_server = NULL,
 
2013
                        .interfaces = NULL, .interfaces_size = 0 };
2301
2014
  AvahiSServiceBrowser *sb = NULL;
2302
2015
  error_t ret_errno;
2303
2016
  int ret;
2312
2025
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2313
2026
  const char *seckey = PATHDIR "/" SECKEY;
2314
2027
  const char *pubkey = PATHDIR "/" PUBKEY;
2315
 
  const char *dh_params_file = NULL;
2316
2028
  char *interfaces_hooks = NULL;
2317
2029
  
2318
2030
  bool gnutls_initialized = false;
2371
2083
        .doc = "Bit length of the prime number used in the"
2372
2084
        " Diffie-Hellman key exchange",
2373
2085
        .group = 2 },
2374
 
      { .name = "dh-params", .key = 134,
2375
 
        .arg = "FILE",
2376
 
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
2377
 
        " for the Diffie-Hellman key exchange",
2378
 
        .group = 2 },
2379
2086
      { .name = "priority", .key = 130,
2380
2087
        .arg = "STRING",
2381
2088
        .doc = "GnuTLS priority string for the TLS handshake",
2436
2143
        }
2437
2144
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2438
2145
        break;
2439
 
      case 134:                 /* --dh-params */
2440
 
        dh_params_file = arg;
2441
 
        break;
2442
2146
      case 130:                 /* --priority */
2443
2147
        mc.priority = arg;
2444
2148
        break;
2484
2188
                         .args_doc = "",
2485
2189
                         .doc = "Mandos client -- Get and decrypt"
2486
2190
                         " passwords from a Mandos server" };
2487
 
    ret_errno = argp_parse(&argp, argc, argv,
2488
 
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2489
 
    switch(ret_errno){
 
2191
    ret = argp_parse(&argp, argc, argv,
 
2192
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2193
    switch(ret){
2490
2194
    case 0:
2491
2195
      break;
2492
2196
    case ENOMEM:
2493
2197
    default:
2494
 
      errno = ret_errno;
 
2198
      errno = ret;
2495
2199
      perror_plus("argp_parse");
2496
2200
      exitcode = EX_OSERR;
2497
2201
      goto end;
2500
2204
      goto end;
2501
2205
    }
2502
2206
  }
2503
 
  
 
2207
    
2504
2208
  {
2505
2209
    /* Work around Debian bug #633582:
2506
 
       <https://bugs.debian.org/633582> */
 
2210
       <http://bugs.debian.org/633582> */
2507
2211
    
2508
2212
    /* Re-raise privileges */
2509
 
    ret = raise_privileges();
2510
 
    if(ret != 0){
2511
 
      errno = ret;
 
2213
    ret_errno = raise_privileges();
 
2214
    if(ret_errno != 0){
 
2215
      errno = ret_errno;
2512
2216
      perror_plus("Failed to raise privileges");
2513
2217
    } else {
2514
2218
      struct stat st;
2530
2234
              }
2531
2235
            }
2532
2236
          }
2533
 
          close(seckey_fd);
 
2237
          TEMP_FAILURE_RETRY(close(seckey_fd));
2534
2238
        }
2535
2239
      }
2536
 
      
 
2240
    
2537
2241
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2538
2242
        int pubkey_fd = open(pubkey, O_RDONLY);
2539
2243
        if(pubkey_fd == -1){
2551
2255
              }
2552
2256
            }
2553
2257
          }
2554
 
          close(pubkey_fd);
2555
 
        }
2556
 
      }
2557
 
      
2558
 
      if(dh_params_file != NULL
2559
 
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
2560
 
        int dhparams_fd = open(dh_params_file, O_RDONLY);
2561
 
        if(dhparams_fd == -1){
2562
 
          perror_plus("open");
2563
 
        } else {
2564
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
2565
 
          if(ret == -1){
2566
 
            perror_plus("fstat");
2567
 
          } else {
2568
 
            if(S_ISREG(st.st_mode)
2569
 
               and st.st_uid == 0 and st.st_gid == 0){
2570
 
              ret = fchown(dhparams_fd, uid, gid);
2571
 
              if(ret == -1){
2572
 
                perror_plus("fchown");
2573
 
              }
2574
 
            }
2575
 
          }
2576
 
          close(dhparams_fd);
2577
 
        }
2578
 
      }
2579
 
      
 
2258
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2259
        }
 
2260
      }
 
2261
    
2580
2262
      /* Lower privileges */
2581
 
      ret = lower_privileges();
2582
 
      if(ret != 0){
2583
 
        errno = ret;
 
2263
      ret_errno = lower_privileges();
 
2264
      if(ret_errno != 0){
 
2265
        errno = ret_errno;
2584
2266
        perror_plus("Failed to lower privileges");
2585
2267
      }
2586
2268
    }
2756
2438
      errno = bring_up_interface(interface, delay);
2757
2439
      if(not interface_was_up){
2758
2440
        if(errno != 0){
2759
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2760
 
                       " %s\n", interface, strerror(errno));
 
2441
          perror_plus("Failed to bring up interface");
2761
2442
        } else {
2762
2443
          errno = argz_add(&interfaces_to_take_down,
2763
2444
                           &interfaces_to_take_down_size,
2786
2467
    goto end;
2787
2468
  }
2788
2469
  
2789
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
2470
  ret = init_gnutls_global(pubkey, seckey, &mc);
2790
2471
  if(ret == -1){
2791
2472
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2792
2473
    exitcode = EX_UNAVAILABLE;
2914
2595
    
2915
2596
    /* Allocate a new server */
2916
2597
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2917
 
                                 &config, NULL, NULL, &ret);
 
2598
                                 &config, NULL, NULL, &ret_errno);
2918
2599
    
2919
2600
    /* Free the Avahi configuration data */
2920
2601
    avahi_server_config_free(&config);
2923
2604
  /* Check if creating the Avahi server object succeeded */
2924
2605
  if(mc.server == NULL){
2925
2606
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2926
 
                 avahi_strerror(ret));
 
2607
                 avahi_strerror(ret_errno));
2927
2608
    exitcode = EX_UNAVAILABLE;
2928
2609
    goto end;
2929
2610
  }
2964
2645
 end:
2965
2646
  
2966
2647
  if(debug){
2967
 
    if(signal_received){
2968
 
      fprintf_plus(stderr, "%s exiting due to signal %d: %s\n",
2969
 
                   argv[0], signal_received,
2970
 
                   strsignal(signal_received));
2971
 
    } else {
2972
 
      fprintf_plus(stderr, "%s exiting\n", argv[0]);
2973
 
    }
 
2648
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2974
2649
  }
2975
2650
  
2976
2651
  /* Cleanup things */
2987
2662
  
2988
2663
  if(gnutls_initialized){
2989
2664
    gnutls_certificate_free_credentials(mc.cred);
 
2665
    gnutls_global_deinit();
2990
2666
    gnutls_dh_params_deinit(mc.dh_params);
2991
2667
  }
2992
2668
  
3015
2691
  
3016
2692
  /* Re-raise privileges */
3017
2693
  {
3018
 
    ret = raise_privileges();
3019
 
    if(ret != 0){
3020
 
      errno = ret;
 
2694
    ret_errno = raise_privileges();
 
2695
    if(ret_errno != 0){
 
2696
      errno = ret_errno;
3021
2697
      perror_plus("Failed to raise privileges");
3022
2698
    } else {
3023
2699
      
3028
2704
      /* Take down the network interfaces which were brought up */
3029
2705
      {
3030
2706
        char *interface = NULL;
3031
 
        while((interface = argz_next(interfaces_to_take_down,
3032
 
                                     interfaces_to_take_down_size,
3033
 
                                     interface))){
3034
 
          ret = take_down_interface(interface);
3035
 
          if(ret != 0){
3036
 
            errno = ret;
 
2707
        while((interface=argz_next(interfaces_to_take_down,
 
2708
                                   interfaces_to_take_down_size,
 
2709
                                   interface))){
 
2710
          ret_errno = take_down_interface(interface);
 
2711
          if(ret_errno != 0){
 
2712
            errno = ret_errno;
3037
2713
            perror_plus("Failed to take down interface");
3038
2714
          }
3039
2715
        }
3044
2720
      }
3045
2721
    }
3046
2722
    
3047
 
    ret = lower_privileges_permanently();
3048
 
    if(ret != 0){
3049
 
      errno = ret;
 
2723
    ret_errno = lower_privileges_permanently();
 
2724
    if(ret_errno != 0){
 
2725
      errno = ret_errno;
3050
2726
      perror_plus("Failed to lower privileges permanently");
3051
2727
    }
3052
2728
  }
3054
2730
  free(interfaces_to_take_down);
3055
2731
  free(interfaces_hooks);
3056
2732
  
3057
 
  void clean_dir_at(int base, const char * const dirname,
3058
 
                    uintmax_t level){
3059
 
    struct dirent **direntries = NULL;
3060
 
    int dret;
3061
 
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
3062
 
                                                O_RDONLY
3063
 
                                                | O_NOFOLLOW
3064
 
                                                | O_DIRECTORY
3065
 
                                                | O_PATH));
3066
 
    if(dir_fd == -1){
3067
 
      perror_plus("open");
3068
 
      return;
3069
 
    }
3070
 
    int numentries = scandirat(dir_fd, ".", &direntries,
3071
 
                               notdotentries, alphasort);
3072
 
    if(numentries >= 0){
3073
 
      for(int i = 0; i < numentries; i++){
3074
 
        if(debug){
3075
 
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
3076
 
                       dirname, direntries[i]->d_name);
3077
 
        }
3078
 
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
3079
 
        if(dret == -1){
3080
 
          if(errno == EISDIR){
3081
 
              dret = unlinkat(dir_fd, direntries[i]->d_name,
3082
 
                              AT_REMOVEDIR);
3083
 
          }         
3084
 
          if((dret == -1) and (errno == ENOTEMPTY)
3085
 
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
3086
 
                  == 0) and (level == 0)){
3087
 
            /* Recurse only in this special case */
3088
 
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
3089
 
            dret = 0;
3090
 
          }
3091
 
          if((dret == -1) and (errno != ENOENT)){
3092
 
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
3093
 
                         direntries[i]->d_name, strerror(errno));
3094
 
          }
3095
 
        }
3096
 
        free(direntries[i]);
3097
 
      }
3098
 
      
3099
 
      /* need to clean even if 0 because man page doesn't specify */
3100
 
      free(direntries);
3101
 
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
3102
 
      if(dret == -1 and errno != ENOENT){
3103
 
        perror_plus("rmdir");
3104
 
      }
3105
 
    } else {
3106
 
      perror_plus("scandirat");
3107
 
    }
3108
 
    close(dir_fd);
3109
 
  }
3110
 
  
3111
2733
  /* Removes the GPGME temp directory and all files inside */
3112
2734
  if(tempdir != NULL){
3113
 
    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
    }
3114
2776
  }
3115
2777
  
3116
2778
  if(quit_now){