/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: 2016-10-01 14:24:14 UTC
  • Revision ID: teddy@recompile.se-20161001142414-y53pczg9ll0r2q4y
Tags: version-1.7.11-1
* Makefile (version): Change to 1.7.11.
* NEWS (Version 1.7.11): Add new entry.
* debian/changelog (1.7.11-1): - '' -

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(), strsignal()
 
51
                                */
51
52
#include <sys/ioctl.h>          /* ioctl */
52
53
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
54
                                   sockaddr_in6, PF_INET6,
57
58
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
59
                                   inet_pton(), connect(),
59
60
                                   getnameinfo() */
60
 
#include <fcntl.h>              /* open(), unlinkat() */
 
61
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
61
62
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
63
                                 */
63
64
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
64
65
                                   strtoimax() */
65
 
#include <errno.h>              /* perror(), errno,
 
66
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
 
67
                                   EAI_SYSTEM, ENETUNREACH,
 
68
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
 
69
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
 
70
                                   ENOTEMPTY,
66
71
                                   program_invocation_short_name */
67
72
#include <time.h>               /* nanosleep(), time(), sleep() */
68
73
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
240
245
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
241
246
  if(ret == -1){
242
247
    perror_plus("clock_gettime");
243
 
    free(new_server->ip);
 
248
#ifdef __GNUC__
 
249
#pragma GCC diagnostic push
 
250
#pragma GCC diagnostic ignored "-Wcast-qual"
 
251
#endif
 
252
    free((char *)(new_server->ip));
 
253
#ifdef __GNUC__
 
254
#pragma GCC diagnostic pop
 
255
#endif
244
256
    free(new_server);
245
257
    return false;
246
258
  }
298
310
      return false;
299
311
    }
300
312
    
301
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
 
313
    ret = close(fd);
302
314
    if(ret == -1){
303
315
      perror_plus("close");
304
316
    }
486
498
  return plaintext_length;
487
499
}
488
500
 
 
501
__attribute__((warn_unused_result, const))
 
502
static const char *safe_string(const char *str){
 
503
  if(str == NULL)
 
504
    return "(unknown)";
 
505
  return str;
 
506
}
 
507
 
489
508
__attribute__((warn_unused_result))
490
509
static const char *safer_gnutls_strerror(int value){
491
510
  const char *ret = gnutls_strerror(value);
492
 
  if(ret == NULL)
493
 
    ret = "(unknown)";
494
 
  return ret;
 
511
  return safe_string(ret);
495
512
}
496
513
 
497
514
/* GnuTLS log function callback */
501
518
  fprintf_plus(stderr, "GnuTLS: %s", string);
502
519
}
503
520
 
504
 
__attribute__((nonnull, warn_unused_result))
 
521
__attribute__((nonnull(1, 2, 4), warn_unused_result))
505
522
static int init_gnutls_global(const char *pubkeyfilename,
506
523
                              const char *seckeyfilename,
 
524
                              const char *dhparamsfilename,
507
525
                              mandos_context *mc){
508
526
  int ret;
 
527
  unsigned int uret;
509
528
  
510
529
  if(debug){
511
530
    fprintf_plus(stderr, "Initializing GnuTLS\n");
512
531
  }
513
532
  
514
 
  ret = gnutls_global_init();
515
 
  if(ret != GNUTLS_E_SUCCESS){
516
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
517
 
                 safer_gnutls_strerror(ret));
518
 
    return -1;
519
 
  }
520
 
  
521
533
  if(debug){
522
534
    /* "Use a log level over 10 to enable all debugging options."
523
535
     * - GnuTLS manual
531
543
  if(ret != GNUTLS_E_SUCCESS){
532
544
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
533
545
                 safer_gnutls_strerror(ret));
534
 
    gnutls_global_deinit();
535
546
    return -1;
536
547
  }
537
548
  
562
573
                 safer_gnutls_strerror(ret));
563
574
    goto globalfail;
564
575
  }
565
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
566
 
  if(ret != GNUTLS_E_SUCCESS){
567
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
568
 
                 safer_gnutls_strerror(ret));
569
 
    goto globalfail;
570
 
  }
571
 
  
 
576
  /* If a Diffie-Hellman parameters file was given, try to use it */
 
577
  if(dhparamsfilename != NULL){
 
578
    gnutls_datum_t params = { .data = NULL, .size = 0 };
 
579
    do {
 
580
      int dhpfile = open(dhparamsfilename, O_RDONLY);
 
581
      if(dhpfile == -1){
 
582
        perror_plus("open");
 
583
        dhparamsfilename = NULL;
 
584
        break;
 
585
      }
 
586
      size_t params_capacity = 0;
 
587
      while(true){
 
588
        params_capacity = incbuffer((char **)&params.data,
 
589
                                    (size_t)params.size,
 
590
                                    (size_t)params_capacity);
 
591
        if(params_capacity == 0){
 
592
          perror_plus("incbuffer");
 
593
          free(params.data);
 
594
          params.data = NULL;
 
595
          dhparamsfilename = NULL;
 
596
          break;
 
597
        }
 
598
        ssize_t bytes_read = read(dhpfile,
 
599
                                  params.data + params.size,
 
600
                                  BUFFER_SIZE);
 
601
        /* EOF */
 
602
        if(bytes_read == 0){
 
603
          break;
 
604
        }
 
605
        /* check bytes_read for failure */
 
606
        if(bytes_read < 0){
 
607
          perror_plus("read");
 
608
          free(params.data);
 
609
          params.data = NULL;
 
610
          dhparamsfilename = NULL;
 
611
          break;
 
612
        }
 
613
        params.size += (unsigned int)bytes_read;
 
614
      }
 
615
      if(params.data == NULL){
 
616
        dhparamsfilename = NULL;
 
617
      }
 
618
      if(dhparamsfilename == NULL){
 
619
        break;
 
620
      }
 
621
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
 
622
                                          GNUTLS_X509_FMT_PEM);
 
623
      if(ret != GNUTLS_E_SUCCESS){
 
624
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
 
625
                     " \"%s\": %s\n", dhparamsfilename,
 
626
                     safer_gnutls_strerror(ret));
 
627
        dhparamsfilename = NULL;
 
628
      }
 
629
    } while(false);
 
