/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: 2016-02-28 20:38:55 UTC
  • Revision ID: teddy@recompile.se-20160228203855-pkcunjkz804yep7r
Client: Remove new key directory introduced in GnuPG 2.1

* plugins.d/mandos-client.c (main/clean_dir_at): New function; calls
  itself for any known subdirectories which should also be removed.
  (main): Call clean_dir_at() to remove GPGME temp directory.

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-2014 Teddy Hogeborn
13
 
 * Copyright © 2008-2014 Björn Påhlsson
 
12
 * Copyright © 2008-2016 Teddy Hogeborn
 
13
 * Copyright © 2008-2016 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>             /* memset(), strcmp(), strlen(),
50
 
                                   strerror(), asprintf(), strcpy() */
 
49
#include <string.h>             /* strcmp(), strlen(), strerror(),
 
50
                                   asprintf(), strncpy() */
51
51
#include <sys/ioctl.h>          /* ioctl */
52
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
53
                                   sockaddr_in6, PF_INET6,
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect(),
59
59
                                   getnameinfo() */
60
 
#include <fcntl.h>              /* open(), unlinkat() */
 
60
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
61
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
62
                                 */
63
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
64
64
                                   strtoimax() */
65
 
#include <errno.h>              /* perror(), errno,
 
65
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
 
66
                                   EAI_SYSTEM, ENETUNREACH,
 
67
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
 
68
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
 
69
                                   ENOTEMPTY,
66
70
                                   program_invocation_short_name */
67
71
#include <time.h>               /* nanosleep(), time(), sleep() */
68
72
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
234
238
                          .af = af };
235
239
  if(new_server->ip == NULL){
236
240
    perror_plus("strdup");
 
241
    free(new_server);
237
242
    return false;
238
243
  }
239
244
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
240
245
  if(ret == -1){
241
246
    perror_plus("clock_gettime");
 
247
#ifdef __GNUC__
 
248
#pragma GCC diagnostic push
 
249
#pragma GCC diagnostic ignored "-Wcast-qual"
 
250
#endif
 
251
    free((char *)(new_server->ip));
 
252
#ifdef __GNUC__
 
253
#pragma GCC diagnostic pop
 
254
#endif
 
255
    free(new_server);
242
256
    return false;
243
257
  }
244
258
  /* Special case of first server */
295
309
      return false;
296
310
    }
297
311
    
298
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
 
312
    ret = close(fd);
299
313
    if(ret == -1){
300
314
      perror_plus("close");
301
315
    }
483
497
  return plaintext_length;
484
498
}
485
499
 
 
500
__attribute__((warn_unused_result, const))
 
501
static const char *safe_string(const char *str){
 
502
  if(str == NULL)
 
503
    return "(unknown)";
 
504
  return str;
 
505
}
 
506
 
486
507
__attribute__((warn_unused_result))
487
508
static const char *safer_gnutls_strerror(int value){
488
509
  const char *ret = gnutls_strerror(value);
489
 
  if(ret == NULL)
490
 
    ret = "(unknown)";
491
 
  return ret;
 
510
  return safe_string(ret);
492
511
}
493
512
 
494
513
/* GnuTLS log function callback */
498
517
  fprintf_plus(stderr, "GnuTLS: %s", string);
499
518
}
500
519
 
501
 
__attribute__((nonnull, warn_unused_result))
 
520
__attribute__((nonnull(1, 2, 4), warn_unused_result))
502
521
static int init_gnutls_global(const char *pubkeyfilename,
503
522
                              const char *seckeyfilename,
 
523
                              const char *dhparamsfilename,
504
524
                              mandos_context *mc){
505
525
  int ret;
 
526
  unsigned int uret;
506
527
  
507
528
  if(debug){
508
529
    fprintf_plus(stderr, "Initializing GnuTLS\n");
509
530
  }
510
531
  
511
 
  ret = gnutls_global_init();
512
 
  if(ret != GNUTLS_E_SUCCESS){
513
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
514
 
                 safer_gnutls_strerror(ret));
515
 
    return -1;
516
 
  }
517
 
  
518
532
  if(debug){
519
533
    /* "Use a log level over 10 to enable all debugging options."
520
534
     * - GnuTLS manual
528
542
  if(ret != GNUTLS_E_SUCCESS){
529
543
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
530
544
                 safer_gnutls_strerror(ret));
531
 
    gnutls_global_deinit();
532
545
    return -1;
533
546
  }
534
547
  
559
572
                 safer_gnutls_strerror(ret));
560
573
    goto globalfail;
561
574
  }
562
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
563
 
  if(ret != GNUTLS_E_SUCCESS){
564
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
565
 
                 safer_gnutls_strerror(ret));
566
 
    goto globalfail;
567
 
  }
568
 
  
 
575
  /* If a Diffie-Hellman parameters file was given, try to use it */
 
576
  if(dhparamsfilename != NULL){
 
577
    gnutls_datum_t params = { .data = NULL, .size = 0 };
 
578
    do {
 
579
      int dhpfile = open(dhparamsfilename, O_RDONLY);
 
580
      if(dhpfile == -1){
 
581
        perror_plus("open");
 
582
        dhparamsfilename = NULL;
 
583
        break;
 
584
      }
 
585
      size_t params_capacity = 0;
 
586
      while(true){
 
587
        params_capacity = incbuffer((char **)&params.data,
 
588
                                    (size_t)params.size,
 
589
                                    (size_t)params_capacity);
 
590
        if(params_capacity == 0){
 
591
          perror_plus("incbuffer");
 
592
          free(params.data);
 
593
          params.data = NULL;
 
594
          dhparamsfilename = NULL;
 
595
          break;
 
596
        }
 
597
        ssize_t bytes_read = read(dhpfile,
 
598
                                  params.data + params.size,
 
599
                                  BUFFER_SIZE);
 
600
        /* EOF */
 
601
        if(bytes_read == 0){
 
602
          break;
 
603
        }
 
604
        /* check bytes_read for failure */
 
605
        if(bytes_read < 0){
 
606
          perror_plus("read");
 
607
          free(params.data);
 
608
          params.data = NULL;
 
609
          dhparamsfilename = NULL;
 
610
          break;
 
611
        }
 
612
        params.size += (unsigned int)bytes_read;
 
613
      }
 
614
      if(params.data == NULL){
 
615
        dhparamsfilename = NULL;
 
616
      }
 
617
      if(dhparamsfilename == NULL){
 
618
        break;
 
619
      }
 
620
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
 
621
                                          GNUTLS_X509_FMT_PEM);
 
622
      if(ret != GNUTLS_E_SUCCESS){
 
623
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
 
624
                     " \"%s\": %s\n", dhparamsfilename,
 
625
                     safer_gnutls_strerror(ret));
 
626
        dhparamsfilename = NULL;
 
627
      }
 
628
    } while(false);
 
