/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2015-07-01 20:01:26 UTC
  • mto: This revision was merged to the branch mainline in revision 759.
  • Revision ID: teddy@recompile.se-20150701200126-qb3f6c3jcas2f4og
mandos-client: Try to start a plugin to add and remove a local route.

* debian/mandos-client.README.Debian: Add setting of environment
                                      variable MANDOSPLUGINHELPERDIR
                                      to command line testing
                                      mandos-client.
* mandos-client.c (raise_privileges): Moved to top of file.
                  (raise_privileges_permanently): - '' -
                  (lower_privileges): - '' -
                  (lower_privileges_permanently): - '' -
  (add_remove_local_route, add_local_route, remove_local_route): New.
  (start_mandos_communication): Set SOCK_CLOEXEC flag on socket.  Run
                                the above functions to add (and
                                remove) local route, if the conditions
                                indicates it could help.
  (run_network_hooks): Use O_DIRECTORY, O_PATH, and O_CLOEXEC flags
                       when opening network hook directory. Do
                       TEMP_FAILURE_RETRY around opening of /dev/null
                       and network hook executables.  Move redirecting
                       of stdout and stderr to as late as possible
                       before fexecve().
  (main): Use O_DIRECTORY and O_PATH when opening temporary directory.
* plugins.d/mandos-client.xml (ENVIRONMENT): Document usage of the
                                             MANDOSPLUGINHELPERDIR
                                             environment variable.

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-2015 Teddy Hogeborn
 
13
 * Copyright © 2008-2015 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() */
 
49
#include <string.h>             /* memset(), strcmp(), strlen(),
 
50
                                   strerror(), asprintf(), strcpy() */
51
51
#include <sys/ioctl.h>          /* ioctl */
52
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
53
                                   sockaddr_in6, PF_INET6,
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect(),
59
59
                                   getnameinfo() */
60
 
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
 
60
#include <fcntl.h>              /* open(), unlinkat() */
61
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
62
                                 */
63
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
64
64
                                   strtoimax() */
65
 
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
66
 
                                   EAI_SYSTEM, ENETUNREACH,
67
 
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
68
 
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
69
 
                                   ENOTEMPTY,
 
65
#include <errno.h>              /* perror(), errno,
70
66
                                   program_invocation_short_name */
71
67
#include <time.h>               /* nanosleep(), time(), sleep() */
72
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
309
305
      return false;
310
306
    }
311
307
    
312
 
    ret = close(fd);
 
308
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
313
309
    if(ret == -1){
314
310
      perror_plus("close");
315
311
    }
497
493
  return plaintext_length;
498
494
}
499
495
 
500
 
__attribute__((warn_unused_result, const))
501
 
static const char *safe_string(const char *str){
502
 
  if(str == NULL)
503
 
    return "(unknown)";
504
 
  return str;
505
 
}
506
 
 
507
496
__attribute__((warn_unused_result))
508
497
static const char *safer_gnutls_strerror(int value){
509
498
  const char *ret = gnutls_strerror(value);
510
 
  return safe_string(ret);
 
499
  if(ret == NULL)
 
500
    ret = "(unknown)";
 
501
  return ret;
511
502
}
512
503
 
513
504
/* GnuTLS log function callback */
517
508
  fprintf_plus(stderr, "GnuTLS: %s", string);
518
509
}
519
510
 
520
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
 
511
__attribute__((nonnull, warn_unused_result))
521
512
static int init_gnutls_global(const char *pubkeyfilename,
522
513
                              const char *seckeyfilename,
523
 
                              const char *dhparamsfilename,
524
514
                              mandos_context *mc){
525
515
  int ret;
526
 
  unsigned int uret;
527
516
  
528
517
  if(debug){
529
518
    fprintf_plus(stderr, "Initializing GnuTLS\n");
530
519
  }
531
520
  
 
521
  ret = gnutls_global_init();
 
522
  if(ret != GNUTLS_E_SUCCESS){
 
523
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
524
                 safer_gnutls_strerror(ret));
 
525
    return -1;
 
526
  }
 
527
  
