/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: 2017-02-23 20:20:34 UTC
  • mfrom: (237.7.447 trunk)
  • Revision ID: teddy@recompile.se-20170223202034-0820bcq0k7d1j9kf
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-2015 Teddy Hogeborn
13
 
 * Copyright © 2008-2015 Björn Påhlsson
 
12
 * Copyright © 2008-2017 Teddy Hogeborn
 
13
 * Copyright © 2008-2017 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
    }
513
518
  fprintf_plus(stderr, "GnuTLS: %s", string);
514
519
}
515
520
 
516
 
__attribute__((nonnull, warn_unused_result))
 
521
__attribute__((nonnull(1, 2, 4), warn_unused_result))
517
522
static int init_gnutls_global(const char *pubkeyfilename,
518
523
                              const char *seckeyfilename,
 
524
                              const char *dhparamsfilename,
519
525
                              mandos_context *mc){
520
526
  int ret;
521
527
  unsigned int uret;
524
530
    fprintf_plus(stderr, "Initializing GnuTLS\n");
525
531
  }
526
532
  
527
 
  ret = gnutls_global_init();
528
 
  if(ret != GNUTLS_E_SUCCESS){
529
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
530
 
                 safer_gnutls_strerror(ret));
531
 
    return -1;
532
 
  }
533
 
  
534
533
  if(debug){
535
534
    /* "Use a log level over 10 to enable all debugging options."
536
535
     * - GnuTLS manual
544
543
  if(ret != GNUTLS_E_SUCCESS){
545
544
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
546
545
                 safer_gnutls_strerror(ret));
547
 
    gnutls_global_deinit();
548
546
    return -1;
549
547
  }
550
548
  
575
573
                 safer_gnutls_strerror(ret));
576
574
    goto globalfail;
577
575
  }
578
 
  if(mc->dh_bits == 0){
579
 
    /* Find out the optimal number of DH bits */
580
 
    /* Try to read the private key file */
581
 
    gnutls_datum_t buffer = { .data = NULL, .size = 0 };
582
 
    {
583
 
      int secfile = open(seckeyfilename, O_RDONLY);
584
 
      size_t buffer_capacity = 0;
 
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;
585
587
      while(true){
586
 
        buffer_capacity = incbuffer((char **)&buffer.data,
587
 
                                    (size_t)buffer.size,
588
 
                                    (size_t)buffer_capacity);
589
 
        if(buffer_capacity == 0){
 
588
        params_capacity = incbuffer((char **)&params.data,
 
589
                                    (size_t)params.size,
 
590
                                    (size_t)params_capacity);
 
591
        if(params_capacity == 0){
590
592
          perror_plus("incbuffer");
591
 
          free(buffer.data);
592
 
          buffer.data = NULL;
 
593
          free(params.data);
 
594
          params.data = NULL;
 
595
          dhparamsfilename = NULL;
593
596
          break;
594
597
        }
595
 
        ssize_t bytes_read = read(secfile, buffer.data + buffer.size,
 
598
        ssize_t bytes_read = read(dhpfile,
 
599
                                  params.data + params.size,
596
600
                                  BUFFER_SIZE);
597
601
        /* EOF */
598
602
        if(bytes_read == 0){
601
605
        /* check bytes_read for failure */
602
606
        if(bytes_read < 0){
603
607
          perror_plus("read");
604
 
          free(buffer.data);
605
 
          buffer.data = NULL;
606
 
          break;
607
 
        }
608
 
        buffer.size += (unsigned int)bytes_read;
609
 
      }
610
 
      close(secfile);
611
 
    }
612
 
    /* If successful, use buffer to parse private key */
613
 
    gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
614
 
    if(buffer.data != NULL){
615
 
      {
616
 
        gnutls_openpgp_privkey_t privkey = NULL;
617
 
        ret = gnutls_openpgp_privkey_init(&privkey);
618
 
        if(ret != GNUTLS_E_SUCCESS){
619
 
          fprintf_plus(stderr, "Error initializing OpenPGP key"
620
 
                       " structure: %s", safer_gnutls_strerror(ret));
621
 
          free(buffer.data);
622
 
          buffer.data = NULL;
623
 
        } else {
624
 
          ret = gnutls_openpgp_privkey_import(privkey, &buffer,
625
 
                                            GNUTLS_OPENPGP_FMT_BASE64,
626
 
                                              "", 0);
 
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);
627
678
          if(ret != GNUTLS_E_SUCCESS){
628
 
            fprintf_plus(stderr, "Error importing OpenPGP key : %s",
 
679
            fprintf_plus(stderr, "Error initializing OpenPGP key"
 
680
                         " structure: %s",
629
681
                         safer_gnutls_strerror(ret));
630
 
            privkey = NULL;
 
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
            }
631
706
          }
632
 
          free(buffer.data);
633
 
          buffer.data = NULL;
634
 
          if(privkey != NULL){
635
 
            /* Use private key to suggest an appropriate sec_param */
636
 
            sec_param = gnutls_openpgp_privkey_sec_param(privkey);
637
 
            gnutls_openpgp_privkey_deinit(privkey);
638
 
            if(debug){
639
 
              fprintf_plus(stderr, "This OpenPGP key implies using a"
640
 
                           " GnuTLS security parameter \"%s\".\n",
641
 
                           safe_string(gnutls_sec_param_get_name
642
 
                                       (sec_param)));
643
 
            }
 
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)));
644
716
          }
645
717
        }
646
718
      }
647
 
      if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
648
 
        /* Err on the side of caution */
649
 
        sec_param = GNUTLS_SEC_PARAM_ULTRA;
 
719
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
 
720
      if(uret != 0){
 
721
        mc->dh_bits = uret;
650
722
        if(debug){
651
 
          fprintf_plus(stderr, "Falling back to security parameter"
652
 
                       " \"%s\"\n",
 
723
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
 
724
                       " implies %u DH bits; using that.\n",
653
725
                       safe_string(gnutls_sec_param_get_name
654
 
                                   (sec_param)));
 
726
                                   (sec_param)),
 
727
                       mc->dh_bits);
655
728
        }