630
  }
 
631
  if(dhparamsfilename == NULL){
 
632
    if(mc->dh_bits == 0){
 
633
      /* Find out the optimal number of DH bits */
 
634
      /* Try to read the private key file */
 
635
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
 
636
      do {
 
637
        int secfile = open(seckeyfilename, O_RDONLY);
 
638
        if(secfile == -1){
 
639
          perror_plus("open");
 
640
          break;
 
641
        }
 
642
        size_t buffer_capacity = 0;
 
643
        while(true){
 
644
          buffer_capacity = incbuffer((char **)&buffer.data,
 
645
                                      (size_t)buffer.size,
 
646
                                      (size_t)buffer_capacity);
 
647
          if(buffer_capacity == 0){
 
648
            perror_plus("incbuffer");
 
649
            free(buffer.data);
 
650
            buffer.data = NULL;
 
651
            break;
 
652
          }
 
653
          ssize_t bytes_read = read(secfile,
 
654
                                    buffer.data + buffer.size,
 
655
                                    BUFFER_SIZE);
 
656
          /* EOF */
 
657
          if(bytes_read == 0){
 
658
            break;
 
659
          }
 
660
          /* check bytes_read for failure */
 
661
          if(bytes_read < 0){
 
662
            perror_plus("read");
 
663
            free(buffer.data);
 
664
            buffer.data = NULL;
 
665
            break;
 
666
          }
 
667
          buffer.size += (unsigned int)bytes_read;
 
668
        }
 
669
        close(secfile);
 
670
      } while(false);
 
671
      /* If successful, use buffer to parse private key */
 
672
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
673
      if(buffer.data != NULL){
 
674
        {
 
675
          gnutls_openpgp_privkey_t privkey = NULL;
 
676
          ret = gnutls_openpgp_privkey_init(&privkey);
 
677
          if(ret != GNUTLS_E_SUCCESS){
 
678
            fprintf_plus(stderr, "Error initializing OpenPGP key"
 
679
                         " structure: %s",
 
680
                         safer_gnutls_strerror(ret));
 
681
            free(buffer.data);
 
682
            buffer.data = NULL;
 
683
          } else {
 
684
            ret = gnutls_openpgp_privkey_import
 
685
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
 
686
            if(ret != GNUTLS_E_SUCCESS){
 
687
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
 
688
                           safer_gnutls_strerror(ret));
 
689
              privkey = NULL;
 
690
            }
 
691
            free(buffer.data);
 
692
            buffer.data = NULL;
 
693
            if(privkey != NULL){
 
694
              /* Use private key to suggest an appropriate
 
695
                 sec_param */
 
696
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
 
697
              gnutls_openpgp_privkey_deinit(privkey);
 
698
              if(debug){
 
699
                fprintf_plus(stderr, "This OpenPGP key implies using"
 
700
                             " a GnuTLS security parameter \"%s\".\n",
 
701
                             safe_string(gnutls_sec_param_get_name
 
702
                                         (sec_param)));
 
703
              }
 
704
            }
 
705
          }
 
706
        }
 
707
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
 
708
          /* Err on the side of caution */
 
709
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
710
          if(debug){
 
711
            fprintf_plus(stderr, "Falling back to security parameter"
 
712
                         " \"%s\"\n",
 
713
                         safe_string(gnutls_sec_param_get_name
 
714
                                     (sec_param)));
 
715
          }
 
716
        }
 
717
      }
 
718
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
 
719
      if(uret != 0){
 
720
        mc->dh_bits = uret;
 
721
        if(debug){
 
722
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
 
723
                       " implies %u DH bits; using that.\n",
 
724
                       safe_string(gnutls_sec_param_get_name
 
725
                                   (sec_param)),
 
726
                       mc->dh_bits);
 
727
        }
 
728
      } else {
 
729
        fprintf_plus(stderr, "Failed to get implied number of DH"
 
730
                     " bits for security parameter \"%s\"): %s\n",
 
731
                     safe_string(gnutls_sec_param_get_name
 
732
                                 (sec_param)),
 
733
                     safer_gnutls_strerror(ret));
 
734
        goto globalfail;
 
735
      }
 
736
    } else if(debug){
 
737
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
 
738
                   mc->dh_bits);
 
739
    }
 
740
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
741
    if(ret != GNUTLS_E_SUCCESS){
 
742
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
 
743
                   " bits): %s\n", mc->dh_bits,
 
744
                   safer_gnutls_strerror(ret));
 
745
      goto globalfail;
 
746
    }
 
747
  }
572
748
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
573
749
  
574
750
  return 0;
576
752
 globalfail:
577
753
  
578
754
  gnutls_certificate_free_credentials(mc->cred);
579
 
  gnutls_global_deinit();
580
755
  gnutls_dh_params_deinit(mc->dh_params);
581
756
  return -1;
582
757
}
634
809
  /* ignore client certificate if any. */
635
810
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
636
811
  
637
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
638
 
  
639
812
  return 0;
640
813
}
641
814
 
643
816
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
644
817
                      __attribute__((unused)) const char *txt){}
645
818
 
 
819
/* Set effective uid to 0, return errno */
 
820
__attribute__((warn_unused_result))
 
821
int raise_privileges(void){
 
822
  int old_errno = errno;
 
823
  int ret = 0;
 
824
  if(seteuid(0) == -1){
 
825
    ret = errno;
 
826
  }
 
827
  errno = old_errno;
 
828
  return ret;
 
829
}
 
830
 
 
831
/* Set effective and real user ID to 0.  Return errno. */
 
832
__attribute__((warn_unused_result))
 
833
int raise_privileges_permanently(void){
 
834
  int old_errno = errno;
 
835
  int ret = raise_privileges();
 
836
  if(ret != 0){
 
837
    errno = old_errno;
 
838
    return ret;
 
839
  }
 
840
  if(setuid(0) == -1){
 
841
    ret = errno;
 
842
  }
 
843
  errno = old_errno;
 
844
  return ret;
 
845
}
 
846
 
 
847
/* Set effective user ID to unprivileged saved user ID */
 