532
528
  if(debug){
533
529
    /* "Use a log level over 10 to enable all debugging options."
534
530
     * - GnuTLS manual
542
538
  if(ret != GNUTLS_E_SUCCESS){
543
539
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
544
540
                 safer_gnutls_strerror(ret));
 
541
    gnutls_global_deinit();
545
542
    return -1;
546
543
  }
547
544
  
572
569
                 safer_gnutls_strerror(ret));
573
570
    goto globalfail;
574
571
  }
575
 
  /* If a Diffie-Hellman parameters file was given, try to use it */
576
 
  if(dhparamsfilename != NULL){
577
 
    gnutls_datum_t params = { .data = NULL, .size = 0 };
578
 
    do {
579
 
      int dhpfile = open(dhparamsfilename, O_RDONLY);
580
 
      if(dhpfile == -1){
581
 
        perror_plus("open");
582
 
        dhparamsfilename = NULL;
583
 
        break;
584
 
      }
585
 
      size_t params_capacity = 0;
586
 
      while(true){
587
 
        params_capacity = incbuffer((char **)&params.data,
588
 
                                    (size_t)params.size,
589
 
                                    (size_t)params_capacity);
590
 
        if(params_capacity == 0){
591
 
          perror_plus("incbuffer");
592
 
          free(params.data);
593
 
          params.data = NULL;
594
 
          dhparamsfilename = NULL;
595
 
          break;
596
 
        }
597
 
        ssize_t bytes_read = read(dhpfile,
598
 
                                  params.data + params.size,
599
 
                                  BUFFER_SIZE);
600
 
        /* EOF */
601
 
        if(bytes_read == 0){
602
 
          break;
603
 
        }
604
 
        /* check bytes_read for failure */
605
 
        if(bytes_read < 0){
606
 
          perror_plus("read");
607
 
          free(params.data);
608
 
          params.data = NULL;
609
 
          dhparamsfilename = NULL;
610
 
          break;
611
 
        }
612
 
        params.size += (unsigned int)bytes_read;
613
 
      }
614
 
      if(params.data == NULL){
615
 
        dhparamsfilename = NULL;
616
 
      }
617
 
      if(dhparamsfilename == NULL){
618
 
        break;
619
 
      }
620
 
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
621
 
                                          GNUTLS_X509_FMT_PEM);
622
 
      if(ret != GNUTLS_E_SUCCESS){
623
 
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
624
 
                     " \"%s\": %s\n", dhparamsfilename,
625
 
                     safer_gnutls_strerror(ret));
626
 
        dhparamsfilename = NULL;
627
 
      }
628
 
    } while(false);
629
 
  }
630
 
  if(dhparamsfilename == NULL){
631
 
    if(mc->dh_bits == 0){
632
 
      /* Find out the optimal number of DH bits */
633
 
      /* Try to read the private key file */
634
 
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
635
 
      do {
636
 
        int secfile = open(seckeyfilename, O_RDONLY);
637
 
        if(secfile == -1){
638
 
          perror_plus("open");
639
 
          break;
640
 
        }
641
 
        size_t buffer_capacity = 0;
642
 
        while(true){
643
 
          buffer_capacity = incbuffer((char **)&buffer.data,
644
 
                                      (size_t)buffer.size,
645
 
                                      (size_t)buffer_capacity);
646
 
          if(buffer_capacity == 0){
647
 
            perror_plus("incbuffer");
648
 
            free(buffer.data);
649
 
            buffer.data = NULL;
650
 
            break;
651
 
          }
652
 
          ssize_t bytes_read = read(secfile,
653
 
                                    buffer.data + buffer.size,
654
 
                                    BUFFER_SIZE);
655
 
          /* EOF */
656
 
          if(bytes_read == 0){
657
 
            break;
658
 
          }
659
 
          /* check bytes_read for failure */
660
 
          if(bytes_read < 0){
661
 
            perror_plus("read");
662
 
            free(buffer.data);
663
 
            buffer.data = NULL;
664
 
            break;
665
 
          }
666
 
          buffer.size += (unsigned int)bytes_read;
667
 
        }
668
 
        close(secfile);
669
 
      } while(false);
670
 
      /* If successful, use buffer to parse private key */
671
 
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
672
 
      if(buffer.data != NULL){
673
 
        {
674
 
          gnutls_openpgp_privkey_t privkey = NULL;
675
 
          ret = gnutls_openpgp_privkey_init(&privkey);
676
 
          if(ret != GNUTLS_E_SUCCESS){
677
 
            fprintf_plus(stderr, "Error initializing OpenPGP key"
678
 
                         " structure: %s",
679
 
                         safer_gnutls_strerror(ret));
680
 
            free(buffer.data);
681
 
            buffer.data = NULL;
682
 
          } else {
683
 
            ret = gnutls_openpgp_privkey_import
684
 
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
685
 
            if(ret != GNUTLS_E_SUCCESS){
686
 
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
687
 
                           safer_gnutls_strerror(ret));
688
 
              privkey = NULL;
689
 
            }
690
 
            free(buffer.data);
691
 
            buffer.data = NULL;
692
 
            if(privkey != NULL){
693
 
              /* Use private key to suggest an appropriate
694
 
                 sec_param */
695
 
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
696
 
              gnutls_openpgp_privkey_deinit(privkey);
697
 
              if(debug){
698
 
                fprintf_plus(stderr, "This OpenPGP key implies using"
699
 
                             " a GnuTLS security parameter \"%s\".\n",
700
 
                             safe_string(gnutls_sec_param_get_name
701
 
                                         (sec_param)));
702
 
              }
703
 
            }
704
 
          }
705
 
        }
706
 
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
707
 
          /* Err on the side of caution */
708
 
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
709
 
          if(debug){
710
 
            fprintf_plus(stderr, "Falling back to security parameter"
711
 
                         " \"%s\"\n",
712
 
                         safe_string(gnutls_sec_param_get_name
713
 
                                     (sec_param)));
714
 
          }
715
 
        }
716
 
      }