656
 
      }
657
 
    }
658
 
    uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
659
 
    if(uret != 0){
660
 
      mc->dh_bits = uret;
661
 
      if(debug){
662
 
        fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
663
 
                     " implies %u DH bits; using that.\n",
 
729
      } else {
 
730
        fprintf_plus(stderr, "Failed to get implied number of DH"
 
731
                     " bits for security parameter \"%s\"): %s\n",
664
732
                     safe_string(gnutls_sec_param_get_name
665
733
                                 (sec_param)),
666
 
                     mc->dh_bits);
 
734
                     safer_gnutls_strerror(ret));
 
735
        goto globalfail;
667
736
      }
668
 
    } else {
669
 
      fprintf_plus(stderr, "Failed to get implied number of DH"
670
 
                   " bits for security parameter \"%s\"): %s\n",
671
 
                   safe_string(gnutls_sec_param_get_name(sec_param)),
 
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,
672
745
                   safer_gnutls_strerror(ret));
673
746
      goto globalfail;
674
747
    }
675
 
  } else if(debug){
676
 
    fprintf_plus(stderr, "DH bits explicitly set to %u\n",
677
 
                 mc->dh_bits);
678
 
  }
679
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
680
 
  if(ret != GNUTLS_E_SUCCESS){
681
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation (%u bits):"
682
 
                 " %s\n", mc->dh_bits, safer_gnutls_strerror(ret));
683
 
    goto globalfail;
684
 
  }
685
 
  
 
748
  }
686
749
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
687
750
  
688
751
  return 0;
690
753
 globalfail:
691
754
  
692
755
  gnutls_certificate_free_credentials(mc->cred);
693
 
  gnutls_global_deinit();
694
756
  gnutls_dh_params_deinit(mc->dh_params);
695
757
  return -1;
696
758
}
748
810
  /* ignore client certificate if any. */
749
811
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
750
812
  
751
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
752
 
  
753
813
  return 0;
754
814
}
755
815
 
759
819
 
760
820
/* Set effective uid to 0, return errno */
761
821
__attribute__((warn_unused_result))
762
 
