/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-07 15:49:49 UTC
  • Revision ID: teddy@recompile.se-20150707154949-vbuj4pc6wf3o1vgz
mandos.service: Use Type=dbus (implicitly).

mandos.service ([Service]/Type): Removed.
               ([Service]/BusName): Uncommented; set to
                                    "se.recompile.Mandos".

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(), strsignal()
51
 
                                */
 
49
#include <string.h>             /* memset(), strcmp(), strlen(),
 
50
                                   strerror(), asprintf(), strcpy() */
52
51
#include <sys/ioctl.h>          /* ioctl */
53
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
54
53
                                   sockaddr_in6, PF_INET6,
58
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
59
58
                                   inet_pton(), connect(),
60
59
                                   getnameinfo() */
61
 
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
 
60
#include <fcntl.h>              /* open(), unlinkat() */
62
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
63
62
                                 */
64
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
65
64
                                   strtoimax() */
66
 
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
67
 
                                   EAI_SYSTEM, ENETUNREACH,
68
 
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
69
 
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
70
 
                                   ENOTEMPTY,
 
65
#include <errno.h>              /* perror(), errno,
71
66
                                   program_invocation_short_name */
72
67
#include <time.h>               /* nanosleep(), time(), sleep() */
73
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
310
305
      return false;
311
306
    }
312
307
    
313
 
    ret = close(fd);
 
308
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
314
309
    if(ret == -1){
315
310
      perror_plus("close");
316
311
    }
518
513
  fprintf_plus(stderr, "GnuTLS: %s", string);
519
514
}
520
515
 
521
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
 
516
__attribute__((nonnull, warn_unused_result))
522
517
static int init_gnutls_global(const char *pubkeyfilename,
523
518
                              const char *seckeyfilename,
524
 
                              const char *dhparamsfilename,
525
519
                              mandos_context *mc){
526
520
  int ret;
527
521
  unsigned int uret;
530
524
    fprintf_plus(stderr, "Initializing GnuTLS\n");
531
525
  }
532
526
  
 
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
  
533
534
  if(debug){
534
535
    /* "Use a log level over 10 to enable all debugging options."
535
536
     * - GnuTLS manual
543
544
  if(ret != GNUTLS_E_SUCCESS){
544
545
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
545
546
                 safer_gnutls_strerror(ret));
 
547
    gnutls_global_deinit();
546
548
    return -1;
547
549
  }
548
550
  
573
575
                 safer_gnutls_strerror(ret));
574
576
    goto globalfail;
575
577
  }
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;
 
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;
587
585
      while(true){
588
 
        params_capacity = incbuffer((char **)&params.data,
589
 
                                    (size_t)params.size,
590
 
                                    (size_t)params_capacity);
591
 
        if(params_capacity == 0){
 
586
        buffer_capacity = incbuffer((char **)&buffer.data,
 
587
                                    (size_t)buffer.size,
 
588
                                    (size_t)buffer_capacity);
 
589
        if(buffer_capacity == 0){
592
590
          perror_plus("incbuffer");
593
 
          free(params.data);
594
 
          params.data = NULL;
595
 
          dhparamsfilename = NULL;
 
591
          free(buffer.data);
 
592
          buffer.data = NULL;
596
593
          break;
597
594
        }
598
 
        ssize_t bytes_read = read(dhpfile,
599
 
                                  params.data + params.size,
 
595
        ssize_t bytes_read = read(secfile, buffer.data + buffer.size,
600
596
                                  BUFFER_SIZE);
601
597
        /* EOF */
602
598
        if(bytes_read == 0){
605
601
        /* check bytes_read for failure */
606
602
        if(bytes_read < 0){
607
603
          perror_plus("read");
608
 
          free(params.data);
609
 
          params.data = NULL;
610
 
          dhparamsfilename = NULL;
611
 
          break;
612
 
        }
613
 
        params.size += (unsigned int)bytes_read;
614
 
      }
615
 
      if(params.data == NULL){
616
 
        dhparamsfilename = NULL;
617
 
      }
618
 
      if(dhparamsfilename == NULL){
619
 
        break;
620
 
      }
621
 
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
622
 
                                          GNUTLS_X509_FMT_PEM);
