/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: 2014-07-15 19:35:03 UTC
  • Revision ID: teddy@recompile.se-20140715193503-e18hls7m4rv4l6iq
mandos-client: Fix mem free bug.

* plugins.d/mandos-client.c (add_server): Hide warning.
  (main): Free server->ip too, not just the server struct.

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-2018 Teddy Hogeborn
13
 
 * Copyright © 2008-2018 Björn Påhlsson
14
 
 * 
15
 
 * This file is part of Mandos.
16
 
 * 
17
 
 * Mandos is free software: you can redistribute it and/or modify it
18
 
 * under the terms of the GNU General Public License as published by
19
 
 * the Free Software Foundation, either version 3 of the License, or
20
 
 * (at your option) any later version.
21
 
 * 
22
 
 * Mandos is distributed in the hope that it will be useful, but
 
12
 * Copyright © 2008-2014 Teddy Hogeborn
 
13
 * Copyright © 2008-2014 Björn Påhlsson
 
14
 * 
 
15
 * This program is free software: you can redistribute it and/or
 
16
 * modify it under the terms of the GNU General Public License as
 
17
 * published by the Free Software Foundation, either version 3 of the
 
18
 * License, or (at your option) any later version.
 
19
 * 
 
20
 * This program is distributed in the hope that it will be useful, but
23
21
 * WITHOUT ANY WARRANTY; without even the implied warranty of
24
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25
23
 * General Public License for more details.
26
24
 * 
27
25
 * You should have received a copy of the GNU General Public License
28
 
 * along with Mandos.  If not, see <http://www.gnu.org/licenses/>.
 
26
 * along with this program.  If not, see
 
27
 * <http://www.gnu.org/licenses/>.
29
28
 * 
30
29
 * Contact the authors at <mandos@recompile.se>.
31
30
 */
47
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
48
47
                                   strtof(), abort() */
49
48
#include <stdbool.h>            /* bool, false, true */
50
 
#include <string.h>             /* strcmp(), strlen(), strerror(),
51
 
                                   asprintf(), strncpy(), strsignal()
52
 
                                */
 
49
#include <string.h>             /* memset(), strcmp(), strlen(),
 
50
                                   strerror(), asprintf(), strcpy() */
53
51
#include <sys/ioctl.h>          /* ioctl */
54
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
55
53
                                   sockaddr_in6, PF_INET6,
59
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
60
58
                                   inet_pton(), connect(),
61
59
                                   getnameinfo() */
62
 
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
 
60
#include <fcntl.h>              /* open(), unlinkat() */
63
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
64
62
                                 */
65
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
66
64
                                   strtoimax() */
67
 
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
68
 
                                   EAI_SYSTEM, ENETUNREACH,
69
 
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
70
 
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
71
 
                                   ENOTEMPTY,
 
65
#include <errno.h>              /* perror(), errno,
72
66
                                   program_invocation_short_name */
73
67
#include <time.h>               /* nanosleep(), time(), sleep() */
74
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
310
304
                   gpgme_strsource(rc), gpgme_strerror(rc));
311
305
      return false;
312
306
    }
313
 
    {
314
 
      gpgme_import_result_t import_result
315
 
        = gpgme_op_import_result(mc->ctx);
316
 
      if((import_result->imported < 1
317
 
          or import_result->not_imported > 0)
318
 
         and import_result->unchanged == 0){
319
 
        fprintf_plus(stderr, "bad gpgme_op_import_results:\n");
320
 
        fprintf_plus(stderr,
321
 
                     "The total number of considered keys: %d\n",
322
 
                     import_result->considered);
323
 
        fprintf_plus(stderr,
324
 
                     "The number of keys without user ID: %d\n",
325
 
                     import_result->no_user_id);
326
 
        fprintf_plus(stderr,
327
 
                     "The total number of imported keys: %d\n",
328
 
                     import_result->imported);
329
 
        fprintf_plus(stderr, "The number of imported RSA keys: %d\n",
330
 
                     import_result->imported_rsa);
331
 
        fprintf_plus(stderr, "The number of unchanged keys: %d\n",
332
 
                     import_result->unchanged);
333
 
        fprintf_plus(stderr, "The number of new user IDs: %d\n",
334
 
                     import_result->new_user_ids);
335
 
        fprintf_plus(stderr, "The number of new sub keys: %d\n",
336
 
                     import_result->new_sub_keys);
337
 
        fprintf_plus(stderr, "The number of new signatures: %d\n",
338
 
                     import_result->new_signatures);
339
 
        fprintf_plus(stderr, "The number of new revocations: %d\n",
340
 
                     import_result->new_revocations);
341
 
        fprintf_plus(stderr,
342
 
                     "The total number of secret keys read: %d\n",
343
 
                     import_result->secret_read);
344
 
        fprintf_plus(stderr,
345
 
                     "The number of imported secret keys: %d\n",
346
 
                     import_result->secret_imported);
347
 
        fprintf_plus(stderr,
348
 
                     "The number of unchanged secret keys: %d\n",
349
 
                     import_result->secret_unchanged);
350
 
        fprintf_plus(stderr, "The number of keys not imported: %d\n",
351
 
                     import_result->not_imported);
352
 
        for(gpgme_import_status_t import_status
353
 
              = import_result->imports;
354
 
            import_status != NULL;
355
 
            import_status = import_status->next){
356
 
          fprintf_plus(stderr, "Import status for key: %s\n",
357
 
                       import_status->fpr);
358
 
          if(import_status->result != GPG_ERR_NO_ERROR){
359
 
            fprintf_plus(stderr, "Import result: %s: %s\n",
360
 
                         gpgme_strsource(import_status->result),
361
 
                         gpgme_strerror(import_status->result));
362
 
          }
363
 
          fprintf_plus(stderr, "Key status:\n");
364
 
          fprintf_plus(stderr,
365
 
                       import_status->status & GPGME_IMPORT_NEW
366
 
                       ? "The key was new.\n"
367
 
                       : "The key was not new.\n");
368
 
          fprintf_plus(stderr,
369
 
                       import_status->status & GPGME_IMPORT_UID
370
 
                       ? "The key contained new user IDs.\n"
371
 
                       : "The key did not contain new user IDs.\n");
372
 
          fprintf_plus(stderr,
373
 
                       import_status->status & GPGME_IMPORT_SIG
374
 
                       ? "The key contained new signatures.\n"
375
 
                       : "The key did not contain new signatures.\n");
376
 
          fprintf_plus(stderr,
377
 
                       import_status->status & GPGME_IMPORT_SUBKEY
378
 
                       ? "The key contained new sub keys.\n"
379
 
                       : "The key did not contain new sub keys.\n");
380
 
          fprintf_plus(stderr,
381
 
                       import_status->status & GPGME_IMPORT_SECRET
382
 
                       ? "The key contained a secret key.\n"
383
 
                       : "The key did not contain a secret key.\n");
384
 
        }
385
 
        return false;
386
 
      }
387
 
    }
388
307
    
389
 
    ret = close(fd);
 
308
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
390
309
    if(ret == -1){
391
310
      perror_plus("close");
392
311
    }
431
350
  /* Create new GPGME "context" */
432
351
  rc = gpgme_new(&(mc->ctx));
433
352
  if(rc != GPG_ERR_NO_ERROR){
434
 
    fprintf_plus(stderr, "bad gpgme_new: %s: %s\n",
435
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
353
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
354
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
355
                 gpgme_strerror(rc));
436
356
    return false;
437
357
  }