error_t raise_privileges(void){
763
 
  error_t old_errno = errno;
764
 
  error_t ret_errno = 0;
 
822
int raise_privileges(void){
 
823
  int old_errno = errno;
 
824
  int ret = 0;
765
825
  if(seteuid(0) == -1){
766
 
    ret_errno = errno;
 
826
    ret = errno;
767
827
  }
768
828
  errno = old_errno;
769
 
  return ret_errno;
 
829
  return ret;
770
830
}
771
831
 
772
832
/* Set effective and real user ID to 0.  Return errno. */
773
833
__attribute__((warn_unused_result))
774
 
error_t raise_privileges_permanently(void){
775
 
  error_t old_errno = errno;
776
 
  error_t ret_errno = raise_privileges();
777
 
  if(ret_errno != 0){
 
834
int raise_privileges_permanently(void){
 
835
  int old_errno = errno;
 
836
  int ret = raise_privileges();
 
837
  if(ret != 0){
778
838
    errno = old_errno;
779
 
    return ret_errno;
 
839
    return ret;
780
840
  }
781
841
  if(setuid(0) == -1){
782
 
    ret_errno = errno;
 
842
    ret = errno;
783
843
  }
784
844
  errno = old_errno;
785
 
  return ret_errno;
 
845
  return ret;
786
846
}
787
847
 
788
848
/* Set effective user ID to unprivileged saved user ID */
789
849
__attribute__((warn_unused_result))
790
 
error_t lower_privileges(void){
791
 
  error_t old_errno = errno;
792
 
  error_t ret_errno = 0;
 
850
int lower_privileges(void){
 
851
  int old_errno = errno;
 
852
  int ret = 0;
793
853
  if(seteuid(uid) == -1){
794
 
    ret_errno = errno;
 
854
    ret = errno;
795
855
  }
796
856
  errno = old_errno;
797
 
  return ret_errno;
 
857
  return ret;
798
858
}
799
859
 
800
860
/* Lower privileges permanently */
801
861
__attribute__((warn_unused_result))
802
 
error_t lower_privileges_permanently(void){
803
 
  error_t old_errno = errno;
804
 
  error_t ret_errno = 0;
 
862
int lower_privileges_permanently(void){
 
863
  int old_errno = errno;
 
864
  int ret = 0;
805
865
  if(setuid(uid) == -1){
806
 
    ret_errno = errno;
 
866
    ret = errno;
807
867
  }
808
868
  errno = old_errno;
809
 
  return ret_errno;
 
869
  return ret;
810
870
}
811
871
 
812
872
/* Helper function to add_local_route() and delete_local_route() */
868
928
      perror_plus("dup2(devnull, STDIN_FILENO)");
869
929
      _exit(EX_OSERR);
870
930
    }
871
 
    ret = (int)TEMP_FAILURE_RETRY(close(devnull));
 
931
    ret = close(devnull);
872
932
    if(ret == -1){
873
933
      perror_plus("close");
874
934
      _exit(EX_OSERR);
891
951
                                                   helper, O_RDONLY));
892
952
    if(helper_fd == -1){
893
953
      perror_plus("openat");
 
954
      close(helperdir_fd);
894
955
      _exit(EX_UNAVAILABLE);
895
956
    }
896
 
    TEMP_FAILURE_RETRY(close(helperdir_fd));
 
957
    close(helperdir_fd);
897
958
#ifdef __GNUC__
898
959
#pragma GCC diagnostic push
899
960
#pragma GCC diagnostic ignored "-Wcast-qual"
1018
1079
    bool match = false;
1019
1080
    {
1020
1081
      char *interface = NULL;
1021
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
1022
 
                                 interface))){
 
1082
      while((interface = argz_next(mc->interfaces,
 
1083
                                   mc->interfaces_size,
 
1084
                                   interface))){
1023
1085
        if(if_nametoindex(interface) == (unsigned int)if_index){
1024
1086
          match = true;
1025
1087
          break;
1067
1129
    goto mandos_end;
1068
1130
  }
1069
1131
  
1070
 
  memset(&to, 0, sizeof(to));
1071
1132
  if(af == AF_INET6){
1072
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
1073
 
    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);
1074
1136
  } else {                      /* IPv4 */
1075
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
1076
 
    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);
1077
1140
  }
1078
1141
  if(ret < 0 ){
1079
1142
    int e = errno;
1158
1221
                    sizeof(struct sockaddr_in));
1159
1222
    }