623
 
      if(ret != GNUTLS_E_SUCCESS){
624
 
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
625
 
                     " \"%s\": %s\n", dhparamsfilename,
626
 
                     safer_gnutls_strerror(ret));
627
 
        dhparamsfilename = NULL;
628
 
      }
629
 
    } while(false);
630
 
  }
631
 
  if(dhparamsfilename == NULL){
632
 
    if(mc->dh_bits == 0){
633
 
      /* Find out the optimal number of DH bits */
634
 
      /* Try to read the private key file */
635
 
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
636
 
      do {
637
 
        int secfile = open(seckeyfilename, O_RDONLY);
638
 
        if(secfile == -1){
639
 
          perror_plus("open");
640
 
          break;
641
 
        }
642
 
        size_t buffer_capacity = 0;
643
 
        while(true){
644
 
          buffer_capacity = incbuffer((char **)&buffer.data,
645
 
                                      (size_t)buffer.size,
646
 
                                      (size_t)buffer_capacity);
647
 
          if(buffer_capacity == 0){
648
 
            perror_plus("incbuffer");
649
 
            free(buffer.data);
650
 
            buffer.data = NULL;
651
 
            break;
652
 
          }
653
 
          ssize_t bytes_read = read(secfile,
654
 
                                    buffer.data + buffer.size,
655
 
                                    BUFFER_SIZE);
656
 
          /* EOF */
657
 
          if(bytes_read == 0){
658
 
            break;
659
 
          }
660
 
          /* check bytes_read for failure */
661
 
          if(bytes_read < 0){
662
 
            perror_plus("read");
663
 
            free(buffer.data);
664
 
            buffer.data = NULL;
665
 
            break;
666
 
          }
667
 
          buffer.size += (unsigned int)bytes_read;
668
 
        }
669
 
        close(secfile);
670
 
      } while(false);
671
 
      /* If successful, use buffer to parse private key */
672
 
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
673
 
      if(buffer.data != NULL){
674
 
        {
675
 
          gnutls_openpgp_privkey_t privkey = NULL;
676
 
          ret = gnutls_openpgp_privkey_init(&privkey);
 
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);
677
627
          if(ret != GNUTLS_E_SUCCESS){
678
 
            fprintf_plus(stderr, "Error initializing OpenPGP key"
679
 
                         " structure: %s",
 
628
            fprintf_plus(stderr, "Error importing OpenPGP key : %s",
680
629
                         safer_gnutls_strerror(ret));
681
 
            free(buffer.data);
682
 
            buffer.data = NULL;
683
 
          } else {
684
 
            ret = gnutls_openpgp_privkey_import
685
 
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
686
 
            if(ret != GNUTLS_E_SUCCESS){
687
 
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
688
 
                           safer_gnutls_strerror(ret));
689
 
              privkey = NULL;
690
 
            }
691
 
            free(buffer.data);
692
 
            buffer.data = NULL;
693
 
            if(privkey != NULL){
694
 
              /* Use private key to suggest an appropriate
695
 
                 sec_param */
696
 
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
697
 
              gnutls_openpgp_privkey_deinit(privkey);
698
 
              if(debug){
699
 
                fprintf_plus(stderr, "This OpenPGP key implies using"
700
 
                             " a GnuTLS security parameter \"%s\".\n",
701
 
                             safe_string(gnutls_sec_param_get_name
702
 
                                         (sec_param)));
703
 
              }
704
 
            }
 
630
            privkey = NULL;
705
631
          }
706
 
        }
707
 
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
708
 
          /* Err on the side of caution */
709
 
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
710
 
          if(debug){
711
 
            fprintf_plus(stderr, "Falling back to security parameter"
712
 
                         " \"%s\"\n",
713
 
                         safe_string(gnutls_sec_param_get_name
714
 
                                     (sec_param)));
 
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
            }
715
644
          }
716
645
        }