717
 
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
718
 
      if(uret != 0){
719
 
        mc->dh_bits = uret;
720
 
        if(debug){
721
 
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
722
 
                       " implies %u DH bits; using that.\n",
723
 
                       safe_string(gnutls_sec_param_get_name
724
 
                                   (sec_param)),
725
 
                       mc->dh_bits);
726
 
        }
727
 
      } else {
728
 
        fprintf_plus(stderr, "Failed to get implied number of DH"
729
 
                     " bits for security parameter \"%s\"): %s\n",
730
 
                     safe_string(gnutls_sec_param_get_name
731
 
                                 (sec_param)),
732
 
                     safer_gnutls_strerror(ret));
733
 
        goto globalfail;
734
 
      }
735
 
    } else if(debug){
736
 
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
737
 
                   mc->dh_bits);
738
 
    }
739
 
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
740
 
    if(ret != GNUTLS_E_SUCCESS){
741
 
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
742
 
                   " bits): %s\n", mc->dh_bits,
743
 
                   safer_gnutls_strerror(ret));
744
 
      goto globalfail;
745
 
    }
746
 
  }
 
572
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
573
  if(ret != GNUTLS_E_SUCCESS){
 
574
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
575
                 safer_gnutls_strerror(ret));
 
576
    goto globalfail;
 
577
  }
 
578
  
747
579
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
748
580
  
749
581
  return 0;
751
583
 globalfail:
752
584
  
753
585
  gnutls_certificate_free_credentials(mc->cred);
 
586
  gnutls_global_deinit();
754
587
  gnutls_dh_params_deinit(mc->dh_params);
755
588
  return -1;
756
589
}
808
641
  /* ignore client certificate if any. */
809
642
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
810
643
  
 
644
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
645
  
811
646
  return 0;
812
647
}
813
648
 
817
652
 
818
653
/* Set effective uid to 0, return errno */
819
654
__attribute__((warn_unused_result))
820
 