629
  }
 
630
  if(dhparamsfilename == NULL){
 
631
    if(mc->dh_bits == 0){
 
632
      /* Find out the optimal number of DH bits */
 
633
      /* Try to read the private key file */
 
634
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
 
635
      do {
 
636
        int secfile = open(seckeyfilename, O_RDONLY);
 
637
        if(secfile == -1){
 
638
          perror_plus("open");
 
639
          break;
 
640
        }
 
641
        size_t buffer_capacity = 0;
 
642
        while(true){
 
643
          buffer_capacity = incbuffer((char **)&buffer.data,
 
644
                                      (size_t)buffer.size,
 
645
                                      (size_t)buffer_capacity);
 
646
          if(buffer_capacity == 0){
 
647
            perror_plus("incbuffer");
 
648
            free(buffer.data);
 
649
            buffer.data = NULL;
 
650
            break;
 
651
          }
 
652
          ssize_t bytes_read = read(secfile,
 
653
                                    buffer.data + buffer.size,
 
654
                                    BUFFER_SIZE);
 
655
          /* EOF */
 
656
          if(bytes_read == 0){
 
657
            break;
 
658
          }
 
659
          /* check bytes_read for failure */
 
660
          if(bytes_read < 0){
 
661
            perror_plus("read");
 
662
            free(buffer.data);
 
663
            buffer.data = NULL;
 
664
            break;
 
665
          }
 
666
          buffer.size += (unsigned int)bytes_read;
 
667
        }
 
668
        close(secfile);
 
669
      } while(false);
 
670
      /* If successful, use buffer to parse private key */
 
671
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
672
      if(buffer.data != NULL){
 
673
        {
 
674
          gnutls_openpgp_privkey_t privkey = NULL;
 
675
          ret = gnutls_openpgp_privkey_init(&privkey);
 
676
          if(ret != GNUTLS_E_SUCCESS){
 
677
            fprintf_plus(stderr, "Error initializing OpenPGP key"
 
678
                         " structure: %s",
 
679
                         safer_gnutls_strerror(ret));
 
680
            free(buffer.data);
 
681
            buffer.data = NULL;
 
682
          } else {
 
683
            ret = gnutls_openpgp_privkey_import
 
684
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
 
685
            if(ret != GNUTLS_E_SUCCESS){
 
686
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
 
687
                           safer_gnutls_strerror(ret));
 
688
              privkey = NULL;
 
689
            }
 
690
            free(buffer.data);
 
691
            buffer.data = NULL;
 
692
            if(privkey != NULL){
 
693
              /* Use private key to suggest an appropriate
 
694
                 sec_param */
 
695
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
 
696
              gnutls_openpgp_privkey_deinit(privkey);
 
697
              if(debug){
 
698
                fprintf_plus(stderr, "This OpenPGP key implies using"
 
699
                             " a GnuTLS security parameter \"%s\".\n",
 
700
                             safe_string(gnutls_sec_param_get_name
 
701
                                         (sec_param)));
 
702
              }
 
703
            }
 
704
          }
 
705
        }
 
706
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
 
707
          /* Err on the side of caution */
 
708
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
709
          if(debug){
 
710
            fprintf_plus(stderr, "Falling back to security parameter"
 
711
                         " \"%s\"\n",
 
712
                         safe_string(gnutls_sec_param_get_name
 
713
                                     (sec_param)));
 
714
          }
 
715
        }
 
716
      }
 
717
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
 
718
      if(uret != 0){
 
719
        mc->dh_bits = uret;
 
720
        if(debug){
 
721
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
 
722
                       " implies %u DH bits; using that.\n",
 
723
                       safe_string(gnutls_sec_param_get_name
 
724
                                   (sec_param)),
 
725
                       mc->dh_bits);
 
726
        }
 
727
      } else {
 
728
        fprintf_plus(stderr, "Failed to get implied number of DH"
 
729
                     " bits for security parameter \"%s\"): %s\n",
 
730
                     safe_string(gnutls_sec_param_get_name
 
731
                                 (sec_param)),
 
732
                     safer_gnutls_strerror(ret));
 
733
        goto globalfail;
 
734
      }
 
735
    } else if(debug){
 
736
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
 
737
                   mc->dh_bits);
 
738
    }
 
739
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
740
    if(ret != GNUTLS_E_SUCCESS){
 
741
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
 
742
                   " bits): %s\n", mc->dh_bits,
 
743
                   safer_gnutls_strerror(ret));
 
744
      goto globalfail;
 
745
    }
 
746
  }
569
747
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
570
748
  
571
749
  return 0;
573
751
 globalfail:
574
752
  
575
753
  gnutls_certificate_free_credentials(mc->cred);
576
 
  gnutls_global_deinit();
577
754
  gnutls_dh_params_deinit(mc->dh_params);
578
755
  return -1;
579
756
}
631
808
  /* ignore client certificate if any. */
632
809
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
633
810
  