717
646
      }
718
 
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
719
 
      if(uret != 0){
720
 
        mc->dh_bits = uret;
 
647
      if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
 
648
        /* Err on the side of caution */
 
649
        sec_param = GNUTLS_SEC_PARAM_ULTRA;
721
650
        if(debug){
722
 
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
723
 
                       " implies %u DH bits; using that.\n",
 
651
          fprintf_plus(stderr, "Falling back to security parameter"
 
652
                       " \"%s\"\n",
724
653
                       safe_string(gnutls_sec_param_get_name
725
 
                                   (sec_param)),
726
 
                       mc->dh_bits);
 
654
                                   (sec_param)));
727
655
        }
728
 
      } else {
729
 
        fprintf_plus(stderr, "Failed to get implied number of DH"
730
 
                     " bits for security parameter \"%s\"): %s\n",
 
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",
731
664
                     safe_string(gnutls_sec_param_get_name
732
665
                                 (sec_param)),
733
 
                     safer_gnutls_strerror(ret));
734
 
        goto globalfail;
 
666
                     mc->dh_bits);
735
667
      }
736
 
    } else if(debug){
737
 
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
738
 
                   mc->dh_bits);
739
 
    }
740
 
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
741
 
    if(ret != GNUTLS_E_SUCCESS){
742
 
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
743
 
                   " bits): %s\n", mc->dh_bits,
 
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)),
744
672
                   safer_gnutls_strerror(ret));
745
673
      goto globalfail;
746
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
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
749
687
  
750
688
  return 0;
752
690
 globalfail:
753
691
  
754
692
  gnutls_certificate_free_credentials(mc->cred);
 
693
  gnutls_global_deinit();
755
694
  gnutls_dh_params_deinit(mc->dh_params);
756
695
  return -1;
757
696
}
809
748
  /* ignore client certificate if any. */
810
749
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
811
750
  
 
751
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
752
  
812
753
  return 0;
813
754
}
814
755
 
818
759
 
819
760
/* Set effective uid to 0, return errno */
820
761
__attribute__((warn_unused_result))
821
 
int raise_privileges(void){
822
 
  int old_errno = errno;
823
 
  int ret = 0;
 
762
error_t raise_privileges(void){
 
763
  error_t old_errno = errno;
 
764
  error_t ret_errno = 0;
824
765
  if(seteuid(0) == -1){
825
 
    ret = errno;
 
766
    ret_errno = errno;
826
767
  }
827
768
  errno = old_errno;
828
 
  return ret;
 
769
  return ret_errno;
829
770
}
830
771
 
831
772
/* Set effective and real user ID to 0.  Return errno. */
832
773
__attribute__((warn_unused_result))
833
 
int raise_privileges_permanently(void){
834
 
  int old_errno = errno;
835
 
  int ret = raise_privileges();
836
 
  if(ret != 0){
 
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){
837
778
    errno = old_errno;
838
 
    return ret;
 
779
    return ret_errno;
839
780
  }
840
781
  if(setuid(0) == -1){
841
 
    ret = errno;
 
782
    ret_errno = errno;
842
783
  }
843
784
  errno = old_errno;
844
 
  return ret;
 
785
  return ret_errno;
845
786
}
846
787
 
847
788
/* Set effective user ID to unprivileged saved user ID */
848
789
__attribute__((warn_unused_result))
849
 
int lower_privileges(void){
850
 
  int old_errno = errno;
851
 
  int ret = 0;
 
790
error_t lower_privileges(void){
 
791
  error_t old_errno = errno;
 
792
  error_t ret_errno = 0;
852
793
  if(seteuid(uid) == -1){
853
 
    ret = errno;
 
794
    ret_errno = errno;
854
795
  }
855
796
  errno = old_errno;
856
 
  return ret;
 
797
  return ret_errno;
857
798
}
858
799
 
859
800
/* Lower privileges permanently */
860
801
__attribute__((warn_unused_result))
861
 
int lower_privileges_permanently(void){
862
 
  int old_errno = errno;
863
 
  int ret = 0;
 
802
error_t lower_privileges_permanently(void){
 
803
  error_t old_errno = errno;
 
804
  error_t ret_errno = 0;
864
805
  if(setuid(uid) == -1){
865
 
    ret = errno;
 
806
    ret_errno = errno;
866
807
  }
867
808
  errno = old_errno;
868
 
  return ret;
 
809
  return ret_errno;
869
810
}
870
811
 
871
812
/* Helper function to add_local_route() and delete_local_route() */
927
868
      perror_plus("dup2(devnull, STDIN_FILENO)");
928
869
      _exit(EX_OSERR);
929
870
    }
930
 
    ret = close(devnull);
 
871
    ret = (int)TEMP_FAILURE_RETRY(close(devnull));
931
872
    if(ret == -1){
932
873
      perror_plus("close");
933
874
      _exit(EX_OSERR);
950
891
                                                   helper, O_RDONLY));
951
892
    if(helper_fd == -1){
952
893
      perror_plus("openat");
953
 
      close(helperdir_fd);
954
894
      _exit(EX_UNAVAILABLE);
955
895
    }
956
 
    close(helperdir_fd);
 
896
    TEMP_FAILURE_RETRY(close(helperdir_fd));
957
897
#ifdef __GNUC__
958
898
#pragma GCC diagnostic push
959
899
#pragma GCC diagnostic ignored "-Wcast-qual"
1127
1067
    goto mandos_end;
1128
1068
  }