438
358
  
474
394
  /* Create new empty GPGME data buffer for the plaintext */
475
395
  rc = gpgme_data_new(&dh_plain);
476
396
  if(rc != GPG_ERR_NO_ERROR){
477
 
    fprintf_plus(stderr, "bad gpgme_data_new: %s: %s\n",
 
397
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
398
                 "bad gpgme_data_new: %s: %s\n",
478
399
                 gpgme_strsource(rc), gpgme_strerror(rc));
479
400
    gpgme_data_release(dh_crypto);
480
401
    return -1;
493
414
      if(result == NULL){
494
415
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
495
416
      } else {
496
 
        if(result->unsupported_algorithm != NULL) {
497
 
          fprintf_plus(stderr, "Unsupported algorithm: %s\n",
498
 
                       result->unsupported_algorithm);
499
 
        }
500
 
        fprintf_plus(stderr, "Wrong key usage: %s\n",
501
 
                     result->wrong_key_usage ? "Yes" : "No");
 
417
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
418
                     result->unsupported_algorithm);
 
419
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
420
                     result->wrong_key_usage);
502
421
        if(result->file_name != NULL){
503
422
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
504
423
        }
505
 
 
506
 
        for(gpgme_recipient_t r = result->recipients; r != NULL;
507
 
            r = r->next){
 
424
        gpgme_recipient_t recipient;
 
425
        recipient = result->recipients;
 
426
        while(recipient != NULL){
508
427
          fprintf_plus(stderr, "Public key algorithm: %s\n",
509
 
                       gpgme_pubkey_algo_name(r->pubkey_algo));
510
 
          fprintf_plus(stderr, "Key ID: %s\n", r->keyid);
 
428
                       gpgme_pubkey_algo_name
 
429
                       (recipient->pubkey_algo));
 
430
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
511
431
          fprintf_plus(stderr, "Secret key available: %s\n",
512
 
                       r->status == GPG_ERR_NO_SECKEY ? "No" : "Yes");
 
432
                       recipient->status == GPG_ERR_NO_SECKEY
 
433
                       ? "No" : "Yes");
 
434
          recipient = recipient->next;
513
435
        }
514
436
      }
515
437
    }
571
493
  return plaintext_length;
572
494
}
573
495
 
574
 
__attribute__((warn_unused_result, const))
575
 
static const char *safe_string(const char *str){
576
 
  if(str == NULL)
577
 
    return "(unknown)";
578
 
  return str;
579
 
}
580
 
 
581
496
__attribute__((warn_unused_result))
582
497
static const char *safer_gnutls_strerror(int value){
583
498
  const char *ret = gnutls_strerror(value);
584
 
  return safe_string(ret);
 
499
  if(ret == NULL)
 
500
    ret = "(unknown)";
 
501
  return ret;
585
502
}
586
503
 
587
504
/* GnuTLS log function callback */
591
508
  fprintf_plus(stderr, "GnuTLS: %s", string);
592
509
}
593
510
 
594
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
 
511
__attribute__((nonnull, warn_unused_result))
595
512
static int init_gnutls_global(const char *pubkeyfilename,
596
513
                              const char *seckeyfilename,
597
 
                              const char *dhparamsfilename,
598
514
                              mandos_context *mc){
599
515
  int ret;
600
 
  unsigned int uret;
601
516
  
602
517
  if(debug){
603
518
    fprintf_plus(stderr, "Initializing GnuTLS\n");
604
519
  }
605
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
  
606
528
  if(debug){
607
529
    /* "Use a log level over 10 to enable all debugging options."
608
530
     * - GnuTLS manual
616
538
  if(ret != GNUTLS_E_SUCCESS){
617
539
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
618
540
                 safer_gnutls_strerror(ret));
 
541
    gnutls_global_deinit();
619
542
    return -1;
620
543
  }
621
544
  
646
569
                 safer_gnutls_strerror(ret));
647
570
    goto globalfail;
648
571
  }
649
 
  /* If a Diffie-Hellman parameters file was given, try to use it */
650
 
  if(dhparamsfilename != NULL){
651
 
    gnutls_datum_t params = { .data = NULL, .size = 0 };
652
 
    do {
653
 
      int dhpfile = open(dhparamsfilename, O_RDONLY);
654
 
      if(dhpfile == -1){
655
 
        perror_plus("open");
656
 
        dhparamsfilename = NULL;
657
 
        break;
658
 
      }
659
 
      size_t params_capacity = 0;
660
 
      while(true){
661
 
        params_capacity = incbuffer((char **)&params.data,
662
 
                                    (size_t)params.size,
663
 
                                    (size_t)params_capacity);
664
 
        if(params_capacity == 0){
665
 
          perror_plus("incbuffer");
666
 
          free(params.data);
667
 
          params.data = NULL;
668
 
          dhparamsfilename = NULL;
669
 
          break;
670
 
        }
671
 
        ssize_t bytes_read = read(dhpfile,
672
 
                                  params.data + params.size,
673
 
                                  BUFFER_SIZE);
674
 
        /* EOF */
675
 
        if(bytes_read == 0){
676
 
          break;
677
 
        }
678
 
        /* check bytes_read for failure */
679
 
        if(bytes_read < 0){
680
 
          perror_plus("read");
681
 
          free(params.data);
682
 
          params.data = NULL;
683
 
          dhparamsfilename = NULL;
684
 
          break;
685
 
        }
686
 
        params.size += (unsigned int)bytes_read;
687
 
      }
688
 
      ret = close(dhpfile);
689
 
      if(ret == -1){
690
 
        perror_plus("close");
691
 
      }
692
 
      if(params.data == NULL){
693
 
        dhparamsfilename = NULL;
694
 
      }
695
 
      if(dhparamsfilename == NULL){
696
 
        break;
697
 
      }
698
 
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
699
 
                                          GNUTLS_X509_FMT_PEM);
700
 
      if(ret != GNUTLS_E_SUCCESS){
701
 
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
702
 
                     " \"%s\": %s\n", dhparamsfilename,
703
 
                     safer_gnutls_strerror(ret));
704
 
        dhparamsfilename = NULL;
705
 
      }
706
 
      free(params.data);
707
 
    } while(false);
708
 
  }