634
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
635
 
  
636
811
  return 0;
637
812
}
638
813
 
640
815
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
641
816
                      __attribute__((unused)) const char *txt){}
642
817
 
 
818
/* Set effective uid to 0, return errno */
 
819
__attribute__((warn_unused_result))
 
820
error_t raise_privileges(void){
 
821
  error_t old_errno = errno;
 
822
  error_t ret_errno = 0;
 
823
  if(seteuid(0) == -1){
 
824
    ret_errno = errno;
 
825
  }
 
826
  errno = old_errno;
 
827
  return ret_errno;
 
828
}
 
829
 
 
830
/* Set effective and real user ID to 0.  Return errno. */
 
831
__attribute__((warn_unused_result))
 
832
error_t raise_privileges_permanently(void){
 
833
  error_t old_errno = errno;
 
834
  error_t ret_errno = raise_privileges();
 
835
  if(ret_errno != 0){
 
836
    errno = old_errno;
 
837
    return ret_errno;
 
838
  }
 
839
  if(setuid(0) == -1){
 
840
    ret_errno = errno;
 
841
  }
 
842
  errno = old_errno;
 
843
  return ret_errno;
 
844
}
 
845
 
 
846
/* Set effective user ID to unprivileged saved user ID */
 
847
__attribute__((warn_unused_result))
 
848
error_t lower_privileges(void){
 
849
  error_t old_errno = errno;
 
850
  error_t ret_errno = 0;
 
851
  if(seteuid(uid) == -1){
 
852
    ret_errno = errno;
 
853
  }
 
854
  errno = old_errno;
 
855
  return ret_errno;
 
856
}
 
857
 
 
858
/* Lower privileges permanently */
 
859
__attribute__((warn_unused_result))
 
860
error_t lower_privileges_permanently(void){
 
861
  error_t old_errno = errno;
 
862
  error_t ret_errno = 0;
 
863
  if(setuid(uid) == -1){
 
864
    ret_errno = errno;
 
865
  }
 
866
  errno = old_errno;
 
867
  return ret_errno;
 
868
}
 
869
 
 
870
/* Helper function to add_local_route() and delete_local_route() */
 
871
__attribute__((nonnull, warn_unused_result))
 
872
static bool add_delete_local_route(const bool add,
 
873
                                   const char *address,
 
874
                                   AvahiIfIndex if_index){
 
875
  int ret;
 
876
  char helper[] = "mandos-client-iprouteadddel";
 
877
  char add_arg[] = "add";
 
878
  char delete_arg[] = "delete";
 
879
  char debug_flag[] = "--debug";
 
880
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
 
881
  if(pluginhelperdir == NULL){
 
882
    if(debug){
 
883
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
 
884
                   " variable not set; cannot run helper\n");
 
885
    }
 
886
    return false;
 
887
  }
 
888
  
 
889
  char interface[IF_NAMESIZE];
 
890
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
891
    perror_plus("if_indextoname");
 
892
    return false;
 
893
  }
 
894
  
 
895
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
896
  if(devnull == -1){
 
897
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
898
    return false;
 
899
  }
 
900
  pid_t pid = fork();
 
901
  if(pid == 0){
 
902
    /* Child */
 
903
    /* Raise privileges */
 
904
    errno = raise_privileges_permanently();
 
905
    if(errno != 0){
 
906
      perror_plus("Failed to raise privileges");
 
907
      /* _exit(EX_NOPERM); */
 
908
    } else {
 
909
      /* Set group */
 
910
      errno = 0;
 
911
      ret = setgid(0);
 
912
      if(ret == -1){
 
913
        perror_plus("setgid");
 
914
        _exit(EX_NOPERM);
 
915
      }
 
916
      /* Reset supplementary groups */
 
917
      errno = 0;
 
918
      ret = setgroups(0, NULL);
 
919
      if(ret == -1){
 
920
        perror_plus("setgroups");
 
921
        _exit(EX_NOPERM);
 
922
      }
 
923
    }
 
924
    ret = dup2(devnull, STDIN_FILENO);
 
925
    if(ret == -1){
 
926
      perror_plus("dup2(devnull, STDIN_FILENO)");
 
927
      _exit(EX_OSERR);
 
928
    }
 
929
    ret = close(devnull);
 
930
    if(ret == -1){
 
931
      perror_plus("close");
 
932
      _exit(EX_OSERR);
 
933
    }
 
934
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
935
    if(ret == -1){
 
936
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
937
      _exit(EX_OSERR);
 
938
    }
 
939
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
 
940
                                                    O_RDONLY
 
941
                                                    | O_DIRECTORY
 
942
                                                    | O_PATH
 
943
                                                    | O_CLOEXEC));
 
944
    if(helperdir_fd == -1){
 
945
      perror_plus("open");
 
946
      _exit(EX_UNAVAILABLE);
 
947
    }
 
948
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
 
949
                                                   helper, O_RDONLY));
 
950
    if(helper_fd == -1){
 
951
      perror_plus("openat");
 
952
      close(helperdir_fd);
 
953
      _exit(EX_UNAVAILABLE);
 
954
    }
 
955
    close(helperdir_fd);
 
956
#ifdef __GNUC__
 
957
#pragma GCC diagnostic push
 
958
#pragma GCC diagnostic ignored "-Wcast-qual"
 
959
#endif
 
960
    if(fexecve(helper_fd, (char *const [])
 
961
               { helper, add ? add_arg : delete_arg, (char *)address,
 
962
                   interface, debug ? debug_flag : NULL, NULL },
 
963
               environ) == -1){
 
964
#ifdef __GNUC__
 
965
#pragma GCC diagnostic pop
 
966
#endif
 
967
      perror_plus("fexecve");
 
968
      _exit(EXIT_FAILURE);
 
969
    }
 
970
  }
 
971
  if(pid == -1){
 
972
    perror_plus("fork");
 
973
    return false;
 
974
  }
 