1129
1069
  
 
1070
  memset(&to, 0, sizeof(to));
1130
1071
  if(af == AF_INET6){
1131
 
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
1132
 
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
1133
 
    ret = inet_pton(af, ip, &to6->sin6_addr);
 
1072
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
1073
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
1134
1074
  } else {                      /* IPv4 */
1135
 
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
1136
 
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
1137
 
    ret = inet_pton(af, ip, &to4->sin_addr);
 
1075
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
1076
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
1138
1077
  }
1139
1078
  if(ret < 0 ){
1140
1079
    int e = errno;
1219
1158
                    sizeof(struct sockaddr_in));
1220
1159
    }
1221
1160
    if(ret < 0){
1222
 
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
 
1161
      if(errno == ENETUNREACH
1223
1162
         and if_index != AVAHI_IF_UNSPEC
1224
1163
         and connect_to == NULL
1225
1164
         and not route_added and
1238
1177
           with an explicit route added with the server's address.
1239
1178
           
1240
1179
           Avahi bug reference:
1241
 
           https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
 
1180
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1242
1181
           https://bugs.debian.org/587961
1243
1182
        */
1244
1183
        if(debug){
1424
1363
                                               &decrypted_buffer, mc);
1425
1364
    if(decrypted_buffer_size >= 0){
1426
1365
      
1427
 
      clearerr(stdout);
1428
1366
      written = 0;
1429
1367
      while(written < (size_t) decrypted_buffer_size){
1430
1368
        if(quit_now){
1446
1384
        }
1447
1385
        written += (size_t)ret;
1448
1386
      }
1449
 
      ret = fflush(stdout);
1450
 
      if(ret != 0){
1451
 
        int e = errno;
1452
 
        if(debug){
1453
 
          fprintf_plus(stderr, "Error writing encrypted data: %s\n",
1454
 
                       strerror(errno));
1455
 
        }
1456
 
        errno = e;
1457
 
        goto mandos_end;
1458
 
      }
1459
1387
      retval = 0;
1460
1388
    }
1461
1389
  }
1474
1402
    free(decrypted_buffer);
1475
1403
    free(buffer);
1476
1404
    if(tcp_sd >= 0){
1477
 
      ret = close(tcp_sd);
 
1405
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1478
1406
    }
1479
1407
    if(ret == -1){
1480
1408
      if(e == 0){
1635
1563
__attribute__((nonnull, warn_unused_result))
1636
1564
bool get_flags(const char *ifname, struct ifreq *ifr){
1637
1565
  int ret;
1638
 
  int old_errno;
 
1566
  error_t ret_errno;
1639
1567
  
1640
1568
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1641
1569
  if(s < 0){
1642
 
    old_errno = errno;
 
1570
    ret_errno = errno;
1643
1571
    perror_plus("socket");
1644
 
    errno = old_errno;
 
1572
    errno = ret_errno;
1645
1573
    return false;
1646
1574
  }
1647
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1648
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
 
1575
  strcpy(ifr->ifr_name, ifname);
1649
1576
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1650
1577
  if(ret == -1){
1651
1578
    if(debug){
1652
 
      old_errno = errno;
 
1579
      ret_errno = errno;
1653
1580
      perror_plus("ioctl SIOCGIFFLAGS");
1654
 
      errno = old_errno;
 
1581
      errno = ret_errno;
1655
1582
    }
1656
1583
    return false;
1657
1584
  }
1921
1848
      return;
1922
1849
    }
1923
1850
  }
 
1851
#ifdef __GLIBC__
 
1852
#if __GLIBC_PREREQ(2, 15)
1924
1853
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1925
1854
                           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__ */
1926
1863
  if(numhooks == -1){
1927
1864
    perror_plus("scandir");
1928
1865
    return;
2010
1947
        perror_plus("openat");
2011
1948
        _exit(EXIT_FAILURE);
2012
1949
      }
2013
 
      if(close(hookdir_fd) == -1){
 
1950
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2014
1951
        perror_plus("close");
2015
1952
        _exit(EXIT_FAILURE);
2016
1953
      }
2019
1956
        perror_plus("dup2(devnull, STDIN_FILENO)");
2020
1957
        _exit(EX_OSERR);
2021
1958
      }
2022
 
      ret = close(devnull);
 
1959
      ret = (int)TEMP_FAILURE_RETRY(close(devnull));
2023
1960
      if(ret == -1){
2024
1961
        perror_plus("close");
2025
1962
        _exit(EX_OSERR);
2074
2011
    free(direntry);
2075
2012
  }
2076
2013
  free(direntries);
2077
 
  if(close(hookdir_fd) == -1){
 
2014
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2078
2015
    perror_plus("close");
2079
2016
  } else {
2080
2017
    hookdir_fd = -1;
2083
2020
}
2084
2021
 
2085
2022
__attribute__((nonnull, warn_unused_result))
2086
 
int bring_up_interface(const char *const interface,
2087
 
                       const float delay){
2088
 
  int old_errno = errno;
 
2023
error_t bring_up_interface(const char *const interface,
 
2024
                           const float delay){
 
2025
  error_t old_errno = errno;
2089
2026
  int ret;
2090
2027
  struct ifreq network;
2091
2028
  unsigned int if_index = if_nametoindex(interface);
2101
2038
  }
2102
2039
  
2103
2040
  if(not interface_is_up(interface)){
2104
 
    int ret_errno = 0;
2105
 
    int ioctl_errno = 0;
 
2041
    error_t ret_errno = 0, ioctl_errno = 0;
2106
2042
    if(not get_flags(interface, &network)){
2107
2043
      ret_errno = errno;
2108
2044
      fprintf_plus(stderr, "Failed to get flags for interface "
2121
2057
    }
2122
2058
    
2123
2059
    if(quit_now){
2124
 
      ret = close(sd);
 
2060
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2125
2061
      if(ret == -1){
2126
2062
        perror_plus("close");
2127
2063
      }
2177
2113
    }
2178
2114
    
2179
2115
    /* Close the socket */
2180
 
    ret = close(sd);
 
2116
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
2181
2117
    if(ret == -1){
2182
2118
      perror_plus("close");
2183
2119
    }
2211
2147
}
2212
2148
 
2213
2149
__attribute__((nonnull, warn_unused_result))
2214
 
int take_down_interface(const char *const interface){
2215
 
  int old_errno = errno;
 
2150
error_t take_down_interface(const char *const interface){
 
2151
  error_t old_errno = errno;
2216
2152
  struct ifreq network;
2217
2153
  unsigned int if_index = if_nametoindex(interface);
2218
2154
  if(if_index == 0){
2221
2157
    return ENXIO;
2222
2158
  }
2223
2159
  if(interface_is_up(interface)){
2224
 
    int ret_errno = 0;
2225
 
    int ioctl_errno = 0;
 
2160
    error_t ret_errno = 0, ioctl_errno = 0;
2226
2161
    if(not get_flags(interface, &network) and debug){
2227
2162
      ret_errno = errno;
2228
2163
      fprintf_plus(stderr, "Failed to get flags for interface "
2266
2201
    }
2267
2202
    
2268
2203
    /* Close the socket */
2269
 
    int ret = close(sd);
 
2204
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
2270
2205
    if(ret == -1){
2271
2206
      perror_plus("close");
2272
2207
    }
2288
2223
 
2289
2224
int main(int argc, char *argv[]){
2290
2225
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2291
 
                        .priority = "SECURE256:!CTYPE-X.509"
2292
 
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
2293
 
                        .current_server = NULL, .interfaces = NULL,
2294
 
                        .interfaces_size = 0 };
 
2226
                        .priority = "SECURE256:!CTYPE-X.509:"
 
2227
                        "+CTYPE-OPENPGP:!RSA", .current_server = NULL,
 
2228
                        .interfaces = NULL, .interfaces_size = 0 };
2295
2229
  AvahiSServiceBrowser *sb = NULL;
2296
2230
  error_t ret_errno;
2297
2231
  int ret;
2306
2240
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2307
2241
  const char *seckey = PATHDIR "/" SECKEY;
2308
2242
  const char *pubkey = PATHDIR "/" PUBKEY;
2309
 
  const char *dh_params_file = NULL;
2310
2243
  char *interfaces_hooks = NULL;
2311
2244
  
2312
2245
  bool gnutls_initialized = false;
2365
2298
        .doc = "Bit length of the prime number used in the"
2366
2299
        " Diffie-Hellman key exchange",
2367
2300
        .group = 2 },
2368
 
      { .name = "dh-params", .key = 134,
2369
 
        .arg = "FILE",
2370
 
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
2371
 
        " for the Diffie-Hellman key exchange",
2372
 
        .group = 2 },
2373
2301
      { .name = "priority", .key = 130,
2374
2302
        .arg = "STRING",
2375
2303
        .doc = "GnuTLS priority string for the TLS handshake",
2430
2358
        }
2431
2359
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2432
2360
        break;
2433
 
      case 134:                 /* --dh-params */
2434
 
        dh_params_file = arg;
2435
 
        break;
2436
2361
      case 130:                 /* --priority */
2437
2362
        mc.priority = arg;
2438
2363
        break;
2478
2403
                         .args_doc = "",
2479
2404
                         .doc = "Mandos client -- Get and decrypt"
2480
2405
                         " passwords from a Mandos server" };
2481
 
    ret_errno = argp_parse(&argp, argc, argv,
2482
 
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2483
 
    switch(ret_errno){
 
2406
    ret = argp_parse(&argp, argc, argv,
 
2407
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2408
    switch(ret){
2484
2409
    case 0:
2485
2410
      break;
2486
2411
    case ENOMEM:
2487
2412
    default:
2488
 
      errno = ret_errno;
 
2413
      errno = ret;
2489
2414
      perror_plus("argp_parse");
2490
2415
      exitcode = EX_OSERR;
2491
2416
      goto end;
2497
2422
  
2498
2423
  {
2499
2424
    /* Work around Debian bug #633582:
2500
 
       <https://bugs.debian.org/633582> */
 
2425
       <http://bugs.debian.org/633582> */
2501
2426
    
2502
2427
    /* Re-raise privileges */
2503
 
    ret = raise_privileges();
2504
 
    if(ret != 0){
2505
 
      errno = ret;
 
2428
    ret_errno = raise_privileges();
 
2429
    if(ret_errno != 0){
 
2430
      errno = ret_errno;
2506
2431
      perror_plus("Failed to raise privileges");
2507
2432
    } else {
2508
2433
      struct stat st;
2524
2449
              }
2525
2450
            }
2526
2451
          }
2527
 
          close(seckey_fd);
 
2452
          TEMP_FAILURE_RETRY(close(seckey_fd));
2528
2453
        }
2529
2454
      }
2530
2455
      
2545
2470
              }
2546
2471
            }
2547
2472
          }
2548
 
          close(pubkey_fd);
2549
 
        }
2550
 
      }
2551
 
      
2552
 
      if(dh_params_file != NULL
2553
 
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
2554
 
        int dhparams_fd = open(dh_params_file, O_RDONLY);
2555
 
        if(dhparams_fd == -1){
2556
 
          perror_plus("open");
2557
 
        } else {
2558
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
2559
 
          if(ret == -1){
2560
 
            perror_plus("fstat");
2561
 
          } else {
2562
 
            if(S_ISREG(st.st_mode)
2563
 
               and st.st_uid == 0 and st.st_gid == 0){
2564
 
              ret = fchown(dhparams_fd, uid, gid);
2565
 
              if(ret == -1){
2566
 
                perror_plus("fchown");
2567
 
              }
2568
 
            }
2569
 
          }
2570
 
          close(dhparams_fd);
 
2473
          TEMP_FAILURE_RETRY(close(pubkey_fd));
2571
2474
        }
2572
2475
      }
2573
2476
      
2574
2477
      /* Lower privileges */
2575
 
      ret = lower_privileges();
2576
 
      if(ret != 0){
2577
 
        errno = ret;
 
2478
      ret_errno = lower_privileges();
 
2479
      if(ret_errno != 0){
 
2480
        errno = ret_errno;
2578
2481
        perror_plus("Failed to lower privileges");
2579
2482
      }
2580
2483
    }
2750
2653
      errno = bring_up_interface(interface, delay);
2751
2654
      if(not interface_was_up){
2752
2655
        if(errno != 0){
2753
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2754
 
                       " %s\n", interface, strerror(errno));
 
2656
          perror_plus("Failed to bring up interface");
2755
2657
        } else {
2756
2658
          errno = argz_add(&interfaces_to_take_down,
2757
2659
                           &interfaces_to_take_down_size,
2780
2682
    goto end;
2781
2683
  }
2782
2684
  
2783
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
2685
  ret = init_gnutls_global(pubkey, seckey, &mc);
2784
2686
  if(ret == -1){
2785
2687
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2786
2688
    exitcode = EX_UNAVAILABLE;
2908
2810
    
2909
2811
    /* Allocate a new server */
2910
2812
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2911
 
                                 &config, NULL, NULL, &ret);
 
2813
                                 &config, NULL, NULL, &ret_errno);
2912
2814
    
2913
2815
    /* Free the Avahi configuration data */
2914
2816
    avahi_server_config_free(&config);
2917
2819
  /* Check if creating the Avahi server object succeeded */
2918
2820
  if(mc.server == NULL){
2919
2821
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2920
 
                 avahi_strerror(ret));
 
2822
                 avahi_strerror(ret_errno));