848
__attribute__((warn_unused_result))
 
849
int lower_privileges(void){
 
850
  int old_errno = errno;
 
851
  int ret = 0;
 
852
  if(seteuid(uid) == -1){
 
853
    ret = errno;
 
854
  }
 
855
  errno = old_errno;
 
856
  return ret;
 
857
}
 
858
 
 
859
/* Lower privileges permanently */
 
860
__attribute__((warn_unused_result))
 
861
int lower_privileges_permanently(void){
 
862
  int old_errno = errno;
 
863
  int ret = 0;
 
864
  if(setuid(uid) == -1){
 
865
    ret = errno;
 
866
  }
 
867
  errno = old_errno;
 
868
  return ret;
 
869
}
 
870
 
 
871
/* Helper function to add_local_route() and delete_local_route() */
 
872
__attribute__((nonnull, warn_unused_result))
 
873
static bool add_delete_local_route(const bool add,
 
874
                                   const char *address,
 
875
                                   AvahiIfIndex if_index){
 
876
  int ret;
 
877
  char helper[] = "mandos-client-iprouteadddel";
 
878
  char add_arg[] = "add";
 
879
  char delete_arg[] = "delete";
 
880
  char debug_flag[] = "--debug";
 
881
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
 
882
  if(pluginhelperdir == NULL){
 
883
    if(debug){
 
884
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
 
885
                   " variable not set; cannot run helper\n");
 
886
    }
 
887
    return false;
 
888
  }
 
889
  
 
890
  char interface[IF_NAMESIZE];
 
891
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
892
    perror_plus("if_indextoname");
 
893
    return false;
 
894
  }
 
895
  
 
896
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
897
  if(devnull == -1){
 
898
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
899
    return false;
 
900
  }
 
901
  pid_t pid = fork();
 
902
  if(pid == 0){
 
903
    /* Child */
 
904
    /* Raise privileges */
 
905
    errno = raise_privileges_permanently();
 
906
    if(errno != 0){
 
907
      perror_plus("Failed to raise privileges");
 
908
      /* _exit(EX_NOPERM); */
 
909
    } else {
 
910
      /* Set group */
 
911
      errno = 0;
 
912
      ret = setgid(0);
 
913
      if(ret == -1){
 
914
        perror_plus("setgid");
 
915
        _exit(EX_NOPERM);
 
916
      }
 
917
      /* Reset supplementary groups */
 
918
      errno = 0;
 
919
      ret = setgroups(0, NULL);
 
920
      if(ret == -1){
 
921
        perror_plus("setgroups");
 
922
        _exit(EX_NOPERM);
 
923
      }
 
924
    }
 
925
    ret = dup2(devnull, STDIN_FILENO);
 
926
    if(ret == -1){
 
927
      perror_plus("dup2(devnull, STDIN_FILENO)");
 
928
      _exit(EX_OSERR);
 
929
    }
 
930
    ret = close(devnull);
 
931
    if(ret == -1){
 
932
      perror_plus("close");
 
933
      _exit(EX_OSERR);
 
934
    }
 
935
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
936
    if(ret == -1){
 
937
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
938
      _exit(EX_OSERR);
 
939
    }
 
940
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
 
941
                                                    O_RDONLY
 
942
                                                    | O_DIRECTORY
 
943
                                                    | O_PATH
 
944
                                                    | O_CLOEXEC));
 
945
    if(helperdir_fd == -1){
 
946
      perror_plus("open");
 
947
      _exit(EX_UNAVAILABLE);
 
948
    }
 
949
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
 
950
                                                   helper, O_RDONLY));
 
951
    if(helper_fd == -1){
 
952
      perror_plus("openat");
 
953
      close(helperdir_fd);
 
954
      _exit(EX_UNAVAILABLE);
 
955
    }
 
956
    close(helperdir_fd);
 
957
#ifdef __GNUC__
 
958
#pragma GCC diagnostic push
 
959
#pragma GCC diagnostic ignored "-Wcast-qual"
 
960
#endif
 
961
    if(fexecve(helper_fd, (char *const [])
 
962
               { helper, add ? add_arg : delete_arg, (char *)address,
 
963
                   interface, debug ? debug_flag : NULL, NULL },
 
964
               environ) == -1){
 
965
#ifdef __GNUC__
 
966
#pragma GCC diagnostic pop
 
967
#endif
 
968
      perror_plus("fexecve");
 
969
      _exit(EXIT_FAILURE);
 
970
    }
 
971
  }
 
972
  if(pid == -1){
 
973
    perror_plus("fork");
 
974
    return false;
 
975
  }
 
976
  int status;
 
977
  pid_t pret = -1;
 
978
  errno = 0;
 
979
  do {
 
980
    pret = waitpid(pid, &status, 0);
 
981
    if(pret == -1 and errno == EINTR and quit_now){
 
982
      int errno_raising = 0;
 
983
      if((errno = raise_privileges()) != 0){
 
984
        errno_raising = errno;
 
985
        perror_plus("Failed to raise privileges in order to"
 
986
                    " kill helper program");
 
987
      }
 
988
      if(kill(pid, SIGTERM) == -1){
 
989
        perror_plus("kill");
 
990
      }
 
991
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
 
992
        perror_plus("Failed to lower privileges after killing"
 
993
                    " helper program");
 
994
      }
 
995
      return false;
 
996
    }
 
997
  } while(pret == -1 and errno == EINTR);
 
998
  if(pret == -1){
 
999
    perror_plus("waitpid");
 
1000
    return false;
 
1001
  }
 
1002
  if(WIFEXITED(status)){
 
1003
    if(WEXITSTATUS(status) != 0){
 
1004
      fprintf_plus(stderr, "Error: iprouteadddel exited"
 
1005
                   " with status %d\n", WEXITSTATUS(status));
 
1006
      return false;
 
1007
    }
 
1008
    return true;
 
1009
  }
 
1010
  if(WIFSIGNALED(status)){
 
1011
    fprintf_plus(stderr, "Error: iprouteadddel died by"
 
1012
                 " signal %d\n", WTERMSIG(status));
 
1013
    return false;
 
1014
  }
 
1015
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
 
1016
  return false;
 
1017
}
 