975
  int status;
 
976
  pid_t pret = -1;
 
977
  errno = 0;
 
978
  do {
 
979
    pret = waitpid(pid, &status, 0);
 
980
    if(pret == -1 and errno == EINTR and quit_now){
 
981
      int errno_raising = 0;
 
982
      if((errno = raise_privileges()) != 0){
 
983
        errno_raising = errno;
 
984
        perror_plus("Failed to raise privileges in order to"
 
985
                    " kill helper program");
 
986
      }
 
987
      if(kill(pid, SIGTERM) == -1){
 
988
        perror_plus("kill");
 
989
      }
 
990
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
 
991
        perror_plus("Failed to lower privileges after killing"
 
992
                    " helper program");
 
993
      }
 
994
      return false;
 
995
    }
 
996
  } while(pret == -1 and errno == EINTR);
 
997
  if(pret == -1){
 
998
    perror_plus("waitpid");
 
999
    return false;
 
1000
  }
 
1001
  if(WIFEXITED(status)){
 
1002
    if(WEXITSTATUS(status) != 0){
 
1003
      fprintf_plus(stderr, "Error: iprouteadddel exited"
 
1004
                   " with status %d\n", WEXITSTATUS(status));
 
1005
      return false;
 
1006
    }
 
1007
    return true;
 
1008
  }
 
1009
  if(WIFSIGNALED(status)){
 
1010
    fprintf_plus(stderr, "Error: iprouteadddel died by"
 
1011
                 " signal %d\n", WTERMSIG(status));
 
1012
    return false;
 
1013
  }
 
1014
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
 
1015
  return false;
 
1016
}
 
1017
 
 
1018
__attribute__((nonnull, warn_unused_result))
 
1019
static bool add_local_route(const char *address,
 
1020
                            AvahiIfIndex if_index){
 
1021
  if(debug){
 
1022
    fprintf_plus(stderr, "Adding route to %s\n", address);
 
1023
  }
 
1024
  return add_delete_local_route(true, address, if_index);
 
1025
}
 
1026
 
 
1027
__attribute__((nonnull, warn_unused_result))
 
1028
static bool delete_local_route(const char *address,
 
1029
                               AvahiIfIndex if_index){
 
1030
  if(debug){
 
1031
    fprintf_plus(stderr, "Removing route to %s\n", address);
 
1032
  }
 
1033
  return add_delete_local_route(false, address, if_index);
 
1034
}
 
1035
 
643
1036
/* Called when a Mandos server is found */
644
1037
__attribute__((nonnull, warn_unused_result))
645
1038
static int start_mandos_communication(const char *ip, in_port_t port,
656
1049
  int retval = -1;
657
1050
  gnutls_session_t session;
658
1051
  int pf;                       /* Protocol family */
 
1052
  bool route_added = false;
659
1053
  
660
1054
  errno = 0;
661
1055
  
719
1113
                 PRIuMAX "\n", ip, (uintmax_t)port);
720
1114
  }
721
1115
  
722
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
1116
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
723
1117
  if(tcp_sd < 0){
724
1118
    int e = errno;
725
1119
    perror_plus("socket");
732
1126
    goto mandos_end;
733
1127
  }
734
1128
  
735
 
  memset(&to, 0, sizeof(to));
736
1129
  if(af == AF_INET6){
737
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
738
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
1130
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
 
1131
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
 
1132
    ret = inet_pton(af, ip, &to6->sin6_addr);
739
1133
  } else {                      /* IPv4 */
740
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
741
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
1134
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
 
1135
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
 
1136
    ret = inet_pton(af, ip, &to4->sin_addr);
742
1137
  }
743
1138
  if(ret < 0 ){
744
1139
    int e = errno;
814
1209
    goto mandos_end;
815
1210
  }
816
1211
  
817
 
  if(af == AF_INET6){
818
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
819
 
                  sizeof(struct sockaddr_in6));
820
 
  } else {
821
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
822
 
                  sizeof(struct sockaddr_in));
823
 
  }
824
 
  if(ret < 0){
825
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
826
 
      int e = errno;
827
 
      perror_plus("connect");
828
 
      errno = e;
829
 
    }
830
 
    goto mandos_end;
831
 
  }
832
 
  
833
 
  if(quit_now){
834
 
    errno = EINTR;
835
 
    goto mandos_end;
 
1212
  while(true){
 
1213
    if(af == AF_INET6){
 
1214
      ret = connect(tcp_sd, (struct sockaddr *)&to,
 
1215
                    sizeof(struct sockaddr_in6));
 
1216
    } else {
 
1217
      ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
1218
                    sizeof(struct sockaddr_in));
 
1219
    }
 
1220
    if(ret < 0){
 
1221
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
 
1222
         and if_index != AVAHI_IF_UNSPEC
 
1223
         and connect_to == NULL
 
1224
         and not route_added and
 
1225
         ((af == AF_INET6 and not
 
1226
           IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
 
1227
                                    &to)->sin6_addr)))
 
1228
          or (af == AF_INET and
 
1229
              /* Not a a IPv4LL address */
 
1230
              (ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
 
1231
               & 0xFFFF0000L) != 0xA9FE0000L))){
 
1232
        /* Work around Avahi bug - Avahi does not announce link-local
 
1233
           addresses if it has a global address, so local hosts with
 
1234
           *only* a link-local address (e.g. Mandos clients) cannot
 
1235
           connect to a Mandos server announced by Avahi on a server
 
1236
           host with a global address.  Work around this by retrying
 
1237
           with an explicit route added with the server's address.
 
1238
           
 
1239
           Avahi bug reference:
 
1240
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
 
1241
           https://bugs.debian.org/587961
 
1242
        */
 
1243
        if(debug){
 
1244
          fprintf_plus(stderr, "Mandos server unreachable, trying"
 
1245
                       " direct route\n");
 
1246
        }
 
1247
        int e = errno;
 
1248
        route_added = add_local_route(ip, if_index);
 
1249
        if(route_added){
 
1250
          continue;
 
1251
        }
 
1252
        errno = e;
 
1253
      }
 
