/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: 2017-02-22 21:45:35 UTC
  • Revision ID: teddy@recompile.se-20170222214535-milf6w0b1krwpaex
Server bug fix: Use the mandos.conf "zeroconf" and "restore" options

Allow the "zeroconf" and "restore" options to actually work from the
mandos.conf file, in addition to command line options.

Closes: 855589
Reported-by: Pablo Abelenda <pabelenda@igalia.com>
Suggested-by: Pablo Abelenda <pabelenda@igalia.com>

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-2015 Teddy Hogeborn
13
 
 * Copyright © 2008-2015 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,
305
310
      return false;
306
311
    }
307
312
    
308
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
 
313
    ret = close(fd);
309
314
    if(ret == -1){
310
315
      perror_plus("close");
311
316
    }
493
498
  return plaintext_length;
494
499
}
495
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
 
496
508
__attribute__((warn_unused_result))
497
509
static const char *safer_gnutls_strerror(int value){
498
510
  const char *ret = gnutls_strerror(value);
499
 
  if(ret == NULL)
500
 
    ret = "(unknown)";
501
 
  return ret;
 
511
  return safe_string(ret);
502
512
}
503
513
 
504
514
/* GnuTLS log function callback */
508
518
  fprintf_plus(stderr, "GnuTLS: %s", string);
509
519
}
510
520
 
511
 
__attribute__((nonnull, warn_unused_result))
 
521
__attribute__((nonnull(1, 2, 4), warn_unused_result))
512
522
static int init_gnutls_global(const char *pubkeyfilename,
513
523
                              const char *seckeyfilename,
 
524
                              const char *dhparamsfilename,
514
525
                              mandos_context *mc){
515
526
  int ret;
 
527
  unsigned int uret;
516
528
  
517
529
  if(debug){
518
530
    fprintf_plus(stderr, "Initializing GnuTLS\n");
519
531
  }
520
532
  
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
 
  
528
533
  if(debug){
529
534
    /* "Use a log level over 10 to enable all debugging options."
530
535
     * - GnuTLS manual
538
543
  if(ret != GNUTLS_E_SUCCESS){
539
544
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
540
545
                 safer_gnutls_strerror(ret));
541
 
    gnutls_global_deinit();
542
546
    return -1;
543
547
  }
544
548
  
569
573
                 safer_gnutls_strerror(ret));
570
574
    goto globalfail;
571
575
  }
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
 
  
 
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
      free(params.data);
 
630
    } while(false);
 
631
  }
 
632
  if(dhparamsfilename == NULL){
 
633
    if(mc->dh_bits == 0){
 
634
      /* Find out the optimal number of DH bits */
 
635
      /* Try to read the private key file */
 
636
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
 
637
      do {
 
638
        int secfile = open(seckeyfilename, O_RDONLY);
 
639
        if(secfile == -1){
 
640
          perror_plus("open");
 
641
          break;
 
642
        }
 
643
        size_t buffer_capacity = 0;
 
644
        while(true){
 
645
          buffer_capacity = incbuffer((char **)&buffer.data,
 
646
                                      (size_t)buffer.size,
 
647
                                      (size_t)buffer_capacity);
 
648
          if(buffer_capacity == 0){
 
649
            perror_plus("incbuffer");
 
650
            free(buffer.data);
 
651
            buffer.data = NULL;
 
652
            break;
 
653
          }
 
654
          ssize_t bytes_read = read(secfile,
 
655
                                    buffer.data + buffer.size,
 
656
                                    BUFFER_SIZE);
 
657
          /* EOF */
 
658
          if(bytes_read == 0){
 
659
            break;
 
660
          }
 
661
          /* check bytes_read for failure */
 
662
          if(bytes_read < 0){
 
663
            perror_plus("read");
 
664
            free(buffer.data);
 
665
            buffer.data = NULL;
 
666
            break;
 
667
          }
 
668
          buffer.size += (unsigned int)bytes_read;
 
669
        }
 
670
        close(secfile);
 
671
      } while(false);
 
672
      /* If successful, use buffer to parse private key */
 
673
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
674
      if(buffer.data != NULL){
 
675
        {
 
676
          gnutls_openpgp_privkey_t privkey = NULL;
 
677
          ret = gnutls_openpgp_privkey_init(&privkey);
 
678
          if(ret != GNUTLS_E_SUCCESS){
 
679
            fprintf_plus(stderr, "Error initializing OpenPGP key"
 
680
                         " structure: %s",
 
681
                         safer_gnutls_strerror(ret));
 
682
            free(buffer.data);
 
683
            buffer.data = NULL;
 
684
          } else {
 
685
            ret = gnutls_openpgp_privkey_import
 
686
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
 
687
            if(ret != GNUTLS_E_SUCCESS){
 
688
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
 
689
                           safer_gnutls_strerror(ret));
 
690
              privkey = NULL;
 
691
            }
 
692
            free(buffer.data);
 
693
            buffer.data = NULL;
 
694
            if(privkey != NULL){
 
695
              /* Use private key to suggest an appropriate
 
696
                 sec_param */
 
697
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
 
698
              gnutls_openpgp_privkey_deinit(privkey);
 
699
              if(debug){
 
700
                fprintf_plus(stderr, "This OpenPGP key implies using"
 
701
                             " a GnuTLS security parameter \"%s\".\n",
 
702
                             safe_string(gnutls_sec_param_get_name
 
703
                                         (sec_param)));
 
704
              }
 
705
            }
 
706
          }
 
707
        }
 
708
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
 
709
          /* Err on the side of caution */
 
710
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
711
          if(debug){
 
712
            fprintf_plus(stderr, "Falling back to security parameter"
 
713
                         " \"%s\"\n",
 
714
                         safe_string(gnutls_sec_param_get_name
 
715
                                     (sec_param)));
 
716
          }
 
717
        }
 
718
      }
 
719
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
 
720
      if(uret != 0){
 
721
        mc->dh_bits = uret;
 
722
        if(debug){
 
723
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
 
724
                       " implies %u DH bits; using that.\n",
 
725
                       safe_string(gnutls_sec_param_get_name
 
726
                                   (sec_param)),
 
727
                       mc->dh_bits);
 
728
        }
 
729
      } else {
 
730
        fprintf_plus(stderr, "Failed to get implied number of DH"
 
731
                     " bits for security parameter \"%s\"): %s\n",
 
732
                     safe_string(gnutls_sec_param_get_name
 
733
                                 (sec_param)),
 
734
                     safer_gnutls_strerror(ret));
 
735
        goto globalfail;
 
736
      }
 
737
    } else if(debug){
 
738
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
 
739
                   mc->dh_bits);
 
740
    }
 
741
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
742
    if(ret != GNUTLS_E_SUCCESS){
 
743
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
 
744
                   " bits): %s\n", mc->dh_bits,
 
745
                   safer_gnutls_strerror(ret));
 
746
      goto globalfail;
 
747
    }
 
748
  }
579
749
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
580
750
  
581
751
  return 0;
583
753
 globalfail:
584
754
  
585
755
  gnutls_certificate_free_credentials(mc->cred);
586
 
  gnutls_global_deinit();
587
756
  gnutls_dh_params_deinit(mc->dh_params);
588
757
  return -1;
589
758
}
641
810
  /* ignore client certificate if any. */
642
811
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
643
812
  
644
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
645
 
  
646
813
  return 0;
647
814
}
648
815
 
652
819
 
653
820
/* Set effective uid to 0, return errno */
654
821
__attribute__((warn_unused_result))
655
 
error_t raise_privileges(void){
656
 
  error_t old_errno = errno;
657
 
  error_t ret_errno = 0;
 
822
int raise_privileges(void){
 
823
  int old_errno = errno;
 
824
  int ret = 0;
658
825
  if(seteuid(0) == -1){
659
 
    ret_errno = errno;
 
826
    ret = errno;
660
827
  }
661
828
  errno = old_errno;
662
 
  return ret_errno;
 
829
  return ret;
663
830
}
664
831
 
665
832
/* Set effective and real user ID to 0.  Return errno. */
666
833
__attribute__((warn_unused_result))
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){
 
834
int raise_privileges_permanently(void){
 
835
  int old_errno = errno;
 
836
  int ret = raise_privileges();
 
837
  if(ret != 0){
671
838
    errno = old_errno;
672
 
    return ret_errno;
 
839
    return ret;
673
840
  }
674
841
  if(setuid(0) == -1){
675
 
    ret_errno = errno;
 
842
    ret = errno;
676
843
  }
677
844
  errno = old_errno;
678
 
  return ret_errno;
 
845
  return ret;
679
846
}
680
847
 
681
848
/* Set effective user ID to unprivileged saved user ID */
682
849
__attribute__((warn_unused_result))
683
 
error_t lower_privileges(void){
684
 
  error_t old_errno = errno;
685
 
  error_t ret_errno = 0;
 
850
int lower_privileges(void){
 
851
  int old_errno = errno;
 
852
  int ret = 0;
686
853
  if(seteuid(uid) == -1){
687
 
    ret_errno = errno;
 
854
    ret = errno;
688
855
  }
689
856
  errno = old_errno;
690
 
  return ret_errno;
 
857
  return ret;
691
858
}
692
859
 
693
860
/* Lower privileges permanently */
694
861
__attribute__((warn_unused_result))
695
 
error_t lower_privileges_permanently(void){
696
 
  error_t old_errno = errno;
697
 
  error_t ret_errno = 0;
 
862
int lower_privileges_permanently(void){
 
863
  int old_errno = errno;
 
864
  int ret = 0;
698
865
  if(setuid(uid) == -1){
699
 
    ret_errno = errno;
 
866
    ret = errno;
700
867
  }
701
868
  errno = old_errno;
702
 
  return ret_errno;
 
869
  return ret;
703
870
}
704
871
 
705
 
/* Helper function to add_local_route() and remove_local_route() */
 
872
/* Helper function to add_local_route() and delete_local_route() */
706
873
__attribute__((nonnull, warn_unused_result))
707
 
static bool add_remove_local_route(const bool add,
 
874
static bool add_delete_local_route(const bool add,
708
875
                                   const char *address,
709
876
                                   AvahiIfIndex if_index){
710
877
  int ret;
711
878
  char helper[] = "mandos-client-iprouteadddel";
712
879
  char add_arg[] = "add";
713
880
  char delete_arg[] = "delete";
 
881
  char debug_flag[] = "--debug";
714
882
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
715
883
  if(pluginhelperdir == NULL){
716
884
    if(debug){
760
928
      perror_plus("dup2(devnull, STDIN_FILENO)");
761
929
      _exit(EX_OSERR);
762
930
    }
763
 
    ret = (int)TEMP_FAILURE_RETRY(close(devnull));
 
931
    ret = close(devnull);
764
932
    if(ret == -1){
765
933
      perror_plus("close");
766
934
      _exit(EX_OSERR);
783
951
                                                   helper, O_RDONLY));
784
952
    if(helper_fd == -1){
785
953
      perror_plus("openat");
 
954
      close(helperdir_fd);
786
955
      _exit(EX_UNAVAILABLE);
787
956
    }
788
 
    TEMP_FAILURE_RETRY(close(helperdir_fd));
 
957
    close(helperdir_fd);
789
958
#ifdef __GNUC__
790
959
#pragma GCC diagnostic push
791
960
#pragma GCC diagnostic ignored "-Wcast-qual"
792
961
#endif
793
962
    if(fexecve(helper_fd, (char *const [])
794
963
               { helper, add ? add_arg : delete_arg, (char *)address,
795
 
                   interface, NULL }, environ) == -1){
 
964
                   interface, debug ? debug_flag : NULL, NULL },
 
965
               environ) == -1){
796
966
#ifdef __GNUC__
797
967
#pragma GCC diagnostic pop
798
968
#endif
850
1020
__attribute__((nonnull, warn_unused_result))
851
1021
static bool add_local_route(const char *address,
852
1022
                            AvahiIfIndex if_index){
853
 
  return add_remove_local_route(true, address, if_index);
 
1023
  if(debug){
 
1024
    fprintf_plus(stderr, "Adding route to %s\n", address);
 
1025
  }
 
1026
  return add_delete_local_route(true, address, if_index);
854
1027
}
855
1028
 
856
1029
__attribute__((nonnull, warn_unused_result))
857
 
static bool remove_local_route(const char *address,
 
1030
static bool delete_local_route(const char *address,
858
1031
                               AvahiIfIndex if_index){
859
 
  return add_remove_local_route(false, address, if_index);
 
1032
  if(debug){
 
1033
    fprintf_plus(stderr, "Removing route to %s\n", address);
 
1034
  }
 
1035
  return add_delete_local_route(false, address, if_index);
860
1036
}
861
1037
 
862
1038
/* Called when a Mandos server is found */
903
1079
    bool match = false;
904
1080
    {
905
1081
      char *interface = NULL;
906
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
907
 
                                 interface))){
 
1082
      while((interface = argz_next(mc->interfaces,
 
1083
                                   mc->interfaces_size,
 
1084
                                   interface))){
908
1085
        if(if_nametoindex(interface) == (unsigned int)if_index){
909
1086
          match = true;
910
1087
          break;
952
1129
    goto mandos_end;
953
1130
  }
954
1131
  
955
 
  memset(&to, 0, sizeof(to));
956
1132
  if(af == AF_INET6){
957
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
958
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
1133
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
 
1134
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
 
1135
    ret = inet_pton(af, ip, &to6->sin6_addr);
959
1136
  } else {                      /* IPv4 */
960
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
961
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
1137
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
 
1138
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
 
1139
    ret = inet_pton(af, ip, &to4->sin_addr);
962
1140
  }
963
1141
  if(ret < 0 ){
964
1142
    int e = errno;
1043
1221
                    sizeof(struct sockaddr_in));
1044
1222
    }
1045
1223
    if(ret < 0){
1046
 
      if(errno == ENETUNREACH
 
1224
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
1047
1225
         and if_index != AVAHI_IF_UNSPEC
1048
1226
         and connect_to == NULL
1049
1227
         and not route_added and
1062
1240
           with an explicit route added with the server's address.
1063
1241
           
1064
1242
           Avahi bug reference:
1065
 
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
 
1243
           https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1066
1244
           https://bugs.debian.org/587961
1067
1245
        */
 
1246
        if(debug){
 
1247
          fprintf_plus(stderr, "Mandos server unreachable, trying"
 
1248
                       " direct route\n");
 
1249
        }
1068
1250
        int e = errno;
1069
1251
        route_added = add_local_route(ip, if_index);
1070
1252
        if(route_added){
1244
1426
                                               &decrypted_buffer, mc);
1245
1427
    if(decrypted_buffer_size >= 0){
1246
1428
      
 
1429
      clearerr(stdout);
1247
1430
      written = 0;
1248
1431
      while(written < (size_t) decrypted_buffer_size){
1249
1432
        if(quit_now){
1265
1448
        }
1266
1449
        written += (size_t)ret;
1267
1450
      }
 
1451
      ret = fflush(stdout);
 
1452
      if(ret != 0){
 
1453
        int e = errno;
 
1454
        if(debug){
 
1455
          fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
1456
                       strerror(errno));
 
1457
        }
 
1458
        errno = e;
 
1459
        goto mandos_end;
 
1460
      }
1268
1461
      retval = 0;
1269
1462
    }
1270
1463
  }
1274
1467
 mandos_end:
1275
1468
  {
1276
1469
    if(route_added){
1277
 
      if(not remove_local_route(ip, if_index)){
1278
 
        fprintf_plus(stderr, "Failed to remove local route to %s on"
 
1470
      if(not delete_local_route(ip, if_index)){
 
1471
        fprintf_plus(stderr, "Failed to delete local route to %s on"
1279
1472
                     " interface %d", ip, if_index);
1280
1473
      }
1281
1474
    }
1283
1476
    free(decrypted_buffer);
1284
1477
    free(buffer);
1285
1478
    if(tcp_sd >= 0){
1286
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
1479
      ret = close(tcp_sd);
1287
1480
    }
1288
1481
    if(ret == -1){
1289
1482
      if(e == 0){
1301
1494
  return retval;
1302
1495
}
1303
1496
 
1304
 
__attribute__((nonnull))
1305
1497
static void resolve_callback(AvahiSServiceResolver *r,
1306
1498
                             AvahiIfIndex interface,
1307
1499
                             AvahiProtocol proto,
1444
1636
__attribute__((nonnull, warn_unused_result))
1445
1637
bool get_flags(const char *ifname, struct ifreq *ifr){
1446
1638
  int ret;
1447
 
  error_t ret_errno;
 
1639
  int old_errno;
1448
1640
  
1449
1641
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1450
1642
  if(s < 0){
1451
 
    ret_errno = errno;
 
1643
    old_errno = errno;
1452
1644
    perror_plus("socket");
1453
 
    errno = ret_errno;
 
1645
    errno = old_errno;
1454
1646
    return false;
1455
1647
  }
1456
 
  strcpy(ifr->ifr_name, ifname);
 
1648
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
 
1649
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1457
1650
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1458
1651
  if(ret == -1){
1459
1652
    if(debug){
1460
 
      ret_errno = errno;
 
1653
      old_errno = errno;
1461
1654
      perror_plus("ioctl SIOCGIFFLAGS");
1462
 
      errno = ret_errno;
 
1655
      errno = old_errno;
1463
1656
    }
1464
1657
    return false;
1465
1658
  }
1729
1922
      return;
1730
1923
    }
1731
1924
  }
1732
 
#ifdef __GLIBC__
1733
 
#if __GLIBC_PREREQ(2, 15)
1734
1925
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1735
1926
                           runnable_hook, alphasort);
1736
 
#else  /* not __GLIBC_PREREQ(2, 15) */
1737
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1738
 
                         alphasort);
1739
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
1740
 
#else   /* not __GLIBC__ */
1741
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1742
 
                         alphasort);
1743
 
#endif  /* not __GLIBC__ */
1744
1927
  if(numhooks == -1){
1745
1928
    perror_plus("scandir");
1746
1929
    return;
1828
2011
        perror_plus("openat");
1829
2012
        _exit(EXIT_FAILURE);
1830
2013
      }
1831
 
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2014
      if(close(hookdir_fd) == -1){
1832
2015
        perror_plus("close");
1833
2016
        _exit(EXIT_FAILURE);
1834
2017
      }
1837
2020
        perror_plus("dup2(devnull, STDIN_FILENO)");
1838
2021
        _exit(EX_OSERR);
1839
2022
      }
1840
 
      ret = (int)TEMP_FAILURE_RETRY(close(devnull));
 
2023
      ret = close(devnull);
1841
2024
      if(ret == -1){
1842
2025
        perror_plus("close");
1843
2026
        _exit(EX_OSERR);
1892
2075
    free(direntry);
1893
2076
  }
1894
2077
  free(direntries);
1895
 
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2078
  if(close(hookdir_fd) == -1){
1896
2079
    perror_plus("close");
1897
2080
  } else {
1898
2081
    hookdir_fd = -1;
1901
2084
}
1902
2085
 
1903
2086
__attribute__((nonnull, warn_unused_result))
1904
 
error_t bring_up_interface(const char *const interface,
1905
 
                           const float delay){
1906
 
  error_t old_errno = errno;
 
2087
int bring_up_interface(const char *const interface,
 
2088
                       const float delay){
 
2089
  int old_errno = errno;
1907
2090
  int ret;
1908
2091
  struct ifreq network;
1909
2092
  unsigned int if_index = if_nametoindex(interface);
1919
2102
  }
1920
2103
  
1921
2104
  if(not interface_is_up(interface)){
1922
 
    error_t ret_errno = 0, ioctl_errno = 0;
 
2105
    int ret_errno = 0;
 
2106
    int ioctl_errno = 0;
1923
2107
    if(not get_flags(interface, &network)){
1924
2108
      ret_errno = errno;
1925
2109
      fprintf_plus(stderr, "Failed to get flags for interface "
1938
2122
    }
1939
2123
    
1940
2124
    if(quit_now){
1941
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2125
      ret = close(sd);
1942
2126
      if(ret == -1){
1943
2127
        perror_plus("close");
1944
2128
      }
1994
2178
    }
1995
2179
    
1996
2180
    /* Close the socket */
1997
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2181
    ret = close(sd);
1998
2182
    if(ret == -1){
1999
2183
      perror_plus("close");
2000
2184
    }
2012
2196
  
2013
2197
  /* Sleep checking until interface is running.
2014
2198
     Check every 0.25s, up to total time of delay */
2015
 
  for(int i=0; i < delay * 4; i++){
 
2199
  for(int i = 0; i < delay * 4; i++){
2016
2200
    if(interface_is_running(interface)){
2017
2201
      break;
2018
2202
    }
2028
2212
}
2029
2213
 
2030
2214
__attribute__((nonnull, warn_unused_result))
2031
 
error_t take_down_interface(const char *const interface){
2032
 
  error_t old_errno = errno;
 
2215
int take_down_interface(const char *const interface){
 
2216
  int old_errno = errno;
2033
2217
  struct ifreq network;
2034
2218
  unsigned int if_index = if_nametoindex(interface);
2035
2219
  if(if_index == 0){
2038
2222
    return ENXIO;
2039
2223
  }
2040
2224
  if(interface_is_up(interface)){
2041
 
    error_t ret_errno = 0, ioctl_errno = 0;
 
2225
    int ret_errno = 0;
 
2226
    int ioctl_errno = 0;
2042
2227
    if(not get_flags(interface, &network) and debug){
2043
2228
      ret_errno = errno;
2044
2229
      fprintf_plus(stderr, "Failed to get flags for interface "
2082
2267
    }
2083
2268
    
2084
2269
    /* Close the socket */
2085
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2270
    int ret = close(sd);
2086
2271
    if(ret == -1){
2087
2272
      perror_plus("close");
2088
2273
    }
2103
2288
}
2104
2289
 
2105
2290
int main(int argc, char *argv[]){
2106
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
2107
 
                        .priority = "SECURE256:!CTYPE-X.509:"
2108
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
2109
 
                        .interfaces = NULL, .interfaces_size = 0 };
 
2291
  mandos_context mc = { .server = NULL, .dh_bits = 0,
 
2292
                        .priority = "SECURE256:!CTYPE-X.509"
 
2293
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
 
2294
                        .current_server = NULL, .interfaces = NULL,
 
2295
                        .interfaces_size = 0 };
2110
2296
  AvahiSServiceBrowser *sb = NULL;
2111
2297
  error_t ret_errno;
2112
2298
  int ret;
2121
2307
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2122
2308
  const char *seckey = PATHDIR "/" SECKEY;
2123
2309
  const char *pubkey = PATHDIR "/" PUBKEY;
 
2310
  const char *dh_params_file = NULL;
2124
2311
  char *interfaces_hooks = NULL;
2125
2312
  
2126
2313
  bool gnutls_initialized = false;
2179
2366
        .doc = "Bit length of the prime number used in the"
2180
2367
        " Diffie-Hellman key exchange",
2181
2368
        .group = 2 },
 
2369
      { .name = "dh-params", .key = 134,
 
2370
        .arg = "FILE",
 
2371
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
 
2372
        " for the Diffie-Hellman key exchange",
 
2373
        .group = 2 },
2182
2374
      { .name = "priority", .key = 130,
2183
2375
        .arg = "STRING",
2184
2376
        .doc = "GnuTLS priority string for the TLS handshake",
2239
2431
        }
2240
2432
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2241
2433
        break;
 
2434
      case 134:                 /* --dh-params */
 
2435
        dh_params_file = arg;
 
2436
        break;
2242
2437
      case 130:                 /* --priority */
2243
2438
        mc.priority = arg;
2244
2439
        break;
2284
2479
                         .args_doc = "",
2285
2480
                         .doc = "Mandos client -- Get and decrypt"
2286
2481
                         " passwords from a Mandos server" };
2287
 
    ret = argp_parse(&argp, argc, argv,
2288
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2289
 
    switch(ret){
 
2482
    ret_errno = argp_parse(&argp, argc, argv,
 
2483
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2484
    switch(ret_errno){
2290
2485
    case 0:
2291
2486
      break;
2292
2487
    case ENOMEM:
2293
2488
    default:
2294
 
      errno = ret;
 
2489
      errno = ret_errno;
2295
2490
      perror_plus("argp_parse");
2296
2491
      exitcode = EX_OSERR;
2297
2492
      goto end;
2303
2498
  
2304
2499
  {
2305
2500
    /* Work around Debian bug #633582:
2306
 
       <http://bugs.debian.org/633582> */
 
2501
       <https://bugs.debian.org/633582> */
2307
2502
    
2308
2503
    /* Re-raise privileges */
2309
 
    ret_errno = raise_privileges();
2310
 
    if(ret_errno != 0){
2311
 
      errno = ret_errno;
 
2504
    ret = raise_privileges();
 
2505
    if(ret != 0){
 
2506
      errno = ret;
2312
2507
      perror_plus("Failed to raise privileges");
2313
2508
    } else {
2314
2509
      struct stat st;
2330
2525
              }
2331
2526
            }
2332
2527
          }
2333
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2528
          close(seckey_fd);
2334
2529
        }
2335
2530
      }
2336
2531
      
2351
2546
              }
2352
2547
            }
2353
2548
          }
2354
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2549
          close(pubkey_fd);
 
2550
        }
 
2551
      }
 
2552
      
 
2553
      if(dh_params_file != NULL
 
2554
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
 
2555
        int dhparams_fd = open(dh_params_file, O_RDONLY);
 
2556
        if(dhparams_fd == -1){
 
2557
          perror_plus("open");
 
2558
        } else {
 
2559
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
 
2560
          if(ret == -1){
 
2561
            perror_plus("fstat");
 
2562
          } else {
 
2563
            if(S_ISREG(st.st_mode)
 
2564
               and st.st_uid == 0 and st.st_gid == 0){
 
2565
              ret = fchown(dhparams_fd, uid, gid);
 
2566
              if(ret == -1){
 
2567
                perror_plus("fchown");
 
2568
              }
 
2569
            }
 
2570
          }
 
2571
          close(dhparams_fd);
2355
2572
        }
2356
2573
      }
2357
2574
      
2358
2575
      /* Lower privileges */
2359
 
      ret_errno = lower_privileges();
2360
 
      if(ret_errno != 0){
2361
 
        errno = ret_errno;
 
2576
      ret = lower_privileges();
 
2577
      if(ret != 0){
 
2578
        errno = ret;
2362
2579
        perror_plus("Failed to lower privileges");
2363
2580
      }
2364
2581
    }
2534
2751
      errno = bring_up_interface(interface, delay);
2535
2752
      if(not interface_was_up){
2536
2753
        if(errno != 0){
2537
 
          perror_plus("Failed to bring up interface");
 
2754
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
 
2755
                       " %s\n", interface, strerror(errno));
2538
2756
        } else {
2539
2757
          errno = argz_add(&interfaces_to_take_down,
2540
2758
                           &interfaces_to_take_down_size,
2563
2781
    goto end;
2564
2782
  }
2565
2783
  
2566
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2784
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
2567
2785
  if(ret == -1){
2568
2786
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2569
2787
    exitcode = EX_UNAVAILABLE;
2691
2909
    
2692
2910
    /* Allocate a new server */
2693
2911
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2694
 
                                 &config, NULL, NULL, &ret_errno);
 
2912
                                 &config, NULL, NULL, &ret);
2695
2913
    
2696
2914
    /* Free the Avahi configuration data */
2697
2915
    avahi_server_config_free(&config);
2700
2918
  /* Check if creating the Avahi server object succeeded */
2701
2919
  if(mc.server == NULL){
2702
2920
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2703
 
                 avahi_strerror(ret_errno));
 
2921
                 avahi_strerror(ret));
2704
2922
    exitcode = EX_UNAVAILABLE;
2705
2923
    goto end;
2706
2924
  }
2741
2959
 end:
2742
2960
  
2743
2961
  if(debug){
2744
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2962
    if(signal_received){
 
2963
      fprintf_plus(stderr, "%s exiting due to signal %d: %s\n",
 
2964
                   argv[0], signal_received,
 
2965
                   strsignal(signal_received));
 
2966
    } else {
 
2967
      fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2968
    }
2745
2969
  }
2746
2970
  
2747
2971
  /* Cleanup things */
2758
2982
  
2759
2983
  if(gnutls_initialized){
2760
2984
    gnutls_certificate_free_credentials(mc.cred);
2761
 
    gnutls_global_deinit();
2762
2985
    gnutls_dh_params_deinit(mc.dh_params);
2763
2986
  }
2764
2987
  
2787
3010
  
2788
3011
  /* Re-raise privileges */
2789
3012
  {
2790
 
    ret_errno = raise_privileges();
2791
 
    if(ret_errno != 0){
2792
 
      errno = ret_errno;
 
3013
    ret = raise_privileges();
 
3014
    if(ret != 0){
 
3015
      errno = ret;
2793
3016
      perror_plus("Failed to raise privileges");
2794
3017
    } else {
2795
3018
      
2800
3023
      /* Take down the network interfaces which were brought up */
2801
3024
      {
2802
3025
        char *interface = NULL;
2803
 
        while((interface=argz_next(interfaces_to_take_down,
2804
 
                                   interfaces_to_take_down_size,
2805
 
                                   interface))){
2806
 
          ret_errno = take_down_interface(interface);
2807
 
          if(ret_errno != 0){
2808
 
            errno = ret_errno;
 
3026
        while((interface = argz_next(interfaces_to_take_down,
 
3027
                                     interfaces_to_take_down_size,
 
3028
                                     interface))){
 
3029
          ret = take_down_interface(interface);
 
3030
          if(ret != 0){
 
3031
            errno = ret;
2809
3032
            perror_plus("Failed to take down interface");
2810
3033
          }
2811
3034
        }
2816
3039
      }
2817
3040
    }
2818
3041
    
2819
 
    ret_errno = lower_privileges_permanently();
2820
 
    if(ret_errno != 0){
2821
 
      errno = ret_errno;
 
3042
    ret = lower_privileges_permanently();
 
3043
    if(ret != 0){
 
3044
      errno = ret;
2822
3045
      perror_plus("Failed to lower privileges permanently");
2823
3046
    }
2824
3047
  }
2826
3049
  free(interfaces_to_take_down);
2827
3050
  free(interfaces_hooks);
2828
3051
  
 
3052
  void clean_dir_at(int base, const char * const dirname,
 
3053
                    uintmax_t level){
 
3054
    struct dirent **direntries = NULL;
 
3055
    int dret;
 
3056
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
 
3057
                                                O_RDONLY
 
3058
                                                | O_NOFOLLOW
 
3059
                                                | O_DIRECTORY
 
3060
                                                | O_PATH));
 
3061
    if(dir_fd == -1){
 
3062
      perror_plus("open");
 
3063
    }
 
3064
    int numentries = scandirat(dir_fd, ".", &direntries,
 
3065
                               notdotentries, alphasort);
 
3066
    if(numentries >= 0){
 
3067
      for(int i = 0; i < numentries; i++){
 
3068
        if(debug){
 
3069
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
 
3070
                       dirname, direntries[i]->d_name);
 
3071
        }
 
3072
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
 
3073
        if(dret == -1){
 
3074
          if(errno == EISDIR){
 
3075
              dret = unlinkat(dir_fd, direntries[i]->d_name,
 
3076
                              AT_REMOVEDIR);
 
3077
          }         
 
3078
          if((dret == -1) and (errno == ENOTEMPTY)
 
3079
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
 
3080
                  == 0) and (level == 0)){
 
3081
            /* Recurse only in this special case */
 
3082
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
 
3083
            dret = 0;
 
3084
          }
 
3085
          if(dret == -1){
 
3086
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
 
3087
                         direntries[i]->d_name, strerror(errno));
 
3088
          }
 
3089
        }
 
3090
        free(direntries[i]);
 
3091
      }
 
3092
      
 
3093
      /* need to clean even if 0 because man page doesn't specify */
 
3094
      free(direntries);
 
3095
      if(numentries == -1){
 
3096
        perror_plus("scandirat");
 
3097
      }
 
3098
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
 
3099
      if(dret == -1 and errno != ENOENT){
 
3100
        perror_plus("rmdir");
 
3101
      }
 
3102
    } else {
 
3103
      perror_plus("scandirat");
 
3104
    }
 
3105
    close(dir_fd);
 
3106
  }
 
3107
  
2829
3108
  /* Removes the GPGME temp directory and all files inside */
2830
3109
  if(tempdir != NULL){
2831
 
    struct dirent **direntries = NULL;
2832
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
2833
 
                                                  | O_NOFOLLOW
2834
 
                                                  | O_DIRECTORY
2835
 
                                                  | O_PATH));
2836
 
    if(tempdir_fd == -1){
2837
 
      perror_plus("open");
2838
 
    } else {
2839
 
#ifdef __GLIBC__
2840
 
#if __GLIBC_PREREQ(2, 15)
2841
 
      int numentries = scandirat(tempdir_fd, ".", &direntries,
2842
 
                                 notdotentries, alphasort);
2843
 
#else  /* not __GLIBC_PREREQ(2, 15) */
2844
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2845
 
                               alphasort);
2846
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
2847
 
#else   /* not __GLIBC__ */
2848
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2849
 
                               alphasort);
2850
 
#endif  /* not __GLIBC__ */
2851
 
      if(numentries >= 0){
2852
 
        for(int i = 0; i < numentries; i++){
2853
 
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
2854
 
          if(ret == -1){
2855
 
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
2856
 
                         " \"%s\", 0): %s\n", tempdir,
2857
 
                         direntries[i]->d_name, strerror(errno));
2858
 
          }
2859
 
          free(direntries[i]);
2860
 
        }
2861
 
        
2862
 
        /* need to clean even if 0 because man page doesn't specify */
2863
 
        free(direntries);
2864
 
        if(numentries == -1){
2865
 
          perror_plus("scandir");
2866
 
        }
2867
 
        ret = rmdir(tempdir);
2868
 
        if(ret == -1 and errno != ENOENT){
2869
 
          perror_plus("rmdir");
2870
 
        }
2871
 
      }
2872
 
      TEMP_FAILURE_RETRY(close(tempdir_fd));
2873
 
    }
 
3110
    clean_dir_at(-1, tempdir, 0);
2874
3111
  }
2875
3112
  
2876
3113
  if(quit_now){