1018
 
 
1019
__attribute__((nonnull, warn_unused_result))
 
1020
static bool add_local_route(const char *address,
 
1021
                            AvahiIfIndex if_index){
 
1022
  if(debug){
 
1023
    fprintf_plus(stderr, "Adding route to %s\n", address);
 
1024
  }
 
1025
  return add_delete_local_route(true, address, if_index);
 
1026
}
 
1027
 
 
1028
__attribute__((nonnull, warn_unused_result))
 
1029
static bool delete_local_route(const char *address,
 
1030
                               AvahiIfIndex if_index){
 
1031
  if(debug){
 
1032
    fprintf_plus(stderr, "Removing route to %s\n", address);
 
1033
  }
 
1034
  return add_delete_local_route(false, address, if_index);
 
1035
}
 
1036
 
646
1037
/* Called when a Mandos server is found */
647
1038
__attribute__((nonnull, warn_unused_result))
648
1039
static int start_mandos_communication(const char *ip, in_port_t port,
659
1050
  int retval = -1;
660
1051
  gnutls_session_t session;
661
1052
  int pf;                       /* Protocol family */
 
1053
  bool route_added = false;
662
1054
  
663
1055
  errno = 0;
664
1056
  
722
1114
                 PRIuMAX "\n", ip, (uintmax_t)port);
723
1115
  }
724
1116
  
725
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
1117
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
726
1118
  if(tcp_sd < 0){
727
1119
    int e = errno;
728
1120
    perror_plus("socket");
735
1127
    goto mandos_end;
736
1128
  }
737
1129
  
738
 
  memset(&to, 0, sizeof(to));
739
1130
  if(af == AF_INET6){
740
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
741
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
1131
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
 
1132
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
 
1133
    ret = inet_pton(af, ip, &to6->sin6_addr);
742
1134
  } else {                      /* IPv4 */
743
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
744
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
1135
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
 
1136
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
 
1137
    ret = inet_pton(af, ip, &to4->sin_addr);
745
1138
  }
746
1139
  if(ret < 0 ){
747
1140
    int e = errno;
817
1210
    goto mandos_end;
818
1211
  }
819
1212
  
820
 
  if(af == AF_INET6){
821
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
822
 
                  sizeof(struct sockaddr_in6));
823
 
  } else {
824
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
825
 
                  sizeof(struct sockaddr_in));
826
 
  }
827
 
  if(ret < 0){
828
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
829
 
      int e = errno;
830
 
      perror_plus("connect");
831
 
      errno = e;
832
 
    }
833
 
    goto mandos_end;
834
 
  }
835
 
  
836
 
  if(quit_now){
837
 
    errno = EINTR;
838
 
    goto mandos_end;
 
1213
  while(true){
 
1214
    if(af == AF_INET6){
 
1215
      ret = connect(tcp_sd, (struct sockaddr *)&to,
 
1216
                    sizeof(struct sockaddr_in6));
 
1217
    } else {
 
1218
      ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
1219
                    sizeof(struct sockaddr_in));
 
1220
    }
 
1221
    if(ret < 0){
 
1222
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
 
1223
         and if_index != AVAHI_IF_UNSPEC
 
1224
         and connect_to == NULL
 
1225
         and not route_added and
 
1226
         ((af == AF_INET6 and not
 
1227
           IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
 
1228
                                    &to)->sin6_addr)))
 
1229
          or (af == AF_INET and
 
1230
              /* Not a a IPv4LL address */
 
1231
              (ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
 
1232
               & 0xFFFF0000L) != 0xA9FE0000L))){
 
1233
        /* Work around Avahi bug - Avahi does not announce link-local
 
1234
           addresses if it has a global address, so local hosts with
 
1235
           *only* a link-local address (e.g. Mandos clients) cannot
 
1236
           connect to a Mandos server announced by Avahi on a server
 
1237
           host with a global address.  Work around this by retrying
 
1238
           with an explicit route added with the server's address.
 
1239
           
 
1240
           Avahi bug reference:
 
1241
           https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
 
1242
           https://bugs.debian.org/587961
 
1243
        */
 
1244
        if(debug){
 
1245
          fprintf_plus(stderr, "Mandos server unreachable, trying"
 
1246
                       " direct route\n");
 
1247
        }
 
1248
        int e = errno;
 
1249
        route_added = add_local_route(ip, if_index);
 
1250
        if(route_added){
 
1251
          continue;
 
1252
        }
 
1253
        errno = e;
 
1254
      }
 
1255
      if(errno != ECONNREFUSED or debug){
 
1256
        int e = errno;
 
1257
        perror_plus("connect");
 
1258
        errno = e;
 
1259
      }
 
1260
      goto mandos_end;
 
1261
    }
 
1262
    
 
1263
    if(quit_now){
 
1264
      errno = EINTR;
 
1265
      goto mandos_end;
 
1266
    }
 
1267
    break;
839
1268
  }
840
1269
  
841
1270
  const char *out = mandos_protocol_version;
995
1424
                                               &decrypted_buffer, mc);
996
1425
    if(decrypted_buffer_size >= 0){
997
1426
      
 
1427
      clearerr(stdout);
998
1428
      written = 0;
999
1429
      while(written < (size_t) decrypted_buffer_size){
1000
1430
        if(quit_now){
1016
1446
        }
1017
1447
        written += (size_t)ret;
1018
1448
      }
 
1449
      ret = fflush(stdout);
 
1450
      if(ret != 0){
 
1451
        int e = errno;
 
1452
        if(debug){
 
1453
          fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
1454
                       strerror(errno));
 
1455
        }
 
1456
        errno = e;
 
1457
        goto mandos_end;
 
1458
      }
1019
1459
      retval = 0;
1020
1460
    }
1021
1461
  }
1024
1464
  
1025
1465
 mandos_end:
1026
1466
  {
 
1467
    if(route_added){
 
1468
      if(not delete_local_route(ip, if_index)){
 
1469
        fprintf_plus(stderr, "Failed to delete local route to %s on"
 
1470
                     " interface %d", ip, if_index);
 
1471
      }
 
1472
    }
1027
1473
    int e = errno;
1028
1474
    free(decrypted_buffer);
1029
1475
    free(buffer);
1030
1476
    if(tcp_sd >= 0){
1031
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
1477
      ret = close(tcp_sd);
1032
1478
    }
1033
1479
    if(ret == -1){
1034
1480
      if(e == 0){
1069
1515
     timed out */
1070
1516
  
1071
1517
  if(quit_now){
 
1518
    avahi_s_service_resolver_free(r);
1072
1519
    return;
1073
1520
  }
1074
1521
  
1188
1635
__attribute__((nonnull, warn_unused_result))
1189
1636
bool get_flags(const char *ifname, struct ifreq *ifr){
1190
1637
  int ret;
1191
 
  error_t ret_errno;
 
1638
  int old_errno;
1192
1639
  
1193
1640
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1194
1641
  if(s < 0){
1195
 
    ret_errno = errno;
 
1642
    old_errno = errno;
1196
1643
    perror_plus("socket");
1197
 
    errno = ret_errno;
 
1644
    errno = old_errno;
1198
1645
    return false;
1199
1646
  }
1200
 
  strcpy(ifr->ifr_name, ifname);
 
1647
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
 
1648
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1201
1649
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1202
1650
  if(ret == -1){
1203
1651
    if(debug){
1204
 
      ret_errno = errno;
 
1652
      old_errno = errno;
1205
1653
      perror_plus("ioctl SIOCGIFFLAGS");
1206
 
      errno = ret_errno;
 
1654
      errno = old_errno;
1207
1655
    }
1208
1656
    return false;
1209
1657
  }
1454
1902
  }
1455
1903
}
1456
1904
 
1457
 
/* Set effective uid to 0, return errno */
1458
 
__attribute__((warn_unused_result))
1459
 
error_t raise_privileges(void){
1460
 
  error_t old_errno = errno;
1461
 
  error_t ret_errno = 0;
1462
 
  if(seteuid(0) == -1){
1463
 
    ret_errno = errno;
1464
 
  }
1465
 
  errno = old_errno;
1466
 
  return ret_errno;
1467
 
}
1468
 
 
1469
 
/* Set effective and real user ID to 0.  Return errno. */
1470
 
__attribute__((warn_unused_result))
1471
 
error_t raise_privileges_permanently(void){
1472
 
  error_t old_errno = errno;
1473
 
  error_t ret_errno = raise_privileges();
1474
 
  if(ret_errno != 0){
1475
 
    errno = old_errno;
1476
 
    return ret_errno;
1477
 
  }
1478
 
  if(setuid(0) == -1){
1479
 
    ret_errno = errno;
1480
 
  }
1481
 
  errno = old_errno;
1482
 
  return ret_errno;
1483
 
}
1484
 
 
1485
 
/* Set effective user ID to unprivileged saved user ID */
1486
 
__attribute__((warn_unused_result))
1487
 
error_t lower_privileges(void){
1488
 
  error_t old_errno = errno;
1489
 
  error_t ret_errno = 0;
1490
 
  if(seteuid(uid) == -1){
1491
 
    ret_errno = errno;
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
 
  }
1505
 
  errno = old_errno;
1506
 
  return ret_errno;
1507
 
}
1508
 
 
1509
1905
__attribute__((nonnull))
1510
1906
void run_network_hooks(const char *mode, const char *interface,
1511
1907
                       const float delay){
1512
1908
  struct dirent **direntries = NULL;
1513
1909
  if(hookdir_fd == -1){
1514
 
    hookdir_fd = open(hookdir, O_RDONLY);
 
1910
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
 
1911
                      | O_CLOEXEC);
1515
1912
    if(hookdir_fd == -1){
1516
1913
      if(errno == ENOENT){
1517
1914
        if(debug){
1524
1921
      return;
1525
1922
    }
1526
1923
  }
1527
 
#ifdef __GLIBC__
1528
 
#if __GLIBC_PREREQ(2, 15)
1529
1924
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1530
1925
                           runnable_hook, alphasort);
1531
 
#else  /* not __GLIBC_PREREQ(2, 15) */
1532
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1533
 
                         alphasort);
1534
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
1535
 
#else   /* not __GLIBC__ */
1536
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1537
 
                         alphasort);
1538
 
#endif  /* not __GLIBC__ */
1539
1926
  if(numhooks == -1){
1540
1927
    perror_plus("scandir");
1541
1928
    return;
1542
1929
  }
1543
1930
  struct dirent *direntry;
1544
1931
  int ret;
1545
 
  int devnull = open("/dev/null", O_RDONLY);
 
1932
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
1933
  if(devnull == -1){
 
1934
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
1935
    return;
 
1936
  }
1546
1937
  for(int i = 0; i < numhooks; i++){
1547
1938
    direntry = direntries[i];
1548
1939
    if(debug){
1572
1963
        perror_plus("setgroups");
1573
1964
        _exit(EX_NOPERM);
1574
1965
      }
1575
 
      ret = dup2(devnull, STDIN_FILENO);
1576
 
      if(ret == -1){
1577
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
1578
 
        _exit(EX_OSERR);
1579
 
      }
1580
 
      ret = close(devnull);
1581
 
      if(ret == -1){
1582
 
        perror_plus("close");
1583
 
        _exit(EX_OSERR);
1584
 
      }
1585
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1586
 
      if(ret == -1){
1587
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1588
 
        _exit(EX_OSERR);
1589
 
      }
1590
1966
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1591
1967
      if(ret == -1){
1592
1968
        perror_plus("setenv");
1627
2003
          _exit(EX_OSERR);
1628
2004
        }
1629
2005
      }
1630
 
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
 
2006
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
 
2007
                                                   direntry->d_name,
 
2008
                                                   O_RDONLY));
1631
2009
      if(hook_fd == -1){
1632
2010
        perror_plus("openat");
1633
2011
        _exit(EXIT_FAILURE);
1634
2012
      }
1635
 
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2013
      if(close(hookdir_fd) == -1){
1636
2014
        perror_plus("close");
1637
2015
        _exit(EXIT_FAILURE);
1638
2016
      }
 
2017
      ret = dup2(devnull, STDIN_FILENO);
 
