/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: 2014-07-13 20:37:44 UTC
  • mfrom: (237.7.258 trunk)
  • Revision ID: teddy@recompile.se-20140713203744-538hqhk81vw9dixv
Merge from trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2016 Teddy Hogeborn
13
 
 * Copyright © 2008-2016 Björn Påhlsson
 
12
 * Copyright © 2008-2014 Teddy Hogeborn
 
13
 * Copyright © 2008-2014 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
48
48
#include <stdbool.h>            /* bool, false, true */
49
 
#include <string.h>             /* strcmp(), strlen(), strerror(),
50
 
                                   asprintf(), strncpy(), strsignal()
51
 
                                */
 
49
#include <string.h>             /* memset(), strcmp(), strlen(),
 
50
                                   strerror(), asprintf(), strcpy() */
52
51
#include <sys/ioctl.h>          /* ioctl */
53
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
54
53
                                   sockaddr_in6, PF_INET6,
58
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
59
58
                                   inet_pton(), connect(),
60
59
                                   getnameinfo() */
61
 
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
 
60
#include <fcntl.h>              /* open(), unlinkat() */
62
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
63
62
                                 */
64
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
65
64
                                   strtoimax() */
66
 
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
67
 
                                   EAI_SYSTEM, ENETUNREACH,
68
 
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
69
 
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
70
 
                                   ENOTEMPTY,
 
65
#include <errno.h>              /* perror(), errno,
71
66
                                   program_invocation_short_name */
72
67
#include <time.h>               /* nanosleep(), time(), sleep() */
73
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
245
240
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
246
241
  if(ret == -1){
247
242
    perror_plus("clock_gettime");
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
 
243
    free(new_server->ip);
256
244
    free(new_server);
257
245
    return false;
258
246
  }
310
298
      return false;
311
299
    }
312
300
    
313
 
    ret = close(fd);
 
301
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
314
302
    if(ret == -1){
315
303
      perror_plus("close");
316
304
    }
498
486
  return plaintext_length;
499
487
}
500
488
 
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
 
 
508
489
__attribute__((warn_unused_result))
509
490
static const char *safer_gnutls_strerror(int value){
510
491
  const char *ret = gnutls_strerror(value);
511
 
  return safe_string(ret);
 
492
  if(ret == NULL)
 
493
    ret = "(unknown)";
 
494
  return ret;
512
495
}
513
496
 
514
497
/* GnuTLS log function callback */
518
501
  fprintf_plus(stderr, "GnuTLS: %s", string);
519
502
}
520
503
 
521
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
 
504
__attribute__((nonnull, warn_unused_result))
522
505
static int init_gnutls_global(const char *pubkeyfilename,
523
506
                              const char *seckeyfilename,
524
 
                              const char *dhparamsfilename,
525
507
                              mandos_context *mc){
526
508
  int ret;
527
 
  unsigned int uret;
528
509
  
529
510
  if(debug){
530
511
    fprintf_plus(stderr, "Initializing GnuTLS\n");
531
512
  }
532
513
  
 
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
  
533
521
  if(debug){
534
522
    /* "Use a log level over 10 to enable all debugging options."
535
523
     * - GnuTLS manual
543
531
  if(ret != GNUTLS_E_SUCCESS){
544
532
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
545
533
                 safer_gnutls_strerror(ret));
 
534
    gnutls_global_deinit();
546
535
    return -1;
547
536
  }
548
537
  
573
562
                 safer_gnutls_strerror(ret));
574
563
    goto globalfail;
575
564
  }
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
 
  }
 
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
  
748
572
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
749
573
  
750
574
  return 0;
752
576
 globalfail:
753
577
  
754
578
  gnutls_certificate_free_credentials(mc->cred);
 
579
  gnutls_global_deinit();
755
580
  gnutls_dh_params_deinit(mc->dh_params);
756
581
  return -1;
757
582
}
809
634
  /* ignore client certificate if any. */
810
635
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
811
636
  
 
637
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
638
  
812
639
  return 0;
813
640
}
814
641
 
816
643
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
817
644
                      __attribute__((unused)) const char *txt){}
818
645
 
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
 
 
1037
646
/* Called when a Mandos server is found */
1038
647
__attribute__((nonnull, warn_unused_result))
1039
648
static int start_mandos_communication(const char *ip, in_port_t port,
1050
659
  int retval = -1;
1051
660
  gnutls_session_t session;
1052
661
  int pf;                       /* Protocol family */
1053
 
  bool route_added = false;
1054
662
  
1055
663
  errno = 0;
1056
664
  
1114
722
                 PRIuMAX "\n", ip, (uintmax_t)port);