1254
      if(errno != ECONNREFUSED or debug){
 
1255
        int e = errno;
 
1256
        perror_plus("connect");
 
1257
        errno = e;
 
1258
      }
 
1259
      goto mandos_end;
 
1260
    }
 
1261
    
 
1262
    if(quit_now){
 
1263
      errno = EINTR;
 
1264
      goto mandos_end;
 
1265
    }
 
1266
    break;
836
1267
  }
837
1268
  
838
1269
  const char *out = mandos_protocol_version;
1021
1452
  
1022
1453
 mandos_end:
1023
1454
  {
 
1455
    if(route_added){
 
1456
      if(not delete_local_route(ip, if_index)){
 
1457
        fprintf_plus(stderr, "Failed to delete local route to %s on"
 
1458
                     " interface %d", ip, if_index);
 
1459
      }
 
1460
    }
1024
1461
    int e = errno;
1025
1462
    free(decrypted_buffer);
1026
1463
    free(buffer);
1027
1464
    if(tcp_sd >= 0){
1028
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
1465
      ret = close(tcp_sd);
1029
1466
    }
1030
1467
    if(ret == -1){
1031
1468
      if(e == 0){
1066
1503
     timed out */
1067
1504
  
1068
1505
  if(quit_now){
 
1506
    avahi_s_service_resolver_free(r);
1069
1507
    return;
1070
1508
  }
1071
1509
  
1194
1632
    errno = ret_errno;
1195
1633
    return false;
1196
1634
  }
1197
 
  strcpy(ifr->ifr_name, ifname);
 
1635
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
 
1636
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1198
1637
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1199
1638
  if(ret == -1){
1200
1639
    if(debug){
1451
1890
  }
1452
1891
}
1453
1892
 
1454
 
/* Set effective uid to 0, return errno */
1455
 
__attribute__((warn_unused_result))
1456
 
error_t raise_privileges(void){
1457
 
  error_t old_errno = errno;
1458
 
  error_t ret_errno = 0;
1459
 
  if(seteuid(0) == -1){
1460
 
    ret_errno = errno;
1461
 
    perror_plus("seteuid");
1462
 
  }
1463
 
  errno = old_errno;
1464
 
  return ret_errno;
1465
 
}
1466
 
 
1467
 
/* Set effective and real user ID to 0.  Return errno. */
1468
 
__attribute__((warn_unused_result))
1469
 
error_t raise_privileges_permanently(void){
1470
 
  error_t old_errno = errno;
1471
 
  error_t ret_errno = raise_privileges();
1472
 
  if(ret_errno != 0){
1473
 
    errno = old_errno;
1474
 
    return ret_errno;
1475
 
  }
1476
 
  if(setuid(0) == -1){
1477
 
    ret_errno = errno;
1478
 
    perror_plus("seteuid");
1479
 
  }
1480
 
  errno = old_errno;
1481
 
  return ret_errno;
1482
 
}
1483
 
 
1484
 
/* Set effective user ID to unprivileged saved user ID */
1485
 
__attribute__((warn_unused_result))
1486
 
error_t lower_privileges(void){
1487
 
  error_t old_errno = errno;
1488
 
  error_t ret_errno = 0;
1489
 
  if(seteuid(uid) == -1){
1490
 
    ret_errno = errno;
1491
 
    perror_plus("seteuid");
1492
 
  }
1493
 
  errno = old_errno;
1494
 
  return ret_errno;
1495
 
}
1496
 
 
1497
 
/* Lower privileges permanently */
1498
 
__attribute__((warn_unused_result))
1499
 
error_t lower_privileges_permanently(void){
1500
 
  error_t old_errno = errno;
1501
 
  error_t ret_errno = 0;
1502
 
  if(setuid(uid) == -1){
1503
 
    ret_errno = errno;
1504
 
    perror_plus("setuid");
1505
 
  }
1506
 
  errno = old_errno;
1507
 
  return ret_errno;
1508
 
}
1509
 
 
1510
 
#ifndef O_CLOEXEC
1511
 
/*
1512
 
 * Based on the example in the GNU LibC manual chapter 13.13 "File
1513
 
 * Descriptor Flags".
1514
 
 | [[info:libc:Descriptor%20Flags][File Descriptor Flags]] |
1515
 
 */
1516
 
__attribute__((warn_unused_result))
1517
 
static int set_cloexec_flag(int fd){
1518
 
  int ret = (int)TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
1519
 
  /* If reading the flags failed, return error indication now. */
1520
 
  if(ret < 0){
1521
 
    return ret;
1522
 
  }
1523
 
  /* Store modified flag word in the descriptor. */
1524
 
  return (int)TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD,
1525
 
                                       ret | FD_CLOEXEC));
1526
 
}
1527
 
#endif  /* not O_CLOEXEC */
1528
 
 
1529
1893
__attribute__((nonnull))
1530
1894
void run_network_hooks(const char *mode, const char *interface,
1531
1895
                       const float delay){
1532
 
  struct dirent **direntries;
 
1896
  struct dirent **direntries = NULL;
1533
1897
  if(hookdir_fd == -1){
1534
 
    hookdir_fd = open(hookdir, O_RDONLY |
1535
 
#ifdef O_CLOEXEC
1536
 
                      O_CLOEXEC
1537
 
#else  /* not O_CLOEXEC */
1538
 
                      0
1539
 
#endif  /* not O_CLOEXEC */
1540
 
                      );
 
1898
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
 
1899
                      | O_CLOEXEC);
1541
1900
    if(hookdir_fd == -1){
1542
1901
      if(errno == ENOENT){
1543
1902
        if(debug){
1549
1908
      }
1550
1909
      return;
1551
1910
    }
1552
 
#ifndef O_CLOEXEC
1553
 
    if(set_cloexec_flag(hookdir_fd) < 0){
1554
 
      perror_plus("set_cloexec_flag");
1555
 
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
1556
 
        perror_plus("close");
1557
 
      } else {
1558
 
        hookdir_fd = -1;
1559
 
      }
1560
 
      return;
1561
 
    }
1562
 
#endif  /* not O_CLOEXEC */
1563
1911
  }