int raise_privileges(void){
821
 
  int old_errno = errno;
822
 
  int ret = 0;
 
655
error_t raise_privileges(void){
 
656
  error_t old_errno = errno;
 
657
  error_t ret_errno = 0;
823
658
  if(seteuid(0) == -1){
824
 
    ret = errno;
 
659
    ret_errno = errno;
825
660
  }
826
661
  errno = old_errno;
827
 
  return ret;
 
662
  return ret_errno;
828
663
}
829
664
 
830
665
/* Set effective and real user ID to 0.  Return errno. */
831
666
__attribute__((warn_unused_result))
832
 
int raise_privileges_permanently(void){
833
 
  int old_errno = errno;
834
 
  int ret = raise_privileges();
835
 
  if(ret != 0){
 
667
error_t raise_privileges_permanently(void){
 
668
  error_t old_errno = errno;
 
669
  error_t ret_errno = raise_privileges();
 
670
  if(ret_errno != 0){
836
671
    errno = old_errno;
837
 
    return ret;
 
672
    return ret_errno;
838
673
  }
839
674
  if(setuid(0) == -1){
840
 
    ret = errno;
 
675
    ret_errno = errno;
841
676
  }
842
677
  errno = old_errno;
843
 
  return ret;
 
678
  return ret_errno;
844
679
}
845
680
 
846
681
/* Set effective user ID to unprivileged saved user ID */
847
682
__attribute__((warn_unused_result))
848
 
int lower_privileges(void){
849
 
  int old_errno = errno;
850
 
  int ret = 0;
 
683
error_t lower_privileges(void){
 
684
  error_t old_errno = errno;
 
685
  error_t ret_errno = 0;
851
686
  if(seteuid(uid) == -1){
852
 
    ret = errno;
 
687
    ret_errno = errno;
853
688
  }
854
689
  errno = old_errno;
855
 
  return ret;
 
690
  return ret_errno;
856
691
}
857
692
 
858
693
/* Lower privileges permanently */
859
694
__attribute__((warn_unused_result))
860
 
int lower_privileges_permanently(void){
861
 
  int old_errno = errno;
862
 
  int ret = 0;
 
695
error_t lower_privileges_permanently(void){
 
696
  error_t old_errno = errno;
 
697
  error_t ret_errno = 0;
863
698
  if(setuid(uid) == -1){
864
 
    ret = errno;
 
699
    ret_errno = errno;
865
700
  }
866
701
  errno = old_errno;
867
 
  return ret;
 
702
  return ret_errno;
868
703
}
869
704
 
870
 
/* Helper function to add_local_route() and delete_local_route() */
 
705
/* Helper function to add_local_route() and remove_local_route() */
871
706
__attribute__((nonnull, warn_unused_result))
872
 
static bool add_delete_local_route(const bool add,
 
707
static bool add_remove_local_route(const bool add,
873
708
                                   const char *address,
874
709
                                   AvahiIfIndex if_index){
875
710
  int ret;
876
711
  char helper[] = "mandos-client-iprouteadddel";
877
712
  char add_arg[] = "add";
878
 
  char delete_arg[] = "delete";
879
 
  char debug_flag[] = "--debug";
 
713
  char remove_arg[] = "remove";
880
714
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
881
715
  if(pluginhelperdir == NULL){
882
716
    if(debug){
941
775
                                                    | O_DIRECTORY
942
776
                                                    | O_PATH
943
777
                                                    | O_CLOEXEC));
944
 
    if(helperdir_fd == -1){
945
 
      perror_plus("open");
946
 
      _exit(EX_UNAVAILABLE);
947
 
    }
948
778
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
949
779
                                                   helper, O_RDONLY));
950
 
    if(helper_fd == -1){
951
 
      perror_plus("openat");
952
 
      close(helperdir_fd);
953
 
      _exit(EX_UNAVAILABLE);
954
 
    }
955
 
    close(helperdir_fd);
 
780
    TEMP_FAILURE_RETRY(close(helperdir_fd));
956
781
#ifdef __GNUC__
957
782
#pragma GCC diagnostic push
958
783
#pragma GCC diagnostic ignored "-Wcast-qual"
959
784
#endif
960
785
    if(fexecve(helper_fd, (char *const [])
961
 
               { helper, add ? add_arg : delete_arg, (char *)address,
962
 
                   interface, debug ? debug_flag : NULL, NULL },
963
 
               environ) == -1){
 
786
               { helper, add ? add_arg : remove_arg, (char *)address,
 
787
                   interface, NULL }, environ) == -1){
964
788
#ifdef __GNUC__
965
789
#pragma GCC diagnostic pop
966
790
#endif
1018
842
__attribute__((nonnull, warn_unused_result))
1019
843
static bool add_local_route(const char *address,
1020
844
                            AvahiIfIndex if_index){
1021
 
  if(debug){
1022
 
    fprintf_plus(stderr, "Adding route to %s\n", address);
1023
 
  }
1024
 
  return add_delete_local_route(true, address, if_index);
 
845
  return add_remove_local_route(true, address, if_index);
1025
846
}
1026
847
 
1027
848
__attribute__((nonnull, warn_unused_result))
1028
 
static bool delete_local_route(const char *address,
 
849
static bool remove_local_route(const char *address,
1029
850
                               AvahiIfIndex if_index){
1030
 
  if(debug){
1031
 
    fprintf_plus(stderr, "Removing route to %s\n", address);
1032
 
  }
1033
 
  return add_delete_local_route(false, address, if_index);
 
851
  return add_remove_local_route(false, address, if_index);
1034
852
}
1035
853
 
1036
854
/* Called when a Mandos server is found */
1126
944
    goto mandos_end;
1127
945
  }
1128
946
  
 
947
  memset(&to, 0, sizeof(to));
1129
948
  if(af == AF_INET6){
1130
 
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
1131
 
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
1132
 
    ret = inet_pton(af, ip, &to6->sin6_addr);
 
949
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
950
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
1133
951
  } else {                      /* IPv4 */
1134
 
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
1135
 
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
1136
 
    ret = inet_pton(af, ip, &to4->sin_addr);
 
952
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
953
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
1137
954
  }
1138
955
  if(ret < 0 ){
1139
956
    int e = errno;
1218
1035
                    sizeof(struct sockaddr_in));
1219
1036
    }
1220
1037
    if(ret < 0){
1221
 
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
 
1038
      if(errno == ENETUNREACH
1222
1039
         and if_index != AVAHI_IF_UNSPEC
1223
1040
         and connect_to == NULL
1224
1041
         and not route_added and
1240
1057
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1241
1058
           https://bugs.debian.org/587961
1242
1059
        */
1243
 
        if(debug){
1244
 
          fprintf_plus(stderr, "Mandos server unreachable, trying"
1245
 
                       " direct route\n");
1246
 
        }
1247
1060
        int e = errno;
1248
1061
        route_added = add_local_route(ip, if_index);
1249
1062
        if(route_added){
1453
1266
 mandos_end:
1454
1267
  {
1455
1268
    if(route_added){
1456
 
      if(not delete_local_route(ip, if_index)){
1457
 
        fprintf_plus(stderr, "Failed to delete local route to %s on"
 
1269
      if(not remove_local_route(ip, if_index)){
 
1270
        fprintf_plus(stderr, "Failed to remove local route to %s on"
1458
1271
                     " interface %d", ip, if_index);
1459
1272
      }
1460
1273
    }
1462
1275
    free(decrypted_buffer);
1463
1276
    free(buffer);
1464
1277
    if(tcp_sd >= 0){
1465
 
      ret = close(tcp_sd);
 
1278
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1466
1279
    }
1467
1280
    if(ret == -1){
1468
1281
      if(e == 0){
1623
1436
__attribute__((nonnull, warn_unused_result))
1624
1437
bool get_flags(const char *ifname, struct ifreq *ifr){
1625
1438
  int ret;
1626
 
  int old_errno;
 
1439
  error_t ret_errno;
1627
1440
  
1628
1441
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1629
1442
  if(s < 0){
1630
 
    old_errno = errno;
 
1443
    ret_errno = errno;
1631
1444
    perror_plus("socket");
1632
 
    errno = old_errno;
 
1445
    errno = ret_errno;
1633
1446
    return false;
1634
1447
  }
1635
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1636
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
 
1448
  strcpy(ifr->ifr_name, ifname);
1637
1449
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1638
1450
  if(ret == -1){
1639
1451
    if(debug){
1640
 
      old_errno = errno;
 
1452
      ret_errno = errno;
1641
1453
      perror_plus("ioctl SIOCGIFFLAGS");
1642
 
      errno = old_errno;
 
1454
      errno = ret_errno;
1643
1455
    }
1644
1456
    return false;
1645
1457
  }
1909
1721
      return;
1910
1722
    }
1911
1723
  }
 
1724
#ifdef __GLIBC__
 
1725
#if __GLIBC_PREREQ(2, 15)
1912
1726
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1913
1727
                           runnable_hook, alphasort);
 
1728
#else  /* not __GLIBC_PREREQ(2, 15) */
 
1729
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1730
                         alphasort);
 
1731
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
1732
#else   /* not __GLIBC__ */
 
1733
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1734
                         alphasort);
 
1735
#endif  /* not __GLIBC__ */
1914
1736
  if(numhooks == -1){
1915
1737
    perror_plus("scandir");
1916
1738
    return;
1991
1813
          _exit(EX_OSERR);
1992
1814
        }
1993
1815
      }
1994
 
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
1995
 
                                                   direntry->d_name,
1996
 
                                                   O_RDONLY));
 
1816
      int hook_fd = TEMP_FAILURE_RETRY(openat(hookdir_fd,
 
1817
                                              direntry->d_name,
 
1818
                                              O_RDONLY));
1997
1819
      if(hook_fd == -1){
1998
1820
        perror_plus("openat");
1999
1821
        _exit(EXIT_FAILURE);
2000
1822
      }
2001
 
      if(close(hookdir_fd) == -1){
 
1823
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2002
1824
        perror_plus("close");
2003
1825
        _exit(EXIT_FAILURE);
2004
1826
      }
2062
1884
    free(direntry);
2063
1885
  }
2064
1886
  free(direntries);
2065
 
  if(close(hookdir_fd) == -1){
 
1887
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2066
1888
    perror_plus("close");
2067
1889
  } else {
2068
1890
    hookdir_fd = -1;
2071
1893
}
2072
1894
 
2073
1895
__attribute__((nonnull, warn_unused_result))
2074
 
int bring_up_interface(const char *const interface,
2075
 
                       const float delay){
2076
 
  int old_errno = errno;
 
1896
error_t bring_up_interface(const char *const interface,
 
1897
                           const float delay){
 
1898
  error_t old_errno = errno;
2077
1899
  int ret;
2078
1900
  struct ifreq network;
2079
1901
  unsigned int if_index = if_nametoindex(interface);
2089
1911
  }
2090
1912
  
2091
1913
  if(not interface_is_up(interface)){
2092
 
    int ret_errno = 0;
2093
 
    int ioctl_errno = 0;
 
1914
    error_t ret_errno = 0, ioctl_errno = 0;
2094
1915
    if(not get_flags(interface, &network)){
2095
1916
      ret_errno = errno;
2096
1917
      fprintf_plus(stderr, "Failed to get flags for interface "
2109
1930
    }
2110
1931
    
2111
1932
    if(quit_now){
2112
 
      ret = close(sd);
 
1933
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2113
1934
      if(ret == -1){
2114
1935
        perror_plus("close");
2115
1936
      }
2165
1986
    }
2166
1987
    
2167
1988
    /* Close the socket */
2168
 
    ret = close(sd);
 
1989
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
2169
1990
    if(ret == -1){
2170
1991
      perror_plus("close");
2171
1992
    }
2199
2020
}
2200
2021
 
2201
2022
__attribute__((nonnull, warn_unused_result))
2202
 
int take_down_interface(const char *const interface){
2203
 
  int old_errno = errno;
 
2023
error_t take_down_interface(const char *const interface){
 
2024
  error_t old_errno = errno;
2204
2025
  struct ifreq network;
2205
2026
  unsigned int if_index = if_nametoindex(interface);
2206
2027
  if(if_index == 0){
2209
2030
    return ENXIO;
2210
2031
  }
2211
2032
  if(interface_is_up(interface)){
2212
 
    int ret_errno = 0;
2213
 
    int ioctl_errno = 0;
 
2033
    error_t ret_errno = 0, ioctl_errno = 0;
2214
2034
    if(not get_flags(interface, &network) and debug){
2215
2035
      ret_errno = errno;
2216
2036
      fprintf_plus(stderr, "Failed to get flags for interface "
2254
2074
    }
2255
2075
    
2256
2076
    /* Close the socket */
2257
 
    int ret = close(sd);
 
2077
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
2258
2078
    if(ret == -1){
2259
2079
      perror_plus("close");
2260
2080
    }
2275
2095
}
2276
2096
 
2277
2097
int main(int argc, char *argv[]){
2278
 
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2279
 
                        .priority = "SECURE256:!CTYPE-X.509"
2280
 
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
2281
 
                        .current_server = NULL, .interfaces = NULL,
2282
 
                        .interfaces_size = 0 };
 
2098
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
2099
                        .priority = "SECURE256:!CTYPE-X.509:"
 
2100
                        "+CTYPE-OPENPGP", .current_server = NULL,
 
2101
                        .interfaces = NULL, .interfaces_size = 0 };
2283
2102
  AvahiSServiceBrowser *sb = NULL;
2284
2103
  error_t ret_errno;
2285
2104
  int ret;
2294
2113
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2295
2114
  const char *seckey = PATHDIR "/" SECKEY;
2296
2115
  const char *pubkey = PATHDIR "/" PUBKEY;
2297
 
  const char *dh_params_file = NULL;
2298
2116
  char *interfaces_hooks = NULL;
2299
2117
  
2300
2118
  bool gnutls_initialized = false;
2353
2171
        .doc = "Bit length of the prime number used in the"
2354
2172
        " Diffie-Hellman key exchange",
2355
2173
        .group = 2 },
2356
 
      { .name = "dh-params", .key = 134,
2357
 
        .arg = "FILE",
2358
 
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
2359
 
        " for the Diffie-Hellman key exchange",
2360
 
        .group = 2 },
2361
2174
      { .name = "priority", .key = 130,
2362
2175
        .arg = "STRING",
2363
2176
        .doc = "GnuTLS priority string for the TLS handshake",
2418
2231
        }
2419
2232
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2420
2233
        break;
2421
 
      case 134:                 /* --dh-params */
2422
 
        dh_params_file = arg;
2423
 
        break;
2424
2234
      case 130:                 /* --priority */
2425
2235
        mc.priority = arg;
2426
2236
        break;
2466
2276
                         .args_doc = "",
2467
2277
                         .doc = "Mandos client -- Get and decrypt"
2468
2278
                         " passwords from a Mandos server" };
2469
 
    ret_errno = argp_parse(&argp, argc, argv,
2470
 
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2471
 
    switch(ret_errno){
 
2279
    ret = argp_parse(&argp, argc, argv,
 
2280
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2281
    switch(ret){
2472
2282
    case 0:
2473
2283
      break;
2474
2284
    case ENOMEM:
2475
2285
    default:
2476
 
      errno = ret_errno;
 
2286
      errno = ret;
2477
2287
      perror_plus("argp_parse");
2478
2288
      exitcode = EX_OSERR;
2479
2289
      goto end;
2488
2298
       <http://bugs.debian.org/633582> */
2489
2299
    
2490
2300
    /* Re-raise privileges */
2491
 
    ret = raise_privileges();
2492
 
    if(ret != 0){
2493
 
      errno = ret;
 
2301
    ret_errno = raise_privileges();
 
2302
    if(ret_errno != 0){
 
2303
      errno = ret_errno;
2494
2304
      perror_plus("Failed to raise privileges");
2495
2305
    } else {
2496
2306
      struct stat st;
2512
2322
              }
2513
2323
            }
2514
2324
          }
2515
 
          close(seckey_fd);
 
2325
          TEMP_FAILURE_RETRY(close(seckey_fd));
2516
2326
        }
2517
2327
      }
2518
2328
      
2533
2343
              }
2534
2344
            }
2535
2345
          }
2536
 
          close(pubkey_fd);
2537
 
        }
2538
 
      }
2539
 
      
2540
 
      if(dh_params_file != NULL
2541
 
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
2542
 
        int dhparams_fd = open(dh_params_file, O_RDONLY);
2543
 
        if(dhparams_fd == -1){
2544
 
          perror_plus("open");
2545
 
        } else {
2546
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
2547
 
          if(ret == -1){
2548
 
            perror_plus("fstat");
2549
 
          } else {
2550
 
            if(S_ISREG(st.st_mode)
2551
 
               and st.st_uid == 0 and st.st_gid == 0){
2552
 
              ret = fchown(dhparams_fd, uid, gid);
2553
 
              if(ret == -1){
2554
 
                perror_plus("fchown");
2555
 
              }
2556
 
            }
2557
 
          }
2558
 
          close(dhparams_fd);
 
2346
          TEMP_FAILURE_RETRY(close(pubkey_fd));
2559
2347
        }
2560
2348
      }
2561
2349
      
2562
2350
      /* Lower privileges */
2563
 
      ret = lower_privileges();
2564
 
      if(ret != 0){
2565
 
        errno = ret;
 
2351
      ret_errno = lower_privileges();
 
2352
      if(ret_errno != 0){
 
2353
        errno = ret_errno;
2566
2354
        perror_plus("Failed to lower privileges");
2567
2355
      }
2568
2356
    }
2738
2526
      errno = bring_up_interface(interface, delay);
2739
2527
      if(not interface_was_up){
2740
2528
        if(errno != 0){
2741
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2742
 
                       " %s\n", interface, strerror(errno));
 
2529
          perror_plus("Failed to bring up interface");
2743
2530
        } else {
2744
2531
          errno = argz_add(&interfaces_to_take_down,
2745
2532
                           &interfaces_to_take_down_size,
2768
2555
    goto end;
2769
2556
  }
2770
2557
  
2771
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
2558
  ret = init_gnutls_global(pubkey, seckey, &mc);
2772
2559
  if(ret == -1){
2773
2560
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2774
2561
    exitcode = EX_UNAVAILABLE;
2896
2683
    
2897
2684
    /* Allocate a new server */
2898
2685
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2899
 
                                 &config, NULL, NULL, &ret);
 
2686
                                 &config, NULL, NULL, &ret_errno);
2900
2687
    
2901
2688
    /* Free the Avahi configuration data */
2902
2689
    avahi_server_config_free(&config);
2905
2692
  /* Check if creating the Avahi server object succeeded */
2906
2693
  if(mc.server == NULL){
2907
2694
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2908
 
                 avahi_strerror(ret));
 
2695
                 avahi_strerror(ret_errno));
2909
2696
    exitcode = EX_UNAVAILABLE;
2910
2697
    goto end;
2911
2698
  }