1115
723
  }
1116
724
  
1117
 
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
 
725
  tcp_sd = socket(pf, SOCK_STREAM, 0);
1118
726
  if(tcp_sd < 0){
1119
727
    int e = errno;
1120
728
    perror_plus("socket");
1127
735
    goto mandos_end;
1128
736
  }
1129
737
  
 
738
  memset(&to, 0, sizeof(to));
1130
739
  if(af == AF_INET6){
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);
 
740
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
741
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
1134
742
  } else {                      /* IPv4 */
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);
 
743
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
744
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
1138
745
  }
1139
746
  if(ret < 0 ){
1140
747
    int e = errno;
1210
817
    goto mandos_end;
1211
818
  }
1212
819
  
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;
 
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;
1268
839
  }
1269
840
  
1270
841
  const char *out = mandos_protocol_version;
1424
995
                                               &decrypted_buffer, mc);
1425
996
    if(decrypted_buffer_size >= 0){
1426
997
      
1427
 
      clearerr(stdout);
1428
998
      written = 0;
1429
999
      while(written < (size_t) decrypted_buffer_size){
1430
1000
        if(quit_now){
1446
1016
        }
1447
1017
        written += (size_t)ret;
1448
1018
      }
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
 
      }
1459
1019
      retval = 0;
1460
1020
    }
1461
1021
  }
1464
1024
  
1465
1025
 mandos_end:
1466
1026
  {
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
 
    }
1473
1027
    int e = errno;
1474
1028
    free(decrypted_buffer);
1475
1029
    free(buffer);
1476
1030
    if(tcp_sd >= 0){
1477
 
      ret = close(tcp_sd);
 
1031
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1478
1032
    }
1479
1033
    if(ret == -1){
1480
1034
      if(e == 0){
1515
1069
     timed out */
1516
1070
  
1517
1071
  if(quit_now){
1518
 
    avahi_s_service_resolver_free(r);
1519
1072
    return;
1520
1073
  }
1521
1074
  
1635
1188
__attribute__((nonnull, warn_unused_result))
1636
1189
bool get_flags(const char *ifname, struct ifreq *ifr){
1637
1190
  int ret;
1638
 
  int old_errno;
 
1191
  error_t ret_errno;
1639
1192
  
1640
1193
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1641
1194
  if(s < 0){
1642
 
    old_errno = errno;
 
1195
    ret_errno = errno;
1643
1196
    perror_plus("socket");
1644
 
    errno = old_errno;
 
1197
    errno = ret_errno;
1645
1198
    return false;
1646
1199
  }
1647
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1648
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
 
1200
  strcpy(ifr->ifr_name, ifname);
1649
1201
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1650
1202
  if(ret == -1){
1651
1203
    if(debug){
1652
 
      old_errno = errno;
 
1204
      ret_errno = errno;
1653
1205
      perror_plus("ioctl SIOCGIFFLAGS");
1654
 
      errno = old_errno;
 
1206
      errno = ret_errno;
1655
1207
    }
1656
1208
    return false;
1657
1209
  }
1902
1454
  }
1903
1455
}
1904
1456
 
 
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
 
1905
1509
__attribute__((nonnull))
1906
1510
void run_network_hooks(const char *mode, const char *interface,
1907
1511
                       const float delay){
1908
1512
  struct dirent **direntries = NULL;
1909
1513
  if(hookdir_fd == -1){
1910
 
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
1911
 
                      | O_CLOEXEC);
 
1514
    hookdir_fd = open(hookdir, O_RDONLY);
1912
1515
    if(hookdir_fd == -1){
1913
1516
      if(errno == ENOENT){
1914
1517
        if(debug){
1921
1524
      return;
1922
1525
    }
1923
1526
  }
 
1527
#ifdef __GLIBC__
 
1528
#if __GLIBC_PREREQ(2, 15)
1924
1529
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1925
1530
                           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__ */
1926
1539
  if(numhooks == -1){
1927
1540
    perror_plus("scandir");
1928
1541
    return;
1929
1542
  }
1930
1543
  struct dirent *direntry;
1931
1544
  int ret;
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
 
  }
 
1545
  int devnull = open("/dev/null", O_RDONLY);
1937
1546
  for(int i = 0; i < numhooks; i++){
1938
1547
    direntry = direntries[i];
1939
1548
    if(debug){
1963
1572
        perror_plus("setgroups");
1964
1573
        _exit(EX_NOPERM);
1965
1574
      }
 
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
      }
1966
1590
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1967
1591
      if(ret == -1){
1968
1592
        perror_plus("setenv");
2003
1627
          _exit(EX_OSERR);
2004
1628
        }
2005
1629
      }
2006
 
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
2007
 
                                                   direntry->d_name,
2008
 
                                                   O_RDONLY));
 