1564
 
#ifdef __GLIBC__
1565
 
#if __GLIBC_PREREQ(2, 15)
1566
1912
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1567
1913
                           runnable_hook, alphasort);
1568
 
#else  /* not __GLIBC_PREREQ(2, 15) */
1569
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1570
 
                         alphasort);
1571
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
1572
 
#else   /* not __GLIBC__ */
1573
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1574
 
                         alphasort);
1575
 
#endif  /* not __GLIBC__ */
1576
1914
  if(numhooks == -1){
1577
1915
    perror_plus("scandir");
1578
1916
    return;
1579
1917
  }
1580
1918
  struct dirent *direntry;
1581
1919
  int ret;
1582
 
  int devnull = open("/dev/null", O_RDONLY);
 
1920
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
1921
  if(devnull == -1){
 
1922
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
1923
    return;
 
1924
  }
1583
1925
  for(int i = 0; i < numhooks; i++){
1584
1926
    direntry = direntries[i];
1585
1927
    if(debug){
1590
1932
    if(hook_pid == 0){
1591
1933
      /* Child */
1592
1934
      /* Raise privileges */
1593
 
      if(raise_privileges_permanently() != 0){
 
1935
      errno = raise_privileges_permanently();
 
1936
      if(errno != 0){
1594
1937
        perror_plus("Failed to raise privileges");
1595
1938
        _exit(EX_NOPERM);
1596
1939
      }
1608
1951
        perror_plus("setgroups");
1609
1952
        _exit(EX_NOPERM);
1610
1953
      }
1611
 
      ret = dup2(devnull, STDIN_FILENO);
1612
 
      if(ret == -1){
1613
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
1614
 
        _exit(EX_OSERR);
1615
 
      }
1616
 
      ret = close(devnull);
1617
 
      if(ret == -1){
1618
 
        perror_plus("close");
1619
 
        _exit(EX_OSERR);
1620
 
      }
1621
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1622
 
      if(ret == -1){
1623
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1624
 
        _exit(EX_OSERR);
1625
 
      }
1626
1954
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1627
1955
      if(ret == -1){
1628
1956
        perror_plus("setenv");
1663
1991
          _exit(EX_OSERR);
1664
1992
        }
1665
1993
      }
1666
 
      if(fexecve(hookdir_fd, (char *const [])
1667
 
                 { direntry->d_name, NULL }, environ) == -1){
 
1994
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
 
1995
                                                   direntry->d_name,
 
1996
                                                   O_RDONLY));
 
1997
      if(hook_fd == -1){
 
1998
        perror_plus("openat");
 
1999
        _exit(EXIT_FAILURE);
 
2000
      }
 
2001
      if(close(hookdir_fd) == -1){
 
2002
        perror_plus("close");
 
2003
        _exit(EXIT_FAILURE);
 
2004
      }
 
2005
      ret = dup2(devnull, STDIN_FILENO);
 
2006
      if(ret == -1){
 
2007
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
2008
        _exit(EX_OSERR);
 
2009
      }
 
2010
      ret = close(devnull);
 
2011
      if(ret == -1){
 
2012
        perror_plus("close");
 
2013
        _exit(EX_OSERR);
 
2014
      }
 
2015
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
2016
      if(ret == -1){
 
2017
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
2018
        _exit(EX_OSERR);
 
2019
      }
 
2020
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
 
2021
                 environ) == -1){
1668
2022
        perror_plus("fexecve");
1669
2023
        _exit(EXIT_FAILURE);
1670
2024
      }
1671
2025
    } else {
 
2026
      if(hook_pid == -1){
 
2027
        perror_plus("fork");
 
2028
        free(direntry);
 
2029
        continue;
 
2030
      }
1672
2031
      int status;
1673
2032
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1674
2033
        perror_plus("waitpid");
 
2034
        free(direntry);
1675
2035
        continue;
1676
2036
      }
1677
2037
      if(WIFEXITED(status)){
1679
2039
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1680
2040
                       " with status %d\n", direntry->d_name,
1681
2041
                       WEXITSTATUS(status));
 
2042
          free(direntry);
1682
2043
          continue;
1683
2044
        }
1684
2045
      } else if(WIFSIGNALED(status)){
1685
2046
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1686
2047
                     " signal %d\n", direntry->d_name,
1687
2048
                     WTERMSIG(status));
 
2049
        free(direntry);
1688
2050
        continue;
1689
2051
      } else {
1690
2052
        fprintf_plus(stderr, "Warning: network hook \"%s\""
1691
2053
                     " crashed\n", direntry->d_name);
 
2054
        free(direntry);
1692
2055
        continue;
1693
2056
      }
1694
2057
    }
1696
2059
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1697
2060
                   direntry->d_name);
1698
2061
    }
 
2062
    free(direntry);
1699
2063
  }
1700
 
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2064
  free(direntries);
 
2065
  if(close(hookdir_fd) == -1){
1701
2066
    perror_plus("close");
1702
2067
  } else {
1703
2068
    hookdir_fd = -1;
1743
2108
    }
1744
2109
    
1745
2110
    if(quit_now){
1746
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2111
      ret = close(sd);
1747
2112
      if(ret == -1){
1748
2113
        perror_plus("close");
1749
2114
      }
1759
2124
    /* Raise privileges */
1760
2125
    ret_errno = raise_privileges();
1761
2126
    if(ret_errno != 0){
 
2127
      errno = ret_errno;
1762
2128
      perror_plus("Failed to raise privileges");
1763
2129
    }
1764
2130
    
1798
2164
    }
