/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-02 18:22:22 UTC
  • mto: This revision was merged to the branch mainline in revision 759.
  • Revision ID: teddy@recompile.se-20150702182222-034v03mb8orwhezn
mandos-client: Minor changes to check for more error conditions.

* mandos-client.c (add_remove_local_route): Do TEMP_FAILURE_RETRY
                                            around closing of
                                            /dev/null.  Check return
                                            value when opening helper
                                            directory and helper
                                            executable.
  (run_network_hooks): Cast return value of TEMP_FAILURE_RETRY to int.
                       Do TEMP_FAILURE_RETRY around closing of
                       /dev/null.

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