1160
1223
    if(ret < 0){
1161
 
      if(errno == ENETUNREACH
 
1224
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
1162
1225
         and if_index != AVAHI_IF_UNSPEC
1163
1226
         and connect_to == NULL
1164
1227
         and not route_added and
1177
1240
           with an explicit route added with the server's address.
1178
1241
           
1179
1242
           Avahi bug reference:
1180
 
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
 
1243
           https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1181
1244
           https://bugs.debian.org/587961
1182
1245
        */
1183
1246
        if(debug){
1363
1426
                                               &decrypted_buffer, mc);
1364
1427
    if(decrypted_buffer_size >= 0){
1365
1428
      
 
1429
      clearerr(stdout);
1366
1430
      written = 0;
1367
1431
      while(written < (size_t) decrypted_buffer_size){
1368
1432
        if(quit_now){
1384
1448
        }
1385
1449
        written += (size_t)ret;
1386
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
      }
1387
1461
      retval = 0;
1388
1462
    }
1389
1463
  }
1402
1476
    free(decrypted_buffer);
1403
1477
    free(buffer);
1404
1478
    if(tcp_sd >= 0){
1405
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
1479
      ret = close(tcp_sd);
1406
1480
    }
1407
1481
    if(ret == -1){
1408
1482
      if(e == 0){
1420
1494
  return retval;
1421
1495
}
1422
1496
 
1423
 
__attribute__((nonnull))
1424
1497
static void resolve_callback(AvahiSServiceResolver *r,
1425
1498
                             AvahiIfIndex interface,
1426
1499
                             AvahiProtocol proto,
1563
1636
__attribute__((nonnull, warn_unused_result))
1564
1637
bool get_flags(const char *ifname, struct ifreq *ifr){
1565
1638
  int ret;
1566
 
  error_t ret_errno;
 
1639
  int old_errno;
1567
1640
  
1568
1641
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1569
1642
  if(s < 0){
1570
 
    ret_errno = errno;
 
1643
    old_errno = errno;
1571
1644
    perror_plus("socket");
1572
 
    errno = ret_errno;
 
1645
    errno = old_errno;
1573
1646
    return false;
1574
1647
  }
1575
 
  strcpy(ifr->ifr_name, ifname);
 
1648
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
 
1649
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1576
1650
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1577
1651
  if(ret == -1){
1578
1652
    if(debug){
1579
 
      ret_errno = errno;
 
1653
      old_errno = errno;
1580
1654
      perror_plus("ioctl SIOCGIFFLAGS");
1581
 
      errno = ret_errno;
 
1655
      errno = old_errno;
1582
1656
    }
1583
1657
    return false;
1584
1658
  }
1848
1922
      return;
1849
1923
    }
1850
1924
  }
1851
 
#ifdef __GLIBC__
1852
 
#if __GLIBC_PREREQ(2, 15)
1853
1925
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1854
1926
                           runnable_hook, alphasort);
1855
 
#else  /* not __GLIBC_PREREQ(2, 15) */
1856
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1857
 
                         alphasort);
1858
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
1859
 
#else   /* not __GLIBC__ */
1860
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1861
 
                         alphasort);
1862
 
#endif  /* not __GLIBC__ */
1863
1927
  if(numhooks == -1){
1864
1928
    perror_plus("scandir");
1865
1929
    return;
1947
2011
        perror_plus("openat");
1948
2012
        _exit(EXIT_FAILURE);
1949
2013
      }
1950
 
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2014
      if(close(hookdir_fd) == -1){
1951
2015
        perror_plus("close");
1952
2016
        _exit(EXIT_FAILURE);
1953
2017
      }
1956
2020
        perror_plus("dup2(devnull, STDIN_FILENO)");
1957
2021
        _exit(EX_OSERR);
1958
2022
      }
1959
 
      ret = (int)TEMP_FAILURE_RETRY(close(devnull));
 
2023
      ret = close(devnull);