1799
2165
    
1800
2166
    /* Close the socket */
1801
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2167
    ret = close(sd);
1802
2168
    if(ret == -1){
1803
2169
      perror_plus("close");
1804
2170
    }
1868
2234
    /* Raise privileges */
1869
2235
    ret_errno = raise_privileges();
1870
2236
    if(ret_errno != 0){
 
2237
      errno = ret_errno;
1871
2238
      perror_plus("Failed to raise privileges");
1872
2239
    }
1873
2240
    
1885
2252
    }
1886
2253
    
1887
2254
    /* Close the socket */
1888
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2255
    int ret = close(sd);
1889
2256
    if(ret == -1){
1890
2257
      perror_plus("close");
1891
2258
    }
1906
2273
}
1907
2274
 
1908
2275
int main(int argc, char *argv[]){
1909
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1910
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1911
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1912
 
                        .interfaces = NULL, .interfaces_size = 0 };
 
2276
  mandos_context mc = { .server = NULL, .dh_bits = 0,
 
2277
                        .priority = "SECURE256:!CTYPE-X.509"
 
2278
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
 
2279
                        .current_server = NULL, .interfaces = NULL,
 
2280
                        .interfaces_size = 0 };
1913
2281
  AvahiSServiceBrowser *sb = NULL;
1914
2282
  error_t ret_errno;
1915
2283
  int ret;
1924
2292
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1925
2293
  const char *seckey = PATHDIR "/" SECKEY;
1926
2294
  const char *pubkey = PATHDIR "/" PUBKEY;
 
2295
  const char *dh_params_file = NULL;
1927
2296
  char *interfaces_hooks = NULL;
1928
2297
  
1929
2298
  bool gnutls_initialized = false;
1982
2351
        .doc = "Bit length of the prime number used in the"
1983
2352
        " Diffie-Hellman key exchange",
1984
2353
        .group = 2 },
 
2354
      { .name = "dh-params", .key = 134,
 
2355
        .arg = "FILE",
 
2356
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
 
2357
        " for the Diffie-Hellman key exchange",
 
2358
        .group = 2 },
1985
2359
      { .name = "priority", .key = 130,
1986
2360
        .arg = "STRING",
1987
2361
        .doc = "GnuTLS priority string for the TLS handshake",
2042
2416
        }
2043
2417
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2044
2418
        break;
 
2419
      case 134:                 /* --dh-params */
 
2420
        dh_params_file = arg;
 
2421
        break;
2045
2422
      case 130:                 /* --priority */
2046
2423
        mc.priority = arg;
2047
2424
        break;
2103
2480
      goto end;
2104
2481
    }
2105
2482
  }
2106
 
    
 
2483
  
2107
2484
  {
2108
2485
    /* Work around Debian bug #633582:
2109
2486
       <http://bugs.debian.org/633582> */
2133
2510
              }
2134
2511
            }
2135
2512
          }
2136
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2513
          close(seckey_fd);
2137
2514
        }
2138
2515
      }
2139
 
    
 
2516
      
2140
2517
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2141
2518
        int pubkey_fd = open(pubkey, O_RDONLY);
2142
2519
        if(pubkey_fd == -1){
2154
2531
              }
2155
2532
            }
2156
2533
          }
2157
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
2158
 
        }
2159
 
      }
2160
 
    
 
2534
          close(pubkey_fd);
 
2535
        }
 
2536
      }
 
2537
      
 
2538
      if(dh_params_file != NULL
 
2539
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
 
2540
        int dhparams_fd = open(dh_params_file, O_RDONLY);
 
2541
        if(dhparams_fd == -1){
 
2542
          perror_plus("open");
 
2543
        } else {
 
2544
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
 
2545
          if(ret == -1){
 
2546
            perror_plus("fstat");
 
2547
          } else {
 
2548
            if(S_ISREG(st.st_mode)
 
2549
               and st.st_uid == 0 and st.st_gid == 0){
 
2550
              ret = fchown(dhparams_fd, uid, gid);
 
2551
              if(ret == -1){
 
2552
                perror_plus("fchown");
 
2553
              }
 
2554
            }
 
2555
          }
 
2556
          close(dhparams_fd);
 
2557
        }
 
2558
      }
 
2559
      
2161
2560
      /* Lower privileges */
2162
2561
      ret_errno = lower_privileges();
2163
2562
      if(ret_errno != 0){
2280
2679
  
2281
2680
  /* If no interfaces were specified, make a list */
2282
2681
  if(mc.interfaces == NULL){
2283
 
    struct dirent **direntries;
 
2682
    struct dirent **direntries = NULL;
2284
2683
    /* Look for any good interfaces */
2285
2684
    ret = scandir(sys_class_net, &direntries, good_interface,
2286
2685
                  alphasort);
2292
2691
        if(ret_errno != 0){
2293
2692
          errno = ret_errno;
2294
2693
          perror_plus("argz_add");
 
2694
          free(direntries[i]);
2295
2695
          continue;
2296
2696
        }
2297
2697
        if(debug){
2298
2698
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2299
2699
                       direntries[i]->d_name);
2300
2700
        }
 
2701
        free(direntries[i]);
2301
2702
      }
2302
2703
      free(direntries);