2963
2750
  
2964
2751
  if(gnutls_initialized){
2965
2752
    gnutls_certificate_free_credentials(mc.cred);
 
2753
    gnutls_global_deinit();
2966
2754
    gnutls_dh_params_deinit(mc.dh_params);
2967
2755
  }
2968
2756
  
2991
2779
  
2992
2780
  /* Re-raise privileges */
2993
2781
  {
2994
 
    ret = raise_privileges();
2995
 
    if(ret != 0){
2996
 
      errno = ret;
 
2782
    ret_errno = raise_privileges();
 
2783
    if(ret_errno != 0){
 
2784
      errno = ret_errno;
2997
2785
      perror_plus("Failed to raise privileges");
2998
2786
    } else {
2999
2787
      
3007
2795
        while((interface=argz_next(interfaces_to_take_down,
3008
2796
                                   interfaces_to_take_down_size,
3009
2797
                                   interface))){
3010
 
          ret = take_down_interface(interface);
3011
 
          if(ret != 0){
3012
 
            errno = ret;
 
2798
          ret_errno = take_down_interface(interface);
 
2799
          if(ret_errno != 0){
 
2800
            errno = ret_errno;
3013
2801
            perror_plus("Failed to take down interface");
3014
2802
          }
3015
2803
        }
3020
2808
      }
3021
2809
    }
3022
2810
    
3023
 
    ret = lower_privileges_permanently();
3024
 
    if(ret != 0){
3025
 
      errno = ret;
 
2811
    ret_errno = lower_privileges_permanently();
 
2812
    if(ret_errno != 0){
 
2813
      errno = ret_errno;
3026
2814
      perror_plus("Failed to lower privileges permanently");
3027
2815
    }
3028
2816
  }
3030
2818
  free(interfaces_to_take_down);
3031
2819
  free(interfaces_hooks);
3032
2820
  
3033
 
  void clean_dir_at(int base, const char * const dirname,
3034
 
                    uintmax_t level){
3035
 
    struct dirent **direntries = NULL;
3036
 
    int dret;
3037
 
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
3038
 
                                                O_RDONLY
3039
 
                                                | O_NOFOLLOW
3040
 
                                                | O_DIRECTORY
3041
 
                                                | O_PATH));
3042
 
    if(dir_fd == -1){
3043
 
      perror_plus("open");
3044
 
    }
3045
 
    int numentries = scandirat(dir_fd, ".", &direntries,
3046
 
                               notdotentries, alphasort);
3047
 
    if(numentries >= 0){
3048
 
      for(int i = 0; i < numentries; i++){
3049
 
        if(debug){
3050
 
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
3051
 
                       dirname, direntries[i]->d_name);
3052
 
        }
3053
 
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
3054
 
        if(dret == -1){
3055
 
          if(errno == EISDIR){
3056
 
              dret = unlinkat(dir_fd, direntries[i]->d_name,
3057
 
                              AT_REMOVEDIR);
3058
 
          }         
3059
 
          if((dret == -1) and (errno == ENOTEMPTY)
3060
 
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
3061
 
                  == 0) and (level == 0)){
3062
 
            /* Recurse only in this special case */
3063
 
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
3064
 
            dret = 0;
3065
 
          }
3066
 
          if(dret == -1){
3067
 
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
3068
 
                         direntries[i]->d_name, strerror(errno));
3069
 
          }
3070
 
        }