709
 
  if(dhparamsfilename == NULL){
710
 
    if(mc->dh_bits == 0){
711
 
      /* Find out the optimal number of DH bits */
712
 
      /* Try to read the private key file */
713
 
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
714
 
      do {
715
 
        int secfile = open(seckeyfilename, O_RDONLY);
716
 
        if(secfile == -1){
717
 
          perror_plus("open");
718
 
          break;
719
 
        }
720
 
        size_t buffer_capacity = 0;
721
 
        while(true){
722
 
          buffer_capacity = incbuffer((char **)&buffer.data,
723
 
                                      (size_t)buffer.size,
724
 
                                      (size_t)buffer_capacity);
725
 
          if(buffer_capacity == 0){
726
 
            perror_plus("incbuffer");
727
 
            free(buffer.data);
728
 
            buffer.data = NULL;
729
 
            break;
730
 
          }
731
 
          ssize_t bytes_read = read(secfile,
732
 
                                    buffer.data + buffer.size,
733
 
                                    BUFFER_SIZE);
734
 
          /* EOF */
735
 
          if(bytes_read == 0){
736
 
            break;
737
 
          }
738
 
          /* check bytes_read for failure */
739
 
          if(bytes_read < 0){
740
 
            perror_plus("read");
741
 
            free(buffer.data);
742
 
            buffer.data = NULL;
743
 
            break;
744
 
          }
745
 
          buffer.size += (unsigned int)bytes_read;
746
 
        }
747
 
        close(secfile);
748
 
      } while(false);
749
 
      /* If successful, use buffer to parse private key */
750
 
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
751
 
      if(buffer.data != NULL){
752
 
        {
753
 
          gnutls_openpgp_privkey_t privkey = NULL;
754
 
          ret = gnutls_openpgp_privkey_init(&privkey);
755
 
          if(ret != GNUTLS_E_SUCCESS){
756
 
            fprintf_plus(stderr, "Error initializing OpenPGP key"
757
 
                         " structure: %s",
758
 
                         safer_gnutls_strerror(ret));
759
 
            free(buffer.data);
760
 
            buffer.data = NULL;
761
 
          } else {
762
 
            ret = gnutls_openpgp_privkey_import
763
 
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
764
 
            if(ret != GNUTLS_E_SUCCESS){
765
 
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
766
 
                           safer_gnutls_strerror(ret));
767
 
              privkey = NULL;
768
 
            }
769
 
            free(buffer.data);
770
 
            buffer.data = NULL;
771
 
            if(privkey != NULL){
772
 
              /* Use private key to suggest an appropriate
773
 
                 sec_param */
774
 
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
775
 
              gnutls_openpgp_privkey_deinit(privkey);
776
 
              if(debug){
777
 
                fprintf_plus(stderr, "This OpenPGP key implies using"
778
 
                             " a GnuTLS security parameter \"%s\".\n",
779
 
                             safe_string(gnutls_sec_param_get_name
780
 
                                         (sec_param)));
781
 
              }
782
 
            }
783
 
          }
784
 
        }
785
 
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
786
 
          /* Err on the side of caution */
787
 
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
788
 
          if(debug){
789
 
            fprintf_plus(stderr, "Falling back to security parameter"
790
 
                         " \"%s\"\n",
791
 
                         safe_string(gnutls_sec_param_get_name
792
 
                                     (sec_param)));
793
 
          }
794
 
        }
795
 
      }
796
 
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
797
 
      if(uret != 0){
798
 
        mc->dh_bits = uret;
799
 
        if(debug){
800
 
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
801
 
                       " implies %u DH bits; using that.\n",
802
 
                       safe_string(gnutls_sec_param_get_name
803
 
                                   (sec_param)),
804
 
                       mc->dh_bits);
805
 
        }
806
 
      } else {
807
 
        fprintf_plus(stderr, "Failed to get implied number of DH"
808
 
                     " bits for security parameter \"%s\"): %s\n",
809
 
                     safe_string(gnutls_sec_param_get_name
810
 
                                 (sec_param)),
811
 
                     safer_gnutls_strerror(ret));
812
 
        goto globalfail;
813
 
      }
814
 
    } else if(debug){
815
 
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
816
 
                   mc->dh_bits);
817
 
    }
818
 
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
819
 
    if(ret != GNUTLS_E_SUCCESS){
820
 
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
821
 
                   " bits): %s\n", mc->dh_bits,
822
 
                   safer_gnutls_strerror(ret));
823
 
      goto globalfail;
824
 
    }
825
 
  }
 
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
  
826
579
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
827
580
  
828
581
  return 0;
830
583
 globalfail:
831
584
  
832
585
  gnutls_certificate_free_credentials(mc->cred);
 
586
  gnutls_global_deinit();
833
587
  gnutls_dh_params_deinit(mc->dh_params);
834
588
  return -1;
835
589
}
887
641
  /* ignore client certificate if any. */
888
642
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
889
643
  
 
644
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
645
  
890
646
  return 0;
891
647
}
892
648
 
894
650
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
895
651
                      __attribute__((unused)) const char *txt){}
896
652
 
897
 
/* Set effective uid to 0, return errno */
898
 
__attribute__((warn_unused_result))
899
 
int raise_privileges(void){
900
 
  int old_errno = errno;
901
 
  int ret = 0;
902
 
  if(seteuid(0) == -1){
903
 
    ret = errno;
904
 
  }
905
 
  errno = old_errno;
906
 
  return ret;
907
 
}
908
 
 
909
 
/* Set effective and real user ID to 0.  Return errno. */
910
 
__attribute__((warn_unused_result))
911
 
int raise_privileges_permanently(void){
912
 
  int old_errno = errno;
913
 
  int ret = raise_privileges();
914
 
  if(ret != 0){
915
 
    errno = old_errno;
916
 
    return ret;
917
 
  }
918
 
  if(setuid(0) == -1){
919
 
    ret = errno;
920
 
  }
921
 
  errno = old_errno;
922
 
  return ret;
923
 
}
924
 
 
925
 
/* Set effective user ID to unprivileged saved user ID */
926
 
__attribute__((warn_unused_result))
927
 
int lower_privileges(void){
928
 
  int old_errno = errno;
929
 
  int ret = 0;
930
 
  if(seteuid(uid) == -1){
931
 
    ret = errno;
932
 
  }
933
 
  errno = old_errno;
934
 
  return ret;
935
 
}
936
 
 
937
 
/* Lower privileges permanently */
938
 
__attribute__((warn_unused_result))
939
 
int lower_privileges_permanently(void){
940
 
  int old_errno = errno;
941
 
  int ret = 0;
942
 
  if(setuid(uid) == -1){
943
 
    ret = errno;
944
 
  }
945
 
  errno = old_errno;
946
 
  return ret;
947
 
}
948
 
 
949
 
/* Helper function to add_local_route() and delete_local_route() */
950
 
__attribute__((nonnull, warn_unused_result))
951
 
static bool add_delete_local_route(const bool add,
952
 
                                   const char *address,
953
 
                                   AvahiIfIndex if_index){
954
 
  int ret;
955
 
  char helper[] = "mandos-client-iprouteadddel";
956
 
  char add_arg[] = "add";
957
 
  char delete_arg[] = "delete";
958
 
  char debug_flag[] = "--debug";
959
 
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
960
 
  if(pluginhelperdir == NULL){
961
 
    if(debug){
962
 
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
963
 
                   " variable not set; cannot run helper\n");
964
 
    }
965
 
    return false;
966
 
  }
967
 
  
968
 
  char interface[IF_NAMESIZE];
969
 
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
970
 
    perror_plus("if_indextoname");
971
 
    return false;
972
 
  }
973
 
  
974
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
975
 
  if(devnull == -1){
976
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
977
 
    return false;
978
 
  }
979
 
  pid_t pid = fork();