1960
2024
      if(ret == -1){
1961
2025
        perror_plus("close");
1962
2026
        _exit(EX_OSERR);
2011
2075
    free(direntry);
2012
2076
  }
2013
2077
  free(direntries);
2014
 
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2078
  if(close(hookdir_fd) == -1){
2015
2079
    perror_plus("close");
2016
2080
  } else {
2017
2081
    hookdir_fd = -1;
2020
2084
}
2021
2085
 
2022
2086
__attribute__((nonnull, warn_unused_result))
2023
 
error_t bring_up_interface(const char *const interface,
2024
 
                           const float delay){
2025
 
  error_t old_errno = errno;
 
2087
int bring_up_interface(const char *const interface,
 
2088
                       const float delay){
 
2089
  int old_errno = errno;
2026
2090
  int ret;
2027
2091
  struct ifreq network;
2028
2092
  unsigned int if_index = if_nametoindex(interface);
2038
2102
  }
2039
2103
  
2040
2104
  if(not interface_is_up(interface)){
2041
 
    error_t ret_errno = 0, ioctl_errno = 0;
 
2105
    int ret_errno = 0;
 
2106
    int ioctl_errno = 0;
2042
2107
    if(not get_flags(interface, &network)){
2043
2108
      ret_errno = errno;
2044
2109
      fprintf_plus(stderr, "Failed to get flags for interface "
2057
2122
    }
2058
2123
    
2059
2124
    if(quit_now){
2060
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2125
      ret = close(sd);
2061
2126
      if(ret == -1){
2062
2127
        perror_plus("close");
2063
2128
      }
2113
2178
    }
2114
2179
    
2115
2180
    /* Close the socket */
2116
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2181
    ret = close(sd);
2117
2182
    if(ret == -1){
2118
2183
      perror_plus("close");
2119
2184
    }
2131
2196
  
2132
2197
  /* Sleep checking until interface is running.
2133
2198
     Check every 0.25s, up to total time of delay */
2134
 
  for(int i=0; i < delay * 4; i++){
 
2199
  for(int i = 0; i < delay * 4; i++){
2135
2200
    if(interface_is_running(interface)){
2136
2201
      break;
2137
2202
    }
2147
2212
}
2148
2213
 
2149
2214
__attribute__((nonnull, warn_unused_result))
2150
 
error_t take_down_interface(const char *const interface){
2151
 
  error_t old_errno = errno;
 
2215
int take_down_interface(const char *const interface){
 
2216
  int old_errno = errno;
2152
2217
  struct ifreq network;
2153
2218
  unsigned int if_index = if_nametoindex(interface);
2154
2219
  if(if_index == 0){
2157
2222
    return ENXIO;
2158
2223
  }
2159
2224
  if(interface_is_up(interface)){
2160
 
    error_t ret_errno = 0, ioctl_errno = 0;
 
2225
    int ret_errno = 0;
 
2226
    int ioctl_errno = 0;
2161
2227
    if(not get_flags(interface, &network) and debug){
2162
2228
      ret_errno = errno;
2163
2229
      fprintf_plus(stderr, "Failed to get flags for interface "
2201
2267
    }
2202
2268
    
2203
2269
    /* Close the socket */
2204
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2270
    int ret = close(sd);
2205
2271
    if(ret == -1){
2206
2272
      perror_plus("close");
2207
2273
    }
2223
2289
 
2224
2290
int main(int argc, char *argv[]){
2225
2291
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2226
 
                        .priority = "SECURE256:!CTYPE-X.509:"
2227
 
                        "+CTYPE-OPENPGP:!RSA", .current_server = NULL,
2228
 
                        .interfaces = NULL, .interfaces_size = 0 };
 
2292
                        .priority = "SECURE256:!CTYPE-X.509"
 
2293
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
 
2294
                        .current_server = NULL, .interfaces = NULL,
 
2295
                        .interfaces_size = 0 };
2229
2296
  AvahiSServiceBrowser *sb = NULL;
2230
2297
  error_t ret_errno;
2231
2298
  int ret;
2240
2307
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2241
2308
  const char *seckey = PATHDIR "/" SECKEY;
2242
2309
  const char *pubkey = PATHDIR "/" PUBKEY;
 
2310
  const char *dh_params_file = NULL;
2243
2311
  char *interfaces_hooks = NULL;
2244
2312
  
2245
2313
  bool gnutls_initialized = false;
2298
2366
        .doc = "Bit length of the prime number used in the"
2299
2367
        " Diffie-Hellman key exchange",
2300
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 },
2301
2374
      { .name = "priority", .key = 130,
2302
2375
        .arg = "STRING",
2303
2376
        .doc = "GnuTLS priority string for the TLS handshake",
2358
2431
        }
2359
2432
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2360
2433
        break;
 
2434
      case 134:                 /* --dh-params */
 
2435
        dh_params_file = arg;
 
2436
        break;
2361
2437
      case 130:                 /* --priority */
2362
2438
        mc.priority = arg;
2363
2439
        break;
2403
2479
                         .args_doc = "",
2404
2480
                         .doc = "Mandos client -- Get and decrypt"
2405
2481
                         " passwords from a Mandos server" };
2406
 
    ret = argp_parse(&argp, argc, argv,
2407
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2408
 
    switch(ret){
 
2482
    ret_errno = argp_parse(&argp, argc, argv,
 
2483
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2484
    switch(ret_errno){
2409
2485
    case 0:
2410
2486
      break;
2411
2487
    case ENOMEM:
2412
2488
    default:
2413
 
      errno = ret;
 
2489
      errno = ret_errno;
2414
2490
      perror_plus("argp_parse");
2415
2491
      exitcode = EX_OSERR;
2416
2492
      goto end;
2422
2498
  
2423
2499
  {
2424
2500
    /* Work around Debian bug #633582:
2425
 
       <http://bugs.debian.org/633582> */
 
2501
       <https://bugs.debian.org/633582> */
2426
2502
    
2427
2503
    /* Re-raise privileges */
2428
 
    ret_errno = raise_privileges();
2429
 
    if(ret_errno != 0){
2430
 
      errno = ret_errno;
 
2504
    ret = raise_privileges();
 
2505
    if(ret != 0){
 
2506
      errno = ret;
2431
2507
      perror_plus("Failed to raise privileges");
2432
2508
    } else {
2433
2509
      struct stat st;
2449
2525
              }
2450
2526
            }
2451
2527
          }
2452
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2528
          close(seckey_fd);
2453
2529
        }
2454
2530
      }
2455
2531
      
2470
2546
              }
2471
2547
            }
2472
2548
          }
2473
 
          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);
2474
2572
        }
2475
2573
      }
2476
2574
      
2477
2575
      /* Lower privileges */
2478
 
      ret_errno = lower_privileges();
2479
 
      if(ret_errno != 0){
2480
 
        errno = ret_errno;
 
2576
      ret = lower_privileges();
 
2577
      if(ret != 0){
 
2578
        errno = ret;
2481
2579
        perror_plus("Failed to lower privileges");
2482
2580
      }
2483
2581
    }
2653
2751
      errno = bring_up_interface(interface, delay);
2654
2752
      if(not interface_was_up){
2655
2753
        if(errno != 0){
2656
 
          perror_plus("Failed to bring up interface");
 
2754
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
 
2755
                       " %s\n", interface, strerror(errno));
2657
2756
        } else {
2658
2757
          errno = argz_add(&interfaces_to_take_down,
2659
2758
                           &interfaces_to_take_down_size,
2682
2781
    goto end;
2683
2782
  }
2684
2783
  
2685
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2784
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
2686
2785
  if(ret == -1){
2687
2786
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2688
2787
    exitcode = EX_UNAVAILABLE;
2810
2909
    
2811
2910
    /* Allocate a new server */
2812
2911
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2813
 
                                 &config, NULL, NULL, &ret_errno);
 
2912
                                 &config, NULL, NULL, &ret);
2814
2913
    
2815
2914
    /* Free the Avahi configuration data */
2816
2915
    avahi_server_config_free(&config);
2819
2918
  /* Check if creating the Avahi server object succeeded */
2820
2919
  if(mc.server == NULL){
2821
2920
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2822
 
                 avahi_strerror(ret_errno));
 
2921
                 avahi_strerror(ret));