3071
 
        free(direntries[i]);
3072
 
      }
3073
 
      
3074
 
      /* need to clean even if 0 because man page doesn't specify */
3075
 
      free(direntries);
3076
 
      if(numentries == -1){
3077
 
        perror_plus("scandirat");
3078
 
      }
3079
 
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
3080
 
      if(dret == -1 and errno != ENOENT){
3081
 
        perror_plus("rmdir");
3082
 
      }
3083
 
    } else {
3084
 
      perror_plus("scandirat");
3085
 
    }
3086
 
    close(dir_fd);
3087
 
  }
3088
 
  
3089
2821
  /* Removes the GPGME temp directory and all files inside */
3090
2822
  if(tempdir != NULL){
3091
 
    clean_dir_at(-1, tempdir, 0);
 
2823
    struct dirent **direntries = NULL;
 
2824
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
 
2825
                                                  | O_NOFOLLOW
 
2826
                                                  | O_DIRECTORY
 
2827
                                                  | O_PATH));
 
2828
    if(tempdir_fd == -1){
 
2829
      perror_plus("open");
 
2830
    } else {
 
2831
#ifdef __GLIBC__
 
2832
#if __GLIBC_PREREQ(2, 15)
 
2833
      int numentries = scandirat(tempdir_fd, ".", &direntries,
 
2834
                                 notdotentries, alphasort);
 
2835
#else  /* not __GLIBC_PREREQ(2, 15) */
 
2836
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2837
                               alphasort);
 
2838
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
2839
#else   /* not __GLIBC__ */
 
2840
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2841
                               alphasort);
 
2842
#endif  /* not __GLIBC__ */
 
2843
      if(numentries >= 0){
 
2844
        for(int i = 0; i < numentries; i++){
 
2845
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
 
2846
          if(ret == -1){
 
2847
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
 
2848
                         " \"%s\", 0): %s\n", tempdir,
 
2849
                         direntries[i]->d_name, strerror(errno));
 
2850
          }
 
2851
          free(direntries[i]);
 
2852
        }
 
2853
        
 
2854
        /* need to clean even if 0 because man page doesn't specify */
 
2855
        free(direntries);
 
2856
        if(numentries == -1){
 
2857
          perror_plus("scandir");
 
2858
        }
 
2859
        ret = rmdir(tempdir);
 
2860
        if(ret == -1 and errno != ENOENT){
 
2861
          perror_plus("rmdir");
 
2862
        }
 
2863
      }
 
2864
      TEMP_FAILURE_RETRY(close(tempdir_fd));
 
2865
    }
3092
2866
  }
3093
2867
  
3094
2868
  if(quit_now){