980
 
  if(pid == 0){
981
 
    /* Child */
982
 
    /* Raise privileges */
983
 
    errno = raise_privileges_permanently();
984
 
    if(errno != 0){
985
 
      perror_plus("Failed to raise privileges");
986
 
      /* _exit(EX_NOPERM); */
987
 
    } else {
988
 
      /* Set group */
989
 
      errno = 0;
990
 
      ret = setgid(0);
991
 
      if(ret == -1){
992
 
        perror_plus("setgid");
993
 
        _exit(EX_NOPERM);
994
 
      }
995
 
      /* Reset supplementary groups */
996
 
      errno = 0;
997
 
      ret = setgroups(0, NULL);
998
 
      if(ret == -1){
999
 
        perror_plus("setgroups");
1000
 
        _exit(EX_NOPERM);
1001
 
      }
1002
 
    }
1003
 
    ret = dup2(devnull, STDIN_FILENO);
1004
 
    if(ret == -1){
1005
 
      perror_plus("dup2(devnull, STDIN_FILENO)");
1006
 
      _exit(EX_OSERR);
1007
 
    }
1008
 
    ret = close(devnull);
1009
 
    if(ret == -1){
1010
 
      perror_plus("close");
1011
 
      _exit(EX_OSERR);
1012
 
    }
1013
 
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1014
 
    if(ret == -1){
1015
 
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1016
 
      _exit(EX_OSERR);
1017
 
    }
1018
 
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
1019
 
                                                    O_RDONLY
1020
 
                                                    | O_DIRECTORY
1021
 
                                                    | O_PATH
1022
 
                                                    | O_CLOEXEC));
1023
 
    if(helperdir_fd == -1){
1024
 
      perror_plus("open");
1025
 
      _exit(EX_UNAVAILABLE);
1026
 
    }
1027
 
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
1028
 
                                                   helper, O_RDONLY));
1029
 
    if(helper_fd == -1){
1030
 
      perror_plus("openat");
1031
 
      close(helperdir_fd);
1032
 
      _exit(EX_UNAVAILABLE);
1033
 
    }
1034
 
    close(helperdir_fd);
1035
 
#ifdef __GNUC__
1036
 
#pragma GCC diagnostic push
1037
 
#pragma GCC diagnostic ignored "-Wcast-qual"
1038
 
#endif
1039
 
    if(fexecve(helper_fd, (char *const [])
1040
 
               { helper, add ? add_arg : delete_arg, (char *)address,
1041
 
                   interface, debug ? debug_flag : NULL, NULL },
1042
 
               environ) == -1){
1043
 
#ifdef __GNUC__
1044
 
#pragma GCC diagnostic pop
1045
 
#endif
1046
 
      perror_plus("fexecve");
1047
 
      _exit(EXIT_FAILURE);
1048
 
    }
1049
 
  }
1050
 
  if(pid == -1){
1051
 
    perror_plus("fork");
1052
 
    return false;
1053
 
  }
1054
 
  int status;
1055
 
  pid_t pret = -1;
1056
 
  errno = 0;
1057
 
  do {
1058
 
    pret = waitpid(pid, &status, 0);
1059
 
    if(pret == -1 and errno == EINTR and quit_now){
1060
 
      int errno_raising = 0;
1061
 
      if((errno = raise_privileges()) != 0){
1062
 
        errno_raising = errno;
1063
 
        perror_plus("Failed to raise privileges in order to"
1064
 
                    " kill helper program");
1065
 
      }
1066
 
      if(kill(pid, SIGTERM) == -1){
1067
 
        perror_plus("kill");
1068
 
      }
1069
 
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
1070
 
        perror_plus("Failed to lower privileges after killing"
1071
 
                    " helper program");
1072
 
      }
1073
 
      return false;
1074
 
    }
1075
 
  } while(pret == -1 and errno == EINTR);
1076
 
  if(pret == -1){
1077
 
    perror_plus("waitpid");
1078
 
    return false;
1079
 
  }
1080
 
  if(WIFEXITED(status)){
1081
 
    if(WEXITSTATUS(status) != 0){
1082
 
      fprintf_plus(stderr, "Error: iprouteadddel exited"
1083
 
                   " with status %d\n", WEXITSTATUS(status));
1084
 
      return false;
1085
 
    }
1086
 
    return true;
1087
 
  }
1088
 
  if(WIFSIGNALED(status)){
1089
 
    fprintf_plus(stderr, "Error: iprouteadddel died by"
1090
 
                 " signal %d\n", WTERMSIG(status));
1091
 
    return false;
1092
 
  }
1093
 
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
1094
 
  return false;
1095
 
}
1096
 
 
1097
 
__attribute__((nonnull, warn_unused_result))
1098
 
static bool add_local_route(const char *address,
1099
 
                            AvahiIfIndex if_index){
1100
 
  if(debug){
1101
 
    fprintf_plus(stderr, "Adding route to %s\n", address);
1102
 
  }
1103
 
  return add_delete_local_route(true, address, if_index);
1104
 
}
1105
 
 
1106
 
__attribute__((nonnull, warn_unused_result))
1107
 
static bool delete_local_route(const char *address,
1108
 
                               AvahiIfIndex if_index){
1109
 
  if(debug){
1110
 
    fprintf_plus(stderr, "Removing route to %s\n", address);
1111
 
  }
1112
 
  return add_delete_local_route(false, address, if_index);
1113
 
}
1114
 
 
1115
653
/* Called when a Mandos server is found */
1116
654
__attribute__((nonnull, warn_unused_result))
1117
655
static int start_mandos_communication(const char *ip, in_port_t port,
1128
666
  int retval = -1;
1129
667
  gnutls_session_t session;
1130
668
  int pf;                       /* Protocol family */
1131
 
  bool route_added = false;
1132
669
  
1133
670
  errno = 0;
1134
671
  
1156
693
    bool match = false;
1157
694
    {
1158
695
      char *interface = NULL;
1159
 
      while((interface = argz_next(mc->interfaces,
1160
 
                                   mc->interfaces_size,
1161
 
                                   interface))){
 
696
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
697
                                 interface))){
1162
698
        if(if_nametoindex(interface) == (unsigned int)if_index){
1163
699
          match = true;
1164
700
          break;
1193
729
                 PRIuMAX "\n", ip, (uintmax_t)port);
1194
730
  }
1195
731
  
1196
 
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
 
732
  tcp_sd = socket(pf, SOCK_STREAM, 0);
1197
733
  if(tcp_sd < 0){
1198
734
    int e = errno;
1199
735
    perror_plus("socket");
1206
742
    goto mandos_end;
1207
743
  }
1208
744
  
 
745
  memset(&to, 0, sizeof(to));
1209
746
  if(af == AF_INET6){
1210
 
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
1211
 
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
1212
 
    ret = inet_pton(af, ip, &to6->sin6_addr);
 
747
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
748
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
1213
749
  } else {                      /* IPv4 */
1214
 
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
1215
 
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
1216
 
    ret = inet_pton(af, ip, &to4->sin_addr);
 
750
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
751
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
1217
752
  }
1218
753
  if(ret < 0 ){
1219
754
    int e = errno;
1289
824
    goto mandos_end;
1290
825
  }
1291
826
  
1292
 
  while(true){
1293
 
    if(af == AF_INET6){
1294
 
      ret = connect(tcp_sd, (struct sockaddr *)&to,
1295
 
                    sizeof(struct sockaddr_in6));
1296
 
    } else {
1297
 
      ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
1298
 
                    sizeof(struct sockaddr_in));
1299
 
    }
1300
 
    if(ret < 0){
1301
 
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
1302
 
         and if_index != AVAHI_IF_UNSPEC
1303
 
         and connect_to == NULL
1304
 
         and not route_added and
1305
 
         ((af == AF_INET6 and not
1306
 
           IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
1307
 
                                    &to)->sin6_addr)))