1630
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
2009
1631
      if(hook_fd == -1){
2010
1632
        perror_plus("openat");
2011
1633
        _exit(EXIT_FAILURE);
2012
1634
      }
2013
 
      if(close(hookdir_fd) == -1){
 
1635
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2014
1636
        perror_plus("close");
2015
1637
        _exit(EXIT_FAILURE);
2016
1638
      }
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
 
      }
2032
1639
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
2033
1640
                 environ) == -1){
2034
1641
        perror_plus("fexecve");
2035
1642
        _exit(EXIT_FAILURE);
2036
1643
      }
2037
1644
    } else {
2038
 
      if(hook_pid == -1){
2039
 
        perror_plus("fork");
2040
 
        free(direntry);
2041
 
        continue;
2042
 
      }
2043
1645
      int status;
2044
1646
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
2045
1647
        perror_plus("waitpid");
2046
 
        free(direntry);
2047
1648
        continue;
2048
1649
      }
2049
1650
      if(WIFEXITED(status)){
2051
1652
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
2052
1653
                       " with status %d\n", direntry->d_name,
2053
1654
                       WEXITSTATUS(status));
2054
 
          free(direntry);
2055
1655
          continue;
2056
1656
        }
2057
1657
      } else if(WIFSIGNALED(status)){
2058
1658
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
2059
1659
                     " signal %d\n", direntry->d_name,
2060
1660
                     WTERMSIG(status));
2061
 
        free(direntry);
2062
1661
        continue;
2063
1662
      } else {
2064
1663
        fprintf_plus(stderr, "Warning: network hook \"%s\""
2065
1664
                     " crashed\n", direntry->d_name);
2066
 
        free(direntry);
2067
1665
        continue;
2068
1666
      }
2069
1667
    }
2071
1669
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
2072
1670
                   direntry->d_name);
2073
1671
    }
2074
 
    free(direntry);
2075
1672
  }
2076
1673
  free(direntries);
2077
 
  if(close(hookdir_fd) == -1){
 
1674
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2078
1675
    perror_plus("close");
2079
1676
  } else {
2080
1677
    hookdir_fd = -1;
2083
1680
}
2084
1681
 
2085
1682
__attribute__((nonnull, warn_unused_result))
2086
 