2018
      if(ret == -1){
 
2019
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
2020
        _exit(EX_OSERR);
 
2021
      }
 
2022
      ret = close(devnull);
 
2023
      if(ret == -1){
 
2024
        perror_plus("close");
 
2025
        _exit(EX_OSERR);
 
2026
      }
 
2027
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
2028
      if(ret == -1){
 
2029
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
2030
        _exit(EX_OSERR);
 
2031
      }
1639
2032
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
1640
2033
                 environ) == -1){
1641
2034
        perror_plus("fexecve");
1642
2035
        _exit(EXIT_FAILURE);
1643
2036
      }
1644
2037
    } else {
 
2038
      if(hook_pid == -1){
 
2039
        perror_plus("fork");
 
2040
        free(direntry);
 
2041
        continue;
 
2042
      }
1645
2043
      int status;
1646
2044
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1647
2045
        perror_plus("waitpid");
 
2046
        free(direntry);
1648
2047
        continue;
1649
2048
      }
1650
2049
      if(WIFEXITED(status)){
1652
2051
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1653
2052
                       " with status %d\n", direntry->d_name,
1654
2053
                       WEXITSTATUS(status));
 
2054
          free(direntry);
1655
2055
          continue;
1656
2056
        }
1657
2057
      } else if(WIFSIGNALED(status)){
1658
2058
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1659
2059
                     " signal %d\n", direntry->d_name,
1660
2060
                     WTERMSIG(status));
 
2061
        free(direntry);
1661
2062
        continue;
1662
2063
      } else {
1663
2064
        fprintf_plus(stderr, "Warning: network hook \"%s\""
1664
2065
                     " crashed\n", direntry->d_name);
 
2066
        free(direntry);
1665
2067
        continue;
1666
2068
      }
1667
2069
    }
1669
2071
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1670
2072
                   direntry->d_name);
1671
2073
    }
 
2074
    free(direntry);
1672
2075
  }
1673
2076
  free(direntries);
1674
 
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2077
  if(close(hookdir_fd) == -1){
1675
2078
    perror_plus("close");
1676
2079
  } else {
1677
2080
    hookdir_fd = -1;
1680
2083
}
1681
2084
 
1682
2085
__attribute__((nonnull, warn_unused_result))
1683
 
error_t bring_up_interface(const char *const interface,
1684
 
                           const float delay){
1685
 
  error_t old_errno = errno;
 
2086
int bring_up_interface(const char *const interface,
 
2087
                       const float delay){
 
2088
  int old_errno = errno;
1686
2089
  int ret;
1687
2090
  struct ifreq network;
1688
2091
  unsigned int if_index = if_nametoindex(interface);
1698
2101
  }
1699
2102
  
1700
2103
  if(not interface_is_up(interface)){
1701
 
    error_t ret_errno = 0, ioctl_errno = 0;
 
2104
    int ret_errno = 0;
 
2105
    int ioctl_errno = 0;
1702
2106
    if(not get_flags(interface, &network)){
1703
2107
      ret_errno = errno;
1704
2108
      fprintf_plus(stderr, "Failed to get flags for interface "
1717
2121
    }
1718
2122
    
1719
2123
    if(quit_now){
1720
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2124
      ret = close(sd);
1721
2125
      if(ret == -1){
1722
2126
        perror_plus("close");
1723
2127
      }
1773
2177
    }
1774
2178
    
1775
2179
    /* Close the socket */
1776
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2180
    ret = close(sd);
1777
2181
    if(ret == -1){
1778
2182
      perror_plus("close");
1779
2183
    }
1807
2211
}
1808
2212
 
1809
2213
__attribute__((nonnull, warn_unused_result))
1810
 
error_t take_down_interface(const char *const interface){
1811
 
  error_t old_errno = errno;
 
2214
int take_down_interface(const char *const interface){
 
2215
  int old_errno = errno;
1812
2216
  struct ifreq network;
1813
2217
  unsigned int if_index = if_nametoindex(interface);
1814
2218
  if(if_index == 0){
1817
2221
    return ENXIO;
1818
2222
  }
1819
2223
  if(interface_is_up(interface)){
1820
 
    error_t ret_errno = 0, ioctl_errno = 0;
 
2224
    int ret_errno = 0;
 
2225
    int ioctl_errno = 0;
1821
2226
    if(not get_flags(interface, &network) and debug){
1822
2227
      ret_errno = errno;
1823
2228
      fprintf_plus(stderr, "Failed to get flags for interface "
1861
2266
    }
1862
2267
    
1863
2268
    /* Close the socket */
1864
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2269
    int ret = close(sd);
1865
2270
    if(ret == -1){
1866
2271
      perror_plus("close");
1867
2272
    }
1882
2287
}
1883
2288
 
1884
2289
int main(int argc, char *argv[]){
1885
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1886
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1887
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1888
 
                        .interfaces = NULL, .interfaces_size = 0 };
 
2290
  mandos_context mc = { .server = NULL, .dh_bits = 0,
 
2291
                        .priority = "SECURE256:!CTYPE-X.509"
 
2292
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
 
2293
                        .current_server = NULL, .interfaces = NULL,
 
2294
                        .interfaces_size = 0 };
1889
2295
  AvahiSServiceBrowser *sb = NULL;
1890
2296
  error_t ret_errno;
1891
2297
  int ret;
1900
2306
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1901
2307
  const char *seckey = PATHDIR "/" SECKEY;
1902
2308
  const char *pubkey = PATHDIR "/" PUBKEY;
 
2309
  const char *dh_params_file = NULL;
1903
2310
  char *interfaces_hooks = NULL;
1904
2311
  
1905
2312
  bool gnutls_initialized = false;
1958
2365
        .doc = "Bit length of the prime number used in the"
1959
2366
        " Diffie-Hellman key exchange",
1960
2367
        .group = 2 },
 
2368
      { .name = "dh-params", .key = 134,
 
2369
        .arg = "FILE",
 
2370
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
 
2371
        " for the Diffie-Hellman key exchange",
 
2372
        .group = 2 },
1961
2373
      { .name = "priority", .key = 130,
1962
2374
        .arg = "STRING",
1963
2375
        .doc = "GnuTLS priority string for the TLS handshake",
2018
2430
        }
2019
2431
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2020
2432
        break;
 
2433
      case 134:                 /* --dh-params */
 
2434
        dh_params_file = arg;
 
2435
        break;
2021
2436
      case 130:                 /* --priority */
2022
2437
        mc.priority = arg;
2023
2438
        break;
2063
2478
                         .args_doc = "",
2064
2479
                         .doc = "Mandos client -- Get and decrypt"
2065
2480
                         " passwords from a Mandos server" };
2066
 
    ret = argp_parse(&argp, argc, argv,
2067
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2068
 
    switch(ret){
 
2481
    ret_errno = argp_parse(&argp, argc, argv,
 
2482
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2483
    switch(ret_errno){
2069
2484
    case 0:
2070
2485
      break;
2071
2486
    case ENOMEM:
2072
2487
    default:
2073
 
      errno = ret;
 
2488
      errno = ret_errno;
2074
2489
      perror_plus("argp_parse");
2075
2490
      exitcode = EX_OSERR;
2076
2491
      goto end;
2079
2494
      goto end;
2080
2495
    }
2081
2496
  }
2082
 
    
 
2497
  
2083
2498
  {
2084
2499
    /* Work around Debian bug #633582:
2085
 
       <http://bugs.debian.org/633582> */
 
2500
       <https://bugs.debian.org/633582> */
2086
2501
    
2087
2502
    /* Re-raise privileges */
2088
 
    ret_errno = raise_privileges();
2089
 
    if(ret_errno != 0){
2090
 
      errno = ret_errno;
 
2503
    ret = raise_privileges();
 
2504
    if(ret != 0){
 
2505
      errno = ret;
2091
2506
      perror_plus("Failed to raise privileges");
2092
2507
    } else {
2093
2508
      struct stat st;
2109
2524
              }
2110
2525
            }
2111
2526
          }
2112
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2527
          close(seckey_fd);
2113
2528
        }
2114
2529
      }
2115
 
    
 
2530
      
2116
2531
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2117
2532
        int pubkey_fd = open(pubkey, O_RDONLY);
2118
2533
        if(pubkey_fd == -1){
2130
2545
              }
2131
2546
            }
2132
2547
          }
2133
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
2134
 
        }