1308
 
          or (af == AF_INET and
1309
 
              /* Not a a IPv4LL address */
1310
 
              (ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
1311
 
               & 0xFFFF0000L) != 0xA9FE0000L))){
1312
 
        /* Work around Avahi bug - Avahi does not announce link-local
1313
 
           addresses if it has a global address, so local hosts with
1314
 
           *only* a link-local address (e.g. Mandos clients) cannot
1315
 
           connect to a Mandos server announced by Avahi on a server
1316
 
           host with a global address.  Work around this by retrying
1317
 
           with an explicit route added with the server's address.
1318
 
           
1319
 
           Avahi bug reference:
1320
 
           https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1321
 
           https://bugs.debian.org/587961
1322
 
        */
1323
 
        if(debug){
1324
 
          fprintf_plus(stderr, "Mandos server unreachable, trying"
1325
 
                       " direct route\n");
1326
 
        }
1327
 
        int e = errno;
1328
 
        route_added = add_local_route(ip, if_index);
1329
 
        if(route_added){
1330
 
          continue;
1331
 
        }
1332
 
        errno = e;
1333
 
      }
1334
 
      if(errno != ECONNREFUSED or debug){
1335
 
        int e = errno;
1336
 
        perror_plus("connect");
1337
 
        errno = e;
1338
 
      }
1339
 
      goto mandos_end;
1340
 
    }
1341
 
    
1342
 
    if(quit_now){
1343
 
      errno = EINTR;
1344
 
      goto mandos_end;
1345
 
    }
1346
 
    break;
 
827
  if(af == AF_INET6){
 
828
    ret = connect(tcp_sd, (struct sockaddr *)&to,
 
829
                  sizeof(struct sockaddr_in6));
 
830
  } else {
 
831
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
832
                  sizeof(struct sockaddr_in));
 
833
  }
 
834
  if(ret < 0){
 
835
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
836
      int e = errno;
 
837
      perror_plus("connect");
 
838
      errno = e;
 
839
    }
 
840
    goto mandos_end;
 
841
  }
 
842
  
 
843
  if(quit_now){
 
844
    errno = EINTR;
 
845
    goto mandos_end;
1347
846
  }
1348
847
  
1349
848
  const char *out = mandos_protocol_version;
1503
1002
                                               &decrypted_buffer, mc);
1504
1003
    if(decrypted_buffer_size >= 0){
1505
1004
      
1506
 
      clearerr(stdout);
1507
1005
      written = 0;
1508
1006
      while(written < (size_t) decrypted_buffer_size){
1509
1007
        if(quit_now){
1525
1023
        }
1526
1024
        written += (size_t)ret;
1527
1025
      }
1528
 
      ret = fflush(stdout);
1529
 
      if(ret != 0){
1530
 
        int e = errno;
1531
 
        if(debug){
1532
 
          fprintf_plus(stderr, "Error writing encrypted data: %s\n",
1533
 
                       strerror(errno));
1534
 
        }
1535
 
        errno = e;
1536
 
        goto mandos_end;
1537
 
      }
1538
1026
      retval = 0;
1539
1027
    }
1540
1028
  }
1543
1031
  
1544
1032
 mandos_end:
1545
1033
  {
1546
 
    if(route_added){
1547
 
      if(not delete_local_route(ip, if_index)){
1548
 
        fprintf_plus(stderr, "Failed to delete local route to %s on"
1549
 
                     " interface %d", ip, if_index);
1550
 
      }
1551
 
    }
1552
1034
    int e = errno;
1553
1035
    free(decrypted_buffer);
1554
1036
    free(buffer);
1555
1037
    if(tcp_sd >= 0){
1556
 
      ret = close(tcp_sd);
 
1038
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1557
1039
    }
1558
1040
    if(ret == -1){
1559
1041
      if(e == 0){
1571
1053
  return retval;
1572
1054
}
1573
1055
 
 
1056
__attribute__((nonnull))
1574
1057
static void resolve_callback(AvahiSServiceResolver *r,
1575
1058
                             AvahiIfIndex interface,
1576
1059
                             AvahiProtocol proto,
1593
1076
     timed out */
1594
1077
  
1595
1078
  if(quit_now){
1596
 
    avahi_s_service_resolver_free(r);
1597
1079
    return;
1598
1080
  }
1599
1081
  
1713
1195
__attribute__((nonnull, warn_unused_result))
1714
1196
bool get_flags(const char *ifname, struct ifreq *ifr){
1715
1197
  int ret;
1716
 
  int old_errno;
 
1198
  error_t ret_errno;
1717
1199
  
1718
1200
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1719
1201
  if(s < 0){
1720
 
    old_errno = errno;
 
1202
    ret_errno = errno;
1721
1203
    perror_plus("socket");
1722
 
    errno = old_errno;
 
1204
    errno = ret_errno;
1723
1205
    return false;
1724
1206
  }
1725
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1726
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
 
1207
  strcpy(ifr->ifr_name, ifname);
1727
1208
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1728
1209
  if(ret == -1){
1729
1210
    if(debug){
1730
 
      old_errno = errno;
 
1211
      ret_errno = errno;
1731
1212
      perror_plus("ioctl SIOCGIFFLAGS");
1732
 
      errno = old_errno;
1733
 
    }
1734
 
    if((close(s) == -1) and debug){
1735
 
      old_errno = errno;
1736
 
      perror_plus("close");
1737
 
      errno = old_errno;
 
1213
      errno = ret_errno;
1738
1214
    }
1739
1215
    return false;
1740
1216
  }
1741
 
  if((close(s) == -1) and debug){
1742
 
    old_errno = errno;
1743
 
    perror_plus("close");
1744
 
    errno = old_errno;
1745
 
  }
1746
1217
  return true;
1747
1218
}
1748
1219
 
1990
1461
  }
1991
1462
}
1992
1463
 
 
1464
/* Set effective uid to 0, return errno */
 
1465
__attribute__((warn_unused_result))
 
1466
error_t raise_privileges(void){
 
1467
  error_t old_errno = errno;
 
1468
  error_t ret_errno = 0;
 
1469
  if(seteuid(0) == -1){
 
1470
    ret_errno = errno;
 
1471
  }
 
1472
  errno = old_errno;
 
1473
  return ret_errno;
 
1474
}
 
1475
 
 
1476
/* Set effective and real user ID to 0.  Return errno. */
 
1477
__attribute__((warn_unused_result))
 
1478
error_t raise_privileges_permanently(void){
 
1479
  error_t old_errno = errno;
 
1480
  error_t ret_errno = raise_privileges();
 
1481
  if(ret_errno != 0){
 
1482
    errno = old_errno;
 
1483
    return ret_errno;
 
1484
  }
 
1485
  if(setuid(0) == -1){
 
1486
    ret_errno = errno;
 
1487
  }
 
1488
  errno = old_errno;
 
1489
  return ret_errno;
 
1490
}
 
1491
 
 
1492
/* Set effective user ID to unprivileged saved user ID */
 
1493
__attribute__((warn_unused_result))
 
1494
error_t lower_privileges(void){
 
1495
  error_t old_errno = errno;
 
1496
  error_t ret_errno = 0;
 
1497
  if(seteuid(uid) == -1){
 
1498
    ret_errno = errno;
 
1499
  }
 
1500
  errno = old_errno;
 
1501
  return ret_errno;
 
1502
}
 
1503
 
 
1504
/* Lower privileges permanently */
 
1505
__attribute__((warn_unused_result))
 
1506
error_t lower_privileges_permanently(void){
 
1507
  error_t old_errno = errno;
 
1508
  error_t ret_errno = 0;
 
1509
  if(setuid(uid) == -1){
 
1510
    ret_errno = errno;
 
1511
  }
 
1512
  errno = old_errno;
 
1513
  return ret_errno;
 
1514
}
 
1515
 
1993
1516
__attribute__((nonnull))
1994
1517
void run_network_hooks(const char *mode, const char *interface,
1995
1518
                       const float delay){
1996
1519
  struct dirent **direntries = NULL;
1997
1520
  if(hookdir_fd == -1){
1998
 
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
1999
 
                      | O_CLOEXEC);
 
1521
    hookdir_fd = open(hookdir, O_RDONLY);
2000
1522
    if(hookdir_fd == -1){
2001
1523
      if(errno == ENOENT){
2002
1524
        if(debug){
2009
1531
      return;
2010
1532
    }
2011
1533
  }
2012
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
2013
 
  if(devnull == -1){
2014
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
2015
 
    return;
2016
 
  }
 
1534
#ifdef __GLIBC__
 
1535
#if __GLIBC_PREREQ(2, 15)
2017
1536
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
2018
1537
                           runnable_hook, alphasort);
 
1538
#else  /* not __GLIBC_PREREQ(2, 15) */
 
1539
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1540
                         alphasort);
 
1541
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
1542
#else   /* not __GLIBC__ */
 
1543
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1544
                         alphasort);
 