int bring_up_interface(const char *const interface,
2087
 
                       const float delay){
2088
 
  int old_errno = errno;
 
1683
error_t bring_up_interface(const char *const interface,
 
1684
                           const float delay){
 
1685
  error_t old_errno = errno;
2089
1686
  int ret;
2090
1687
  struct ifreq network;
2091
1688
  unsigned int if_index = if_nametoindex(interface);
2101
1698
  }
2102
1699
  
2103
1700
  if(not interface_is_up(interface)){
2104
 
    int ret_errno = 0;
2105
 
    int ioctl_errno = 0;
 
1701
    error_t ret_errno = 0, ioctl_errno = 0;
2106
1702
    if(not get_flags(interface, &network)){
2107
1703
      ret_errno = errno;
2108
1704
      fprintf_plus(stderr, "Failed to get flags for interface "
2121
1717
    }
2122
1718
    
2123
1719
    if(quit_now){
2124
 
      ret = close(sd);
 
1720
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2125
1721
      if(ret == -1){
2126
1722
        perror_plus("close");
2127
1723
      }
2177
1773
    }
2178
1774
    
2179
1775
    /* Close the socket */
2180
 
    ret = close(sd);
 
1776
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
2181
1777
    if(ret == -1){
2182
1778
      perror_plus("close");
2183
1779
    }
2211
1807
}
2212
1808
 
2213
1809
__attribute__((nonnull, warn_unused_result))
2214
 
int take_down_interface(const char *const interface){
2215
 
  int old_errno = errno;
 
1810
error_t take_down_interface(const char *const interface){
 
1811
  error_t old_errno = errno;
2216
1812
  struct ifreq network;
2217
1813
  unsigned int if_index = if_nametoindex(interface);
2218
1814
  if(if_index == 0){
2221
1817
    return ENXIO;
2222
1818
  }
2223
1819
  if(interface_is_up(interface)){
2224
 
    int ret_errno = 0;
2225
 
    int ioctl_errno = 0;
 
1820
    error_t ret_errno = 0, ioctl_errno = 0;
2226
1821
    if(not get_flags(interface, &network) and debug){
2227
1822
      ret_errno = errno;
2228
1823
      fprintf_plus(stderr, "Failed to get flags for interface "
2266
1861
    }
2267
1862
    
2268
1863
    /* Close the socket */
2269
 
    int ret = close(sd);
 
1864
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
2270
1865
    if(ret == -1){
2271
1866
      perror_plus("close");
2272
1867
    }
2287
1882
}
2288
1883
 
2289
1884
int main(int argc, char *argv[]){
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 };
 
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 };
2295
1889
  AvahiSServiceBrowser *sb = NULL;
2296
1890
  error_t ret_errno;
2297
1891
  int ret;
2306
1900
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2307
1901
  const char *seckey = PATHDIR "/" SECKEY;
2308
1902
  const char *pubkey = PATHDIR "/" PUBKEY;
2309
 
  const char *dh_params_file = NULL;
2310
1903
  char *interfaces_hooks = NULL;
2311
1904
  
2312
1905
  bool gnutls_initialized = false;
2365
1958
        .doc = "Bit length of the prime number used in the"
2366
1959
        " Diffie-Hellman key exchange",
2367
1960
        .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 },
2373
1961
      { .name = "priority", .key = 130,
2374
1962
        .arg = "STRING",
2375
1963
        .doc = "GnuTLS priority string for the TLS handshake",
2430
2018
        }
2431
2019
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2432
2020
        break;
2433
 
      case 134:                 /* --dh-params */
2434
 
        dh_params_file = arg;
2435
 
        break;
2436
2021
      case 130:                 /* --priority */
2437
2022
        mc.priority = arg;
2438
2023
        break;
2478
2063
                         .args_doc = "",
2479
2064
                         .doc = "Mandos client -- Get and decrypt"
2480
2065
                         " passwords from a Mandos server" };
2481
 
    ret_errno = argp_parse(&argp, argc, argv,
2482
 
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2483
 
    switch(ret_errno){
 
2066
    ret = argp_parse(&argp, argc, argv,
 
2067
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2068
    switch(ret){
2484
2069
    case 0:
2485
2070
      break;
2486
2071
    case ENOMEM:
2487
2072
    default:
2488
 
      errno = ret_errno;
 
2073
      errno = ret;
2489
2074
      perror_plus("argp_parse");
2490
2075
      exitcode = EX_OSERR;
2491
2076
      goto end;
2494
2079
      goto end;
2495
2080
    }
2496
2081
  }
2497
 
  
 
2082
    
2498
2083
  {
2499
2084
    /* Work around Debian bug #633582:
2500
 
       <https://bugs.debian.org/633582> */
 
2085
       <http://bugs.debian.org/633582> */
2501
2086
    
2502
2087
    /* Re-raise privileges */
2503
 
    ret = raise_privileges();
2504
 
    if(ret != 0){
2505
 
      errno = ret;
 
2088
    ret_errno = raise_privileges();
 
2089
    if(ret_errno != 0){
 
2090
      errno = ret_errno;
2506
2091
      perror_plus("Failed to raise privileges");
2507
2092
    } else {
2508
2093
      struct stat st;
2524
2109
              }
2525
2110
            }
2526
2111
          }
2527
 
          close(seckey_fd);
 
2112
          TEMP_FAILURE_RETRY(close(seckey_fd));
2528
2113
        }
2529
2114
      }
2530
 
      
 
2115
    
2531
2116
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2532
2117
        int pubkey_fd = open(pubkey, O_RDONLY);
2533
2118
        if(pubkey_fd == -1){
2545
2130
              }
2546
2131
            }
2547
2132
          }
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
 
      
 
2133
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2134
        }
 
2135
      }
 
2136
    
2574
2137
      /* Lower privileges */
2575
 
      ret = lower_privileges();
2576
 
      if(ret != 0){
2577
 
        errno = ret;
 
2138
      ret_errno = lower_privileges();
 
2139
      if(ret_errno != 0){
 
2140
        errno = ret_errno;
2578
2141
        perror_plus("Failed to lower privileges");
2579
2142
      }
2580
2143
    }