2303
2704
    } else {
2304
 
      free(direntries);
 
2705
      if(ret == 0){
 
2706
        free(direntries);
 
2707
      }
2305
2708
      fprintf_plus(stderr, "Could not find a network interface\n");
2306
2709
      exitcode = EXIT_FAILURE;
2307
2710
      goto end;
2333
2736
      errno = bring_up_interface(interface, delay);
2334
2737
      if(not interface_was_up){
2335
2738
        if(errno != 0){
2336
 
          perror_plus("Failed to bring up interface");
 
2739
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
 
2740
                       " %s\n", interface, strerror(errno));
2337
2741
        } else {
2338
2742
          errno = argz_add(&interfaces_to_take_down,
2339
2743
                           &interfaces_to_take_down_size,
2362
2766
    goto end;
2363
2767
  }
2364
2768
  
2365
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2769
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
2366
2770
  if(ret == -1){
2367
2771
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2368
2772
    exitcode = EX_UNAVAILABLE;
2557
2961
  
2558
2962
  if(gnutls_initialized){
2559
2963
    gnutls_certificate_free_credentials(mc.cred);
2560
 
    gnutls_global_deinit();
2561
2964
    gnutls_dh_params_deinit(mc.dh_params);
2562
2965
  }
2563
2966
  
2571
2974
    mc.current_server->prev->next = NULL;
2572
2975
    while(mc.current_server != NULL){
2573
2976
      server *next = mc.current_server->next;
 
2977
#ifdef __GNUC__
 
2978
#pragma GCC diagnostic push
 
2979
#pragma GCC diagnostic ignored "-Wcast-qual"
 
2980
#endif
 
2981
      free((char *)(mc.current_server->ip));
 
2982
#ifdef __GNUC__
 
2983
#pragma GCC diagnostic pop
 
2984
#endif
2574
2985
      free(mc.current_server);
2575
2986
      mc.current_server = next;
2576
2987
    }
2580
2991
  {
2581
2992
    ret_errno = raise_privileges();
2582
2993
    if(ret_errno != 0){
 
2994
      errno = ret_errno;
2583
2995
      perror_plus("Failed to raise privileges");
2584
2996
    } else {
2585
2997
      
2608
3020
    
2609
3021
    ret_errno = lower_privileges_permanently();
2610
3022
    if(ret_errno != 0){
 
3023
      errno = ret_errno;
2611
3024
      perror_plus("Failed to lower privileges permanently");
2612
3025
    }
2613
3026
  }
2615
3028
  free(interfaces_to_take_down);
2616
3029
  free(interfaces_hooks);
2617
3030
  
 
3031
  void clean_dir_at(int base, const char * const dirname,
 
3032
                    uintmax_t level){
 
3033
    struct dirent **direntries = NULL;
 
3034
    int dret;
 
3035
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
 
3036
                                                O_RDONLY
 
3037
                                                | O_NOFOLLOW
 
3038
                                                | O_DIRECTORY
 
3039
                                                | O_PATH));
 
3040
    if(dir_fd == -1){
 
3041
      perror_plus("open");
 
3042
    }
 
3043
    int numentries = scandirat(dir_fd, ".", &direntries,
 
3044
                               notdotentries, alphasort);
 
3045
    if(numentries >= 0){
 
3046
      for(int i = 0; i < numentries; i++){
 
3047
        if(debug){
 
3048
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
 
3049
                       dirname, direntries[i]->d_name);
 
3050
        }
 
3051
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
 
3052
        if(dret == -1){
 
3053
          if(errno == EISDIR){
 
3054
              dret = unlinkat(dir_fd, direntries[i]->d_name,
 
3055
                              AT_REMOVEDIR);
 
3056
          }         
 
3057
          if((dret == -1) and (errno == ENOTEMPTY)
 
3058
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
 
3059
                  == 0) and (level == 0)){
 
3060
            /* Recurse only in this special case */
 
3061
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
 
3062
            dret = 0;
 
3063
          }
 
3064
          if(dret == -1){
 
3065
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
 
3066
                         direntries[i]->d_name, strerror(errno));
 
3067
          }
 
3068
        }
 
3069
        free(direntries[i]);
 
3070
      }
 
3071
      
 
3072
      /* need to clean even if 0 because man page doesn't specify */
 
3073
      free(direntries);
 
3074
      if(numentries == -1){
 
3075
        perror_plus("scandirat");
 
3076
      }
 
3077
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
 
3078
      if(dret == -1 and errno != ENOENT){
 
3079
        perror_plus("rmdir");
 
3080
      }
 
3081
    } else {
 
3082
      perror_plus("scandirat");
 
3083
    }
 
3084
    close(dir_fd);
 
3085
  }
 
3086
  
2618
3087
  /* Removes the GPGME temp directory and all files inside */
2619
3088
  if(tempdir != NULL){
2620
 
    struct dirent **direntries = NULL;
2621
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY));
2622
 
    if(tempdir_fd == -1){
2623
 
      perror_plus("open");
2624
 
    } else {
2625
 
#ifdef __GLIBC__
2626
 
#if __GLIBC_PREREQ(2, 15)
2627
 
      int numentries = scandirat(tempdir_fd, ".", &direntries,
2628
 
                                 notdotentries, alphasort);
2629
 
#else  /* not __GLIBC_PREREQ(2, 15) */
2630
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2631
 
                               alphasort);
2632
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
2633
 
#else   /* not __GLIBC__ */
2634
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2635
 
                               alphasort);
2636
 
#endif  /* not __GLIBC__ */
2637
 
      if(numentries > 0){
2638
 
        for(int i = 0; i < numentries; i++){
2639
 
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
2640
 
          if(ret == -1){
2641
 
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
2642
 
                         " \"%s\", 0): %s\n", tempdir,
2643
 
                         direntries[i]->d_name, strerror(errno));
2644
 
          }
2645
 
        }
2646
 
        
2647
 
        /* need to clean even if 0 because man page doesn't specify */
2648
 
        free(direntries);
2649
 
        if(numentries == -1){
2650
 
          perror_plus("scandir");
2651
 
        }
2652
 
        ret = rmdir(tempdir);
2653
 
        if(ret == -1 and errno != ENOENT){
2654
 
          perror_plus("rmdir");
2655
 
        }
2656
 
      }
2657
 
      TEMP_FAILURE_RETRY(close(tempdir_fd));
2658
 
    }
 
3089
    clean_dir_at(-1, tempdir, 0);
2659
3090
  }
2660
3091
  
2661
3092
  if(quit_now){