1545
#endif  /* not __GLIBC__ */
2019
1546
  if(numhooks == -1){
2020
1547
    perror_plus("scandir");
2021
 
    close(devnull);
2022
1548
    return;
2023
1549
  }
2024
1550
  struct dirent *direntry;
2025
1551
  int ret;
 
1552
  int devnull = open("/dev/null", O_RDONLY);
2026
1553
  for(int i = 0; i < numhooks; i++){
2027
1554
    direntry = direntries[i];
2028
1555
    if(debug){
2052
1579
        perror_plus("setgroups");
2053
1580
        _exit(EX_NOPERM);
2054
1581
      }
 
1582
      ret = dup2(devnull, STDIN_FILENO);
 
1583
      if(ret == -1){
 
1584
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
1585
        _exit(EX_OSERR);
 
1586
      }
 
1587
      ret = close(devnull);
 
1588
      if(ret == -1){
 
1589
        perror_plus("close");
 
1590
        _exit(EX_OSERR);
 
1591
      }
 
1592
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
1593
      if(ret == -1){
 
1594
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
1595
        _exit(EX_OSERR);
 
1596
      }
2055
1597
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
2056
1598
      if(ret == -1){
2057
1599
        perror_plus("setenv");
2092
1634
          _exit(EX_OSERR);
2093
1635
        }
2094
1636
      }
2095
 
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
2096
 
                                                   direntry->d_name,
2097
 
                                                   O_RDONLY));
 
1637
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
2098
1638
      if(hook_fd == -1){
2099
1639
        perror_plus("openat");
2100
1640
        _exit(EXIT_FAILURE);
2101
1641
      }
2102
 
      if(close(hookdir_fd) == -1){
 
1642
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2103
1643
        perror_plus("close");
2104
1644
        _exit(EXIT_FAILURE);
2105
1645
      }
2106
 
      ret = dup2(devnull, STDIN_FILENO);
2107
 
      if(ret == -1){
2108
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
2109
 
        _exit(EX_OSERR);
2110
 
      }
2111
 
      ret = close(devnull);
2112
 
      if(ret == -1){
2113
 
        perror_plus("close");
2114
 
        _exit(EX_OSERR);
2115
 
      }
2116
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
2117
 
      if(ret == -1){
2118
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
2119
 
        _exit(EX_OSERR);
2120
 
      }
2121
1646
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
2122
1647
                 environ) == -1){
2123
1648
        perror_plus("fexecve");
2124
1649
        _exit(EXIT_FAILURE);
2125
1650
      }
2126
1651
    } else {
2127
 
      if(hook_pid == -1){
2128
 
        perror_plus("fork");
2129
 
        free(direntry);
2130
 
        continue;
2131
 
      }
2132
1652
      int status;
2133
1653
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
2134
1654
        perror_plus("waitpid");
2135
 
        free(direntry);
2136
1655
        continue;
2137
1656
      }
2138
1657
      if(WIFEXITED(status)){
2140
1659
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
2141
1660
                       " with status %d\n", direntry->d_name,
2142
1661
                       WEXITSTATUS(status));
2143
 
          free(direntry);
2144
1662
          continue;
2145
1663
        }
2146
1664
      } else if(WIFSIGNALED(status)){
2147
1665
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
2148
1666
                     " signal %d\n", direntry->d_name,
2149
1667
                     WTERMSIG(status));
2150
 
        free(direntry);
2151
1668
        continue;
2152
1669
      } else {
2153
1670
        fprintf_plus(stderr, "Warning: network hook \"%s\""
2154
1671
                     " crashed\n", direntry->d_name);
2155
 
        free(direntry);
2156
1672
        continue;
2157
1673
      }
2158
1674
    }
2160
1676
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
2161
1677
                   direntry->d_name);
2162
1678
    }
2163
 
    free(direntry);
2164
1679
  }
2165
1680
  free(direntries);
2166
 
  if(close(hookdir_fd) == -1){
 
1681
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2167
1682
    perror_plus("close");
2168
1683
  } else {
2169
1684
    hookdir_fd = -1;
2172
1687
}
2173
1688
 
2174
1689
__attribute__((nonnull, warn_unused_result))
2175
 
int bring_up_interface(const char *const interface,
2176
 
                       const float delay){
2177
 
  int old_errno = errno;
 
1690
error_t bring_up_interface(const char *const interface,
 
1691
                           const float delay){
 
1692
  error_t old_errno = errno;
2178
1693
  int ret;
2179
1694
  struct ifreq network;
2180
1695
  unsigned int if_index = if_nametoindex(interface);
2190
1705
  }
2191
1706
  
2192
1707
  if(not interface_is_up(interface)){
2193
 
    int ret_errno = 0;
2194
 
    int ioctl_errno = 0;
 
1708
    error_t ret_errno = 0, ioctl_errno = 0;
2195
1709
    if(not get_flags(interface, &network)){
2196
1710
      ret_errno = errno;
2197
1711
      fprintf_plus(stderr, "Failed to get flags for interface "
2210
1724
    }
2211
1725
    
2212
1726
    if(quit_now){
2213
 
      ret = close(sd);
 
1727
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2214
1728
      if(ret == -1){
2215
1729
        perror_plus("close");
2216
1730
      }
2266
1780
    }
2267
1781
    
2268
1782
    /* Close the socket */
2269
 
    ret = close(sd);
 
1783
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
2270
1784
    if(ret == -1){
2271
1785
      perror_plus("close");
2272
1786
    }
2284
1798
  
2285
1799
  /* Sleep checking until interface is running.
2286
1800
     Check every 0.25s, up to total time of delay */
2287
 
  for(int i = 0; i < delay * 4; i++){
 
1801
  for(int i=0; i < delay * 4; i++){
2288
1802
    if(interface_is_running(interface)){
2289
1803
      break;
2290
1804
    }
2300
1814
}
2301
1815
 
2302
1816
__attribute__((nonnull, warn_unused_result))
2303
 
int take_down_interface(const char *const interface){
2304
 
  int old_errno = errno;
 
1817
error_t take_down_interface(const char *const interface){
 
1818
  error_t old_errno = errno;
2305
1819
  struct ifreq network;
2306
1820
  unsigned int if_index = if_nametoindex(interface);
2307
1821
  if(if_index == 0){
2310
1824
    return ENXIO;
2311
1825
  }
2312
1826
  if(interface_is_up(interface)){
2313
 
    int ret_errno = 0;
2314
 
    int ioctl_errno = 0;
 
1827
    error_t ret_errno = 0, ioctl_errno = 0;
2315
1828
    if(not get_flags(interface, &network) and debug){
2316
1829
      ret_errno = errno;
2317
1830
      fprintf_plus(stderr, "Failed to get flags for interface "
2355
1868
    }
2356
1869
    
2357
1870
    /* Close the socket */
2358
 
    int ret = close(sd);
 
1871
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
2359
1872
    if(ret == -1){
2360
1873
      perror_plus("close");
2361
1874
    }
2376
1889
}
2377
1890
 
2378
1891
int main(int argc, char *argv[]){
2379
 
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2380
 
                        .priority = "SECURE256:!CTYPE-X.509"
2381
 
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
2382
 
                        .current_server = NULL, .interfaces = NULL,
2383
 
                        .interfaces_size = 0 };
 
1892
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1893
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1894
                        "+CTYPE-OPENPGP", .current_server = NULL,
 
1895
                        .interfaces = NULL, .interfaces_size = 0 };
2384
1896
  AvahiSServiceBrowser *sb = NULL;
2385
1897
  error_t ret_errno;
2386
1898
  int ret;
2395
1907
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2396
1908
  const char *seckey = PATHDIR "/" SECKEY;
2397
1909
  const char *pubkey = PATHDIR "/" PUBKEY;
2398
 
  const char *dh_params_file = NULL;
2399
1910
  char *interfaces_hooks = NULL;
2400
1911
  
2401
1912
  bool gnutls_initialized = false;
2454
1965
        .doc = "Bit length of the prime number used in the"
2455
1966
        " Diffie-Hellman key exchange",
2456
1967
        .group = 2 },
2457
 
      { .name = "dh-params", .key = 134,
2458
 
        .arg = "FILE",
2459
 
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
2460
 
        " for the Diffie-Hellman key exchange",
2461
 
        .group = 2 },
2462
1968
      { .name = "priority", .key = 130,
2463
1969
        .arg = "STRING",
2464
1970
        .doc = "GnuTLS priority string for the TLS handshake",
2519
2025
        }
2520
2026
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2521
2027
        break;
2522
 
      case 134:                 /* --dh-params */
2523
 
        dh_params_file = arg;
2524
 
        break;
2525
2028
      case 130:                 /* --priority */
2526
2029
        mc.priority = arg;
2527
2030
        break;
2567
2070
                         .args_doc = "",
2568
2071
                         .doc = "Mandos client -- Get and decrypt"
2569
2072
                         " passwords from a Mandos server" };
2570
 
    ret_errno = argp_parse(&argp, argc, argv,
2571
 
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2572
 
    switch(ret_errno){
 
2073
    ret = argp_parse(&argp, argc, argv,
 
2074
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2075
    switch(ret){
2573
2076
    case 0:
2574
2077
      break;
2575
2078
    case ENOMEM:
2576
2079
    default:
2577
 
      errno = ret_errno;
 
2080
      errno = ret;
2578
2081
      perror_plus("argp_parse");
2579
2082
      exitcode = EX_OSERR;
2580
2083
      goto end;
2583
2086
      goto end;
2584
2087
    }
2585
2088
  }
2586
 
  
 
2089
    
2587
2090
  {
2588
2091
    /* Work around Debian bug #633582:
2589
 
       <https://bugs.debian.org/633582> */
 
2092
       <http://bugs.debian.org/633582> */
2590
2093
    
2591
2094
    /* Re-raise privileges */
2592
 
    ret = raise_privileges();
2593
 
    if(ret != 0){
2594
 
      errno = ret;
 
2095
    ret_errno = raise_privileges();
 
2096
    if(ret_errno != 0){
 
2097
      errno = ret_errno;
2595
2098
      perror_plus("Failed to raise privileges");
2596
2099
    } else {
2597
2100
      struct stat st;
2613
2116
              }
2614
2117
            }
2615
2118
          }
2616
 
          close(seckey_fd);
 
2119
          TEMP_FAILURE_RETRY(close(seckey_fd));
2617
2120
        }
2618
2121
      }
2619
 
      
 
2122
    
2620
2123
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2621
2124
        int pubkey_fd = open(pubkey, O_RDONLY);
2622
2125
        if(pubkey_fd == -1){
2634
2137
              }
2635
2138
            }
2636
2139
          }
2637
 
          close(pubkey_fd);
2638
 
        }
2639
 
      }
2640
 
      
2641
 
      if(dh_params_file != NULL
2642
 
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
2643
 
        int dhparams_fd = open(dh_params_file, O_RDONLY);
2644
 
        if(dhparams_fd == -1){
2645
 
          perror_plus("open");
2646
 
        } else {
2647
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
2648
 
          if(ret == -1){
2649
 
            perror_plus("fstat");
2650
 
          } else {
2651
 
            if(S_ISREG(st.st_mode)
2652
 
               and st.st_uid == 0 and st.st_gid == 0){
2653
 
              ret = fchown(dhparams_fd, uid, gid);
2654
 
              if(ret == -1){
2655
 
                perror_plus("fchown");
2656
 
              }
2657
 
            }
2658
 
          }
2659
 
          close(dhparams_fd);
2660
 
        }
2661
 
      }
2662
 
      
 
2140
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2141
        }
 
2142
      }
 
2143
    
2663
2144
      /* Lower privileges */
2664
 
      ret = lower_privileges();
2665
 
      if(ret != 0){
2666
 
        errno = ret;
 
2145
      ret_errno = lower_privileges();
 
2146
      if(ret_errno != 0){
 
2147
        errno = ret_errno;
2667
2148
        perror_plus("Failed to lower privileges");
2668
2149
      }
2669
2150
    }
2794
2275
        if(ret_errno != 0){
2795
2276
          errno = ret_errno;
2796
2277
          perror_plus("argz_add");
2797
 
          free(direntries[i]);
2798
2278
          continue;
2799
2279
        }
2800
2280
        if(debug){
2801
2281
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2802
2282
                       direntries[i]->d_name);
2803
2283
        }
2804
 
        free(direntries[i]);
2805
2284
      }
2806
2285
      free(direntries);
2807
2286
    } else {
2839
2318
      errno = bring_up_interface(interface, delay);
2840
2319
      if(not interface_was_up){
2841
2320
        if(errno != 0){
2842
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2843
 
                       " %s\n", interface, strerror(errno));
 
2321
          perror_plus("Failed to bring up interface");
2844
2322
        } else {
2845
2323
          errno = argz_add(&interfaces_to_take_down,
2846
2324
                           &interfaces_to_take_down_size,
2869
2347
    goto end;
2870
2348
  }
2871
2349
  
2872
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
2350
  ret = init_gnutls_global(pubkey, seckey, &mc);
2873
2351
  if(ret == -1){
2874
2352
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2875
2353
    exitcode = EX_UNAVAILABLE;
2997
2475
    
2998
2476
    /* Allocate a new server */
2999
2477
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
3000
 
                                 &config, NULL, NULL, &ret);
 
2478
                                 &config, NULL, NULL, &ret_errno);
3001
2479
    
3002
2480
    /* Free the Avahi configuration data */
3003
2481
    avahi_server_config_free(&config);
3006
2484
  /* Check if creating the Avahi server object succeeded */
3007
2485
  if(mc.server == NULL){
3008
2486
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
3009
 
                 avahi_strerror(ret));
 
2487
                 avahi_strerror(ret_errno));
3010
2488
    exitcode = EX_UNAVAILABLE;
3011
2489
    goto end;
3012
2490
  }
3047
2525
 end:
3048
2526
  
3049
2527
  if(debug){
3050
 
    if(signal_received){
3051
 
      fprintf_plus(stderr, "%s exiting due to signal %d: %s\n",
3052
 
                   argv[0], signal_received,
3053
 
                   strsignal(signal_received));
3054
 
    } else {
3055
 
      fprintf_plus(stderr, "%s exiting\n", argv[0]);
3056
 
    }
 
2528
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
3057
2529
  }
3058
2530
  
3059
2531
  /* Cleanup things */
3070
2542
  
3071
2543
  if(gnutls_initialized){
3072
2544
    gnutls_certificate_free_credentials(mc.cred);
 
2545
    gnutls_global_deinit();
3073
2546
    gnutls_dh_params_deinit(mc.dh_params);
3074
2547
  }
3075
2548
  
3098
2571
  
3099
2572
  /* Re-raise privileges */
3100
2573
  {
3101
 
    ret = raise_privileges();
3102
 
    if(ret != 0){
3103
 
      errno = ret;
 
2574
    ret_errno = raise_privileges();
 
2575
    if(ret_errno != 0){
 
2576
      errno = ret_errno;
3104
2577
      perror_plus("Failed to raise privileges");
3105
2578
    } else {
3106
2579
      
3111
2584
      /* Take down the network interfaces which were brought up */
3112
2585
      {
3113
2586
        char *interface = NULL;
3114
 
        while((interface = argz_next(interfaces_to_take_down,
3115
 
                                     interfaces_to_take_down_size,
3116
 
                                     interface))){
3117
 
          ret = take_down_interface(interface);
3118
 
          if(ret != 0){
3119
 
            errno = ret;
 
2587
        while((interface=argz_next(interfaces_to_take_down,
 
2588
                                   interfaces_to_take_down_size,
 
2589
                                   interface))){
 
2590
          ret_errno = take_down_interface(interface);
 
2591
          if(ret_errno != 0){
 
2592
            errno = ret_errno;
3120
2593
            perror_plus("Failed to take down interface");
3121
2594
          }
3122
2595
        }
3127
2600
      }
3128
2601
    }
3129
2602
    
3130
 
    ret = lower_privileges_permanently();
3131
 
    if(ret != 0){
3132
 
      errno = ret;
 
2603
    ret_errno = lower_privileges_permanently();
 
2604
    if(ret_errno != 0){
 
2605
      errno = ret_errno;
3133
2606
      perror_plus("Failed to lower privileges permanently");
3134
2607
    }
3135
2608
  }
3137
2610
  free(interfaces_to_take_down);
3138
2611
  free(interfaces_hooks);
3139
2612
  
3140
 
  void clean_dir_at(int base, const char * const dirname,
3141
 
                    uintmax_t level){
3142
 
    struct dirent **direntries = NULL;
3143
 
    int dret;
3144
 
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
3145
 
                                                O_RDONLY
3146
 
                                                | O_NOFOLLOW
3147
 
                                                | O_DIRECTORY
3148
 
                                                | O_PATH));
3149
 
    if(dir_fd == -1){
3150
 
      perror_plus("open");
3151
 
      return;
3152
 
    }
3153
 
    int numentries = scandirat(dir_fd, ".", &direntries,
3154
 
                               notdotentries, alphasort);
3155
 
    if(numentries >= 0){
3156
 
      for(int i = 0; i < numentries; i++){
3157
 
        if(debug){
3158
 
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
3159
 
                       dirname, direntries[i]->d_name);
3160
 
        }
3161
 
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
3162
 
        if(dret == -1){
3163
 
          if(errno == EISDIR){
3164
 
              dret = unlinkat(dir_fd, direntries[i]->d_name,
3165
 
                              AT_REMOVEDIR);
3166
 
          }         
3167
 
          if((dret == -1) and (errno == ENOTEMPTY)
3168
 
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
3169
 
                  == 0) and (level == 0)){
3170
 
            /* Recurse only in this special case */
3171
 
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
3172
 
            dret = 0;
3173
 
          }
3174
 
          if((dret == -1) and (errno != ENOENT)){
3175
 
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
3176
 
                         direntries[i]->d_name, strerror(errno));
3177
 
          }
3178
 
        }
3179
 
        free(direntries[i]);
3180
 
      }
3181
 
      
3182
 
      /* need to clean even if 0 because man page doesn't specify */
3183
 
      free(direntries);
3184
 
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
3185
 
      if(dret == -1 and errno != ENOENT){
3186
 
        perror_plus("rmdir");
3187
 
      }
3188
 
    } else {
3189
 
      perror_plus("scandirat");
3190
 
    }
3191
 
    close(dir_fd);
3192
 
  }
3193
 
  
3194
2613
  /* Removes the GPGME temp directory and all files inside */
3195
2614
  if(tempdir != NULL){
3196
 
    clean_dir_at(-1, tempdir, 0);
 
2615
    struct dirent **direntries = NULL;
 
2616
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY |
 
2617
                                                  O_NOFOLLOW));
 
2618
    if(tempdir_fd == -1){
 
2619
      perror_plus("open");
 
2620
    } else {
 
2621
#ifdef __GLIBC__
 
2622
#if __GLIBC_PREREQ(2, 15)
 
2623
      int numentries = scandirat(tempdir_fd, ".", &direntries,
 
2624
                                 notdotentries, alphasort);
 
2625
#else  /* not __GLIBC_PREREQ(2, 15) */
 
2626
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2627
                               alphasort);
 
2628
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
2629
#else   /* not __GLIBC__ */
 
2630
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2631
                               alphasort);
 
2632
#endif  /* not __GLIBC__ */
 
2633
      if(numentries >= 0){
 
2634
        for(int i = 0; i < numentries; i++){
 
2635
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
 
2636
          if(ret == -1){
 
2637
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
 
2638
                         " \"%s\", 0): %s\n", tempdir,
 
2639
                         direntries[i]->d_name, strerror(errno));
 
2640
          }
 
2641
        }
 
2642
        
 
2643
        /* need to clean even if 0 because man page doesn't specify */
 
2644
        free(direntries);
 
2645
        if(numentries == -1){
 
2646
          perror_plus("scandir");
 
2647
        }
 
2648
        ret = rmdir(tempdir);
 
2649
        if(ret == -1 and errno != ENOENT){
 
2650
          perror_plus("rmdir");
 
2651
        }
 
2652
      }
 
2653
      TEMP_FAILURE_RETRY(close(tempdir_fd));
 
2654
    }
3197
2655
  }
3198
2656
  
3199
2657
  if(quit_now){