2705
2268
        if(ret_errno != 0){
2706
2269
          errno = ret_errno;
2707
2270
          perror_plus("argz_add");
2708
 
          free(direntries[i]);
2709
2271
          continue;
2710
2272
        }
2711
2273
        if(debug){
2712
2274
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2713
2275
                       direntries[i]->d_name);
2714
2276
        }
2715
 
        free(direntries[i]);
2716
2277
      }
2717
2278
      free(direntries);
2718
2279
    } else {
2750
2311
      errno = bring_up_interface(interface, delay);
2751
2312
      if(not interface_was_up){
2752
2313
        if(errno != 0){
2753
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2754
 
                       " %s\n", interface, strerror(errno));
 
2314
          perror_plus("Failed to bring up interface");
2755
2315
        } else {
2756
2316
          errno = argz_add(&interfaces_to_take_down,
2757
2317
                           &interfaces_to_take_down_size,
2780
2340
    goto end;
2781
2341
  }
2782
2342
  
2783
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
2343
  ret = init_gnutls_global(pubkey, seckey, &mc);
2784
2344
  if(ret == -1){
2785
2345
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2786
2346
    exitcode = EX_UNAVAILABLE;
2908
2468
    
2909
2469
    /* Allocate a new server */
2910
2470
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2911
 
                                 &config, NULL, NULL, &ret);
 
2471
                                 &config, NULL, NULL, &ret_errno);
2912
2472
    
2913
2473
    /* Free the Avahi configuration data */
2914
2474
    avahi_server_config_free(&config);
2917
2477
  /* Check if creating the Avahi server object succeeded */
2918
2478
  if(mc.server == NULL){
2919
2479
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2920
 
                 avahi_strerror(ret));
 
2480
                 avahi_strerror(ret_errno));
2921
2481
    exitcode = EX_UNAVAILABLE;
2922
2482
    goto end;
2923
2483
  }
2958
2518
 end:
2959
2519
  
2960
2520
  if(debug){
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
 
    }
 
2521
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2968
2522
  }
2969
2523
  
2970
2524
  /* Cleanup things */
2981
2535
  
2982
2536
  if(gnutls_initialized){
2983
2537
    gnutls_certificate_free_credentials(mc.cred);
 
2538
    gnutls_global_deinit();
2984
2539
    gnutls_dh_params_deinit(mc.dh_params);
2985
2540
  }
2986
2541
  
2994
2549
    mc.current_server->prev->next = NULL;
2995
2550
    while(mc.current_server != NULL){
2996
2551
      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
3005
2552
      free(mc.current_server);
3006
2553
      mc.current_server = next;
3007
2554
    }
3009
2556
  
3010
2557
  /* Re-raise privileges */
3011
2558
  {
3012
 
    ret = raise_privileges();
3013
 
    if(ret != 0){
3014
 
      errno = ret;
 
2559
    ret_errno = raise_privileges();
 
2560
    if(ret_errno != 0){
 
2561
      errno = ret_errno;
3015
2562
      perror_plus("Failed to raise privileges");
3016
2563
    } else {
3017
2564
      
3025
2572
        while((interface=argz_next(interfaces_to_take_down,
3026
2573
                                   interfaces_to_take_down_size,
3027
2574
                                   interface))){
3028
 
          ret = take_down_interface(interface);
3029
 
          if(ret != 0){
3030
 
            errno = ret;
 
2575
          ret_errno = take_down_interface(interface);
 
2576
          if(ret_errno != 0){
 
2577
            errno = ret_errno;
3031
2578
            perror_plus("Failed to take down interface");
3032
2579
          }
3033
2580
        }
3038
2585
      }
3039
2586
    }
3040
2587
    
3041
 
    ret = lower_privileges_permanently();
3042
 
    if(ret != 0){
3043
 
      errno = ret;
 
2588
    ret_errno = lower_privileges_permanently();
 
2589
    if(ret_errno != 0){
 
2590
      errno = ret_errno;
3044
2591
      perror_plus("Failed to lower privileges permanently");
3045
2592
    }
3046
2593
  }
3048
2595
  free(interfaces_to_take_down);
3049
2596
  free(interfaces_hooks);
3050
2597
  
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
 
  
3107
2598
  /* Removes the GPGME temp directory and all files inside */
3108
2599
  if(tempdir != NULL){
3109
 
    clean_dir_at(-1, tempdir, 0);
 
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
    }
3110
2640
  }
3111
2641
  
3112
2642
  if(quit_now){