2921
2823
    exitcode = EX_UNAVAILABLE;
2922
2824
    goto end;
2923
2825
  }
2958
2860
 end:
2959
2861
  
2960
2862
  if(debug){
2961
 
    if(signal_received){
2962
 
      fprintf_plus(stderr, "%s exiting due to signal %d: %s\n",
2963
 
                   argv[0], signal_received,
2964
 
                   strsignal(signal_received));
2965
 
    } else {
2966
 
      fprintf_plus(stderr, "%s exiting\n", argv[0]);
2967
 
    }
 
2863
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2968
2864
  }
2969
2865
  
2970
2866
  /* Cleanup things */
2981
2877
  
2982
2878
  if(gnutls_initialized){
2983
2879
    gnutls_certificate_free_credentials(mc.cred);
 
2880
    gnutls_global_deinit();
2984
2881
    gnutls_dh_params_deinit(mc.dh_params);
2985
2882
  }
2986
2883
  
3009
2906
  
3010
2907
  /* Re-raise privileges */
3011
2908
  {
3012
 
    ret = raise_privileges();
3013
 
    if(ret != 0){
3014
 
      errno = ret;
 
2909
    ret_errno = raise_privileges();
 
2910
    if(ret_errno != 0){
 
2911
      errno = ret_errno;
3015
2912
      perror_plus("Failed to raise privileges");
3016
2913
    } else {
3017
2914
      
3025
2922
        while((interface=argz_next(interfaces_to_take_down,
3026
2923
                                   interfaces_to_take_down_size,
3027
2924
                                   interface))){
3028
 
          ret = take_down_interface(interface);
3029
 
          if(ret != 0){
3030
 
            errno = ret;
 
2925
          ret_errno = take_down_interface(interface);
 
2926
          if(ret_errno != 0){
 
2927
            errno = ret_errno;
3031
2928
            perror_plus("Failed to take down interface");
3032
2929
          }
3033
2930
        }
3038
2935
      }
3039
2936
    }
3040
2937
    
3041
 
    ret = lower_privileges_permanently();
3042
 
    if(ret != 0){
3043
 
      errno = ret;
 
2938
    ret_errno = lower_privileges_permanently();
 
2939
    if(ret_errno != 0){
 
2940
      errno = ret_errno;
3044
2941
      perror_plus("Failed to lower privileges permanently");
3045
2942
    }
3046
2943
  }
3048
2945
  free(interfaces_to_take_down);
3049
2946
  free(interfaces_hooks);
3050
2947
  
3051
 
  void clean_dir_at(int base, const char * const dirname,
3052
 
                    uintmax_t level){
3053
 
    struct dirent **direntries = NULL;
3054
 
    int dret;
3055
 
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
3056
 
                                                O_RDONLY
3057
 
                                                | O_NOFOLLOW
3058
 
                                                | O_DIRECTORY
3059
 
                                                | O_PATH));
3060
 
    if(dir_fd == -1){
3061
 
      perror_plus("open");
3062
 
    }
3063
 
    int numentries = scandirat(dir_fd, ".", &direntries,
3064
 
                               notdotentries, alphasort);
3065
 
    if(numentries >= 0){
3066
 
      for(int i = 0; i < numentries; i++){
3067
 
        if(debug){
3068
 
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
3069
 
                       dirname, direntries[i]->d_name);
3070
 
        }
3071
 
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
3072
 
        if(dret == -1){
3073
 
          if(errno == EISDIR){
3074
 
              dret = unlinkat(dir_fd, direntries[i]->d_name,
3075
 
                              AT_REMOVEDIR);
3076
 
          }         
3077
 
          if((dret == -1) and (errno == ENOTEMPTY)
3078
 
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
3079
 
                  == 0) and (level == 0)){
3080
 
            /* Recurse only in this special case */
3081
 
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
3082
 
            dret = 0;
3083
 
          }
3084
 
          if(dret == -1){
3085
 
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
3086
 
                         direntries[i]->d_name, strerror(errno));
3087
 
          }
3088
 
        }
3089
 
        free(direntries[i]);
3090
 
      }
3091
 
      
3092
 
      /* need to clean even if 0 because man page doesn't specify */
3093
 
      free(direntries);
3094
 
      if(numentries == -1){
3095
 
        perror_plus("scandirat");
3096
 
      }
3097
 
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
3098
 
      if(dret == -1 and errno != ENOENT){
3099
 
        perror_plus("rmdir");
3100
 
      }
3101
 
    } else {
3102
 
      perror_plus("scandirat");
3103
 
    }
3104
 
    close(dir_fd);
3105
 
  }
3106
 
  
3107
2948
  /* Removes the GPGME temp directory and all files inside */
3108
2949
  if(tempdir != NULL){
3109
 
    clean_dir_at(-1, tempdir, 0);
 
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
2993
  }
3111
2994
  
3112
2995
  if(quit_now){