2135
 
      }
2136
 
    
 
2548
          close(pubkey_fd);
 
2549
        }
 
2550
      }
 
2551
      
 
2552
      if(dh_params_file != NULL
 
2553
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
 
2554
        int dhparams_fd = open(dh_params_file, O_RDONLY);
 
2555
        if(dhparams_fd == -1){
 
2556
          perror_plus("open");
 
2557
        } else {
 
2558
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
 
2559
          if(ret == -1){
 
2560
            perror_plus("fstat");
 
2561
          } else {
 
2562
            if(S_ISREG(st.st_mode)
 
2563
               and st.st_uid == 0 and st.st_gid == 0){
 
2564
              ret = fchown(dhparams_fd, uid, gid);
 
2565
              if(ret == -1){
 
2566
                perror_plus("fchown");
 
2567
              }
 
2568
            }
 
2569
          }
 
2570
          close(dhparams_fd);
 
2571
        }
 
2572
      }
 
2573
      
2137
2574
      /* Lower privileges */
2138
 
      ret_errno = lower_privileges();
2139
 
      if(ret_errno != 0){
2140
 
        errno = ret_errno;
 
2575
      ret = lower_privileges();
 
2576
      if(ret != 0){
 
2577
        errno = ret;
2141
2578
        perror_plus("Failed to lower privileges");
2142
2579
      }
2143
2580
    }
2268
2705
        if(ret_errno != 0){
2269
2706
          errno = ret_errno;
2270
2707
          perror_plus("argz_add");
 
2708
          free(direntries[i]);
2271
2709
          continue;
2272
2710
        }
2273
2711
        if(debug){
2274
2712
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2275
2713
                       direntries[i]->d_name);
2276
2714
        }
 
2715
        free(direntries[i]);
2277
2716
      }
2278
2717
      free(direntries);
2279
2718
    } else {
2311
2750
      errno = bring_up_interface(interface, delay);
2312
2751
      if(not interface_was_up){
2313
2752
        if(errno != 0){
2314
 
          perror_plus("Failed to bring up interface");
 
2753
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
 
2754
                       " %s\n", interface, strerror(errno));
2315
2755
        } else {
2316
2756
          errno = argz_add(&interfaces_to_take_down,
2317
2757
                           &interfaces_to_take_down_size,
2340
2780
    goto end;
2341
2781
  }
2342
2782
  
2343
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2783
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
2344
2784
  if(ret == -1){
2345
2785
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2346
2786
    exitcode = EX_UNAVAILABLE;
2468
2908
    
2469
2909
    /* Allocate a new server */
2470
2910
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2471
 
                                 &config, NULL, NULL, &ret_errno);
 
2911
                                 &config, NULL, NULL, &ret);
2472
2912
    
2473
2913
    /* Free the Avahi configuration data */
2474
2914
    avahi_server_config_free(&config);
2477
2917
  /* Check if creating the Avahi server object succeeded */
2478
2918
  if(mc.server == NULL){
2479
2919
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2480
 
                 avahi_strerror(ret_errno));
 
2920
                 avahi_strerror(ret));
2481
2921
    exitcode = EX_UNAVAILABLE;
2482
2922
    goto end;
2483
2923
  }
2518
2958
 end:
2519
2959
  
2520
2960
  if(debug){
2521
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2961
    if(signal_received){
 
2962
      fprintf_plus(stderr, "%s exiting due to signal %d: %s\n",
 
2963
                   argv[0], signal_received,
 
2964
                   strsignal(signal_received));
 
2965
    } else {
 
2966
      fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2967
    }
2522
2968
  }
2523
2969
  
2524
2970
  /* Cleanup things */
2535
2981
  
2536
2982
  if(gnutls_initialized){
2537
2983
    gnutls_certificate_free_credentials(mc.cred);
2538
 
    gnutls_global_deinit();
2539
2984
    gnutls_dh_params_deinit(mc.dh_params);
2540
2985
  }
2541
2986
  
2549
2994
    mc.current_server->prev->next = NULL;
2550
2995
    while(mc.current_server != NULL){
2551
2996
      server *next = mc.current_server->next;
 
2997
#ifdef __GNUC__
 
2998
#pragma GCC diagnostic push
 
2999
#pragma GCC diagnostic ignored "-Wcast-qual"
 
3000
#endif
 
3001
      free((char *)(mc.current_server->ip));
 
3002
#ifdef __GNUC__
 
3003
#pragma GCC diagnostic pop
 
3004
#endif
2552
3005
      free(mc.current_server);
2553
3006
      mc.current_server = next;
2554
3007
    }
2556
3009
  
2557
3010
  /* Re-raise privileges */
2558
3011
  {
2559
 
    ret_errno = raise_privileges();
2560
 
    if(ret_errno != 0){
2561
 
      errno = ret_errno;
 
3012
    ret = raise_privileges();
 
3013
    if(ret != 0){
 
3014
      errno = ret;
2562
3015
      perror_plus("Failed to raise privileges");
2563
3016
    } else {
2564
3017
      
2572
3025
        while((interface=argz_next(interfaces_to_take_down,
2573
3026
                                   interfaces_to_take_down_size,
2574
3027
                                   interface))){
2575
 
          ret_errno = take_down_interface(interface);
2576
 
          if(ret_errno != 0){
2577
 
            errno = ret_errno;
 
3028
          ret = take_down_interface(interface);
 
3029
          if(ret != 0){
 
3030
            errno = ret;
2578
3031
            perror_plus("Failed to take down interface");
2579
3032
          }
2580
3033
        }
2585
3038
      }
2586
3039
    }
2587
3040
    
2588
 
    ret_errno = lower_privileges_permanently();
2589
 
    if(ret_errno != 0){
2590
 
      errno = ret_errno;
 
3041
    ret = lower_privileges_permanently();
 
3042
    if(ret != 0){
 
3043
      errno = ret;
2591
3044
      perror_plus("Failed to lower privileges permanently");
2592
3045
    }
2593
3046
  }
2595
3048
  free(interfaces_to_take_down);
2596
3049
  free(interfaces_hooks);
2597
3050
  
 
3051
  void clean_dir_at(int base, const char * const dirname,
 
3052
                    uintmax_t level){
 
3053
    struct dirent **direntries = NULL;
 
3054
    int dret;
 
3055
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
 
3056
                                                O_RDONLY
 
3057
                                                | O_NOFOLLOW
 
3058
                                                | O_DIRECTORY
 
3059
                                                | O_PATH));
 
3060
    if(dir_fd == -1){
 
3061
      perror_plus("open");
 
3062
    }
 
3063
    int numentries = scandirat(dir_fd, ".", &direntries,
 
3064
                               notdotentries, alphasort);
 
3065
    if(numentries >= 0){
 
3066
      for(int i = 0; i < numentries; i++){
 
3067
        if(debug){
 
3068
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
 
3069
                       dirname, direntries[i]->d_name);
 
3070
        }
 
3071
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
 
3072
        if(dret == -1){
 
3073
          if(errno == EISDIR){
 
3074
              dret = unlinkat(dir_fd, direntries[i]->d_name,
 
3075
                              AT_REMOVEDIR);
 
3076
          }         
 
3077
          if((dret == -1) and (errno == ENOTEMPTY)
 
3078
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
 
3079
                  == 0) and (level == 0)){
 
3080
            /* Recurse only in this special case */
 
3081
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
 
3082
            dret = 0;
 
3083
          }
 
3084
          if(dret == -1){
 
3085
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
 
3086
                         direntries[i]->d_name, strerror(errno));
 
3087
          }
 
3088
        }
 
3089
        free(direntries[i]);
 
3090
      }
 
3091
      
 
3092
      /* need to clean even if 0 because man page doesn't specify */
 
3093
      free(direntries);
 
3094
      if(numentries == -1){
 
3095
        perror_plus("scandirat");
 
3096
      }
 
3097
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
 
3098
      if(dret == -1 and errno != ENOENT){
 
3099
        perror_plus("rmdir");
 
3100
      }
 
3101
    } else {
 
3102
      perror_plus("scandirat");
 
3103
    }
 
3104
    close(dir_fd);
 
3105
  }
 
3106
  
2598
3107
  /* Removes the GPGME temp directory and all files inside */
2599
3108
  if(tempdir != NULL){
2600
 
    struct dirent **direntries = NULL;
2601
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY |
2602
 
                                                  O_NOFOLLOW));
2603
 
    if(tempdir_fd == -1){
2604
 
      perror_plus("open");
2605
 
    } else {
2606
 
#ifdef __GLIBC__
2607
 
#if __GLIBC_PREREQ(2, 15)
2608
 
      int numentries = scandirat(tempdir_fd, ".", &direntries,
2609
 
                                 notdotentries, alphasort);
2610
 
#else  /* not __GLIBC_PREREQ(2, 15) */
2611
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2612
 
                               alphasort);
2613
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
2614
 
#else   /* not __GLIBC__ */
2615
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2616
 
                               alphasort);
2617
 
#endif  /* not __GLIBC__ */
2618
 
      if(numentries >= 0){
2619
 
        for(int i = 0; i < numentries; i++){
2620
 
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
2621
 
          if(ret == -1){
2622
 
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
2623
 
                         " \"%s\", 0): %s\n", tempdir,
2624
 
                         direntries[i]->d_name, strerror(errno));
2625
 
          }
2626
 
        }
2627
 
        
2628
 
        /* need to clean even if 0 because man page doesn't specify */
2629
 
        free(direntries);
2630
 
        if(numentries == -1){
2631
 
          perror_plus("scandir");
2632
 
        }
2633
 
        ret = rmdir(tempdir);
2634
 
        if(ret == -1 and errno != ENOENT){
2635
 
          perror_plus("rmdir");
2636
 
        }
2637
 
      }
2638
 
      TEMP_FAILURE_RETRY(close(tempdir_fd));
2639
 
    }
 
3109
    clean_dir_at(-1, tempdir, 0);
2640
3110
  }
2641
3111
  
2642
3112
  if(quit_now){