2823
2922
    exitcode = EX_UNAVAILABLE;
2824
2923
    goto end;
2825
2924
  }
2860
2959
 end:
2861
2960
  
2862
2961
  if(debug){
2863
 
    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
    }
2864
2969
  }
2865
2970
  
2866
2971
  /* Cleanup things */
2877
2982
  
2878
2983
  if(gnutls_initialized){
2879
2984
    gnutls_certificate_free_credentials(mc.cred);
2880
 
    gnutls_global_deinit();
2881
2985
    gnutls_dh_params_deinit(mc.dh_params);
2882
2986
  }
2883
2987
  
2906
3010
  
2907
3011
  /* Re-raise privileges */
2908
3012
  {
2909
 
    ret_errno = raise_privileges();
2910
 
    if(ret_errno != 0){
2911
 
      errno = ret_errno;
 
3013
    ret = raise_privileges();
 
3014
    if(ret != 0){
 
3015
      errno = ret;
2912
3016
      perror_plus("Failed to raise privileges");
2913
3017
    } else {
2914
3018
      
2919
3023
      /* Take down the network interfaces which were brought up */
2920
3024
      {
2921
3025
        char *interface = NULL;
2922
 
        while((interface=argz_next(interfaces_to_take_down,
2923
 
                                   interfaces_to_take_down_size,
2924
 
                                   interface))){
2925
 
          ret_errno = take_down_interface(interface);
2926
 
          if(ret_errno != 0){
2927
 
            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;
2928
3032
            perror_plus("Failed to take down interface");
2929
3033
          }
2930
3034
        }
2935
3039
      }
2936
3040
    }
2937
3041
    
2938
 
    ret_errno = lower_privileges_permanently();
2939
 
    if(ret_errno != 0){
2940
 
      errno = ret_errno;
 
3042
    ret = lower_privileges_permanently();
 
3043
    if(ret != 0){
 
3044
      errno = ret;
2941
3045
      perror_plus("Failed to lower privileges permanently");
2942
3046
    }
2943
3047
  }
2945
3049
  free(interfaces_to_take_down);
2946
3050
  free(interfaces_hooks);
2947
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
  
2948
3108
  /* Removes the GPGME temp directory and all files inside */
2949
3109
  if(tempdir != NULL){
2950
 
    struct dirent **direntries = NULL;
2951
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
2952
 
                                                  | O_NOFOLLOW
2953
 
                                                  | O_DIRECTORY
2954
 
                                                  | O_PATH));
2955
 
    if(tempdir_fd == -1){
2956
 
      perror_plus("open");
2957
 
    } else {
2958
 
#ifdef __GLIBC__
2959
 
#if __GLIBC_PREREQ(2, 15)
2960
 
      int numentries = scandirat(tempdir_fd, ".", &direntries,
2961
 
                                 notdotentries, alphasort);
2962
 
#else  /* not __GLIBC_PREREQ(2, 15) */
2963
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2964
 
                               alphasort);
2965
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
2966
 
#else   /* not __GLIBC__ */
2967
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2968
 
                               alphasort);
2969
 
#endif  /* not __GLIBC__ */
2970
 
      if(numentries >= 0){
2971
 
        for(int i = 0; i < numentries; i++){
2972
 
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
2973
 
          if(ret == -1){
2974
 
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
2975
 
                         " \"%s\", 0): %s\n", tempdir,
2976
 
                         direntries[i]->d_name, strerror(errno));
2977
 
          }
2978
 
          free(direntries[i]);
2979
 
        }
2980
 
        
2981
 
        /* need to clean even if 0 because man page doesn't specify */
2982
 
        free(direntries);
2983
 
        if(numentries == -1){
2984
 
          perror_plus("scandir");
2985
 
        }
2986
 
        ret = rmdir(tempdir);
2987
 
        if(ret == -1 and errno != ENOENT){
2988
 
          perror_plus("rmdir");
2989
 
        }
2990
 
      }
2991
 
      TEMP_FAILURE_RETRY(close(tempdir_fd));
2992
 
    }
 
3110
    clean_dir_at(-1, tempdir, 0);
2993
3111
  }
2994
3112
  
2995
3113
  if(quit_now){