/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: 2018-08-15 09:18:22 UTC
  • Revision ID: teddy@recompile.se-20180815091822-tmmqryi0gqnzq6ab
mandos: Better error message if self-signature verification fails

* mandos (ClientHandler.fingerprint): If the verification of the
  self-signature fails, report the actual error message instead of a
  generic message.

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-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
 
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
21
23
 * WITHOUT ANY WARRANTY; without even the implied warranty of
22
24
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
23
25
 * General Public License for more details.
24
26
 * 
25
27
 * You should have received a copy of the GNU General Public License
26
 
 * along with this program.  If not, see
27
 
 * <http://www.gnu.org/licenses/>.
 
28
 * along with Mandos.  If not, see <http://www.gnu.org/licenses/>.
28
29
 * 
29
30
 * Contact the authors at <mandos@recompile.se>.
30
31
 */
46
47
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
48
                                   strtof(), abort() */
48
49
#include <stdbool.h>            /* bool, false, true */
49
 
#include <string.h>             /* memset(), strcmp(), strlen(),
50
 
                                   strerror(), asprintf(), strcpy() */
 
50
#include <string.h>             /* strcmp(), strlen(), strerror(),
 
51
                                   asprintf(), strncpy(), strsignal()
 
52
                                */
51
53
#include <sys/ioctl.h>          /* ioctl */
52
54
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
55
                                   sockaddr_in6, PF_INET6,
57
59
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
60
                                   inet_pton(), connect(),
59
61
                                   getnameinfo() */
60
 
#include <fcntl.h>              /* open(), unlinkat() */
 
62
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
61
63
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
64
                                 */
63
65
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
64
66
                                   strtoimax() */
65
 
#include <errno.h>              /* perror(), errno,
 
67
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
 
68
                                   EAI_SYSTEM, ENETUNREACH,
 
69
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
 
70
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
 
71
                                   ENOTEMPTY,
66
72
                                   program_invocation_short_name */
67
73
#include <time.h>               /* nanosleep(), time(), sleep() */
68
74
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
234
240
                          .af = af };
235
241
  if(new_server->ip == NULL){
236
242
    perror_plus("strdup");
 
243
    free(new_server);
237
244
    return false;
238
245
  }
239
246
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
240
247
  if(ret == -1){
241
248
    perror_plus("clock_gettime");
 
249
#ifdef __GNUC__
 
250
#pragma GCC diagnostic push
 
251
#pragma GCC diagnostic ignored "-Wcast-qual"
 
252
#endif
 
253
    free((char *)(new_server->ip));
 
254
#ifdef __GNUC__
 
255
#pragma GCC diagnostic pop
 
256
#endif
 
257
    free(new_server);
242
258
    return false;
243
259
  }
244
260
  /* Special case of first server */
294
310
                   gpgme_strsource(rc), gpgme_strerror(rc));
295
311
      return false;
296
312
    }
 
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
    }
297
388
    
298
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
 
389
    ret = close(fd);
299
390
    if(ret == -1){
300
391
      perror_plus("close");
301
392
    }
340
431
  /* Create new GPGME "context" */
341
432
  rc = gpgme_new(&(mc->ctx));
342
433
  if(rc != GPG_ERR_NO_ERROR){
343
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
344
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
345
 
                 gpgme_strerror(rc));
 
434
    fprintf_plus(stderr, "bad gpgme_new: %s: %s\n",
 
435
                 gpgme_strsource(rc), gpgme_strerror(rc));
346
436
    return false;
347
437
  }
348
438
  
384
474
  /* Create new empty GPGME data buffer for the plaintext */
385
475
  rc = gpgme_data_new(&dh_plain);
386
476
  if(rc != GPG_ERR_NO_ERROR){
387
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
388
 
                 "bad gpgme_data_new: %s: %s\n",
 
477
    fprintf_plus(stderr, "bad gpgme_data_new: %s: %s\n",
389
478
                 gpgme_strsource(rc), gpgme_strerror(rc));
390
479
    gpgme_data_release(dh_crypto);
391
480
    return -1;
404
493
      if(result == NULL){
405
494
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
406
495
      } else {
407
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
408
 
                     result->unsupported_algorithm);
409
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
410
 
                     result->wrong_key_usage);
 
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");
411
502
        if(result->file_name != NULL){
412
503
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
413
504
        }
414
 
        gpgme_recipient_t recipient;
415
 
        recipient = result->recipients;
416
 
        while(recipient != NULL){
 
505
 
 
506
        for(gpgme_recipient_t r = result->recipients; r != NULL;
 
507
            r = r->next){
417
508
          fprintf_plus(stderr, "Public key algorithm: %s\n",
418
 
                       gpgme_pubkey_algo_name
419
 
                       (recipient->pubkey_algo));
420
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
509
                       gpgme_pubkey_algo_name(r->pubkey_algo));
 
510
          fprintf_plus(stderr, "Key ID: %s\n", r->keyid);
421
511
          fprintf_plus(stderr, "Secret key available: %s\n",
422
 
                       recipient->status == GPG_ERR_NO_SECKEY
423
 
                       ? "No" : "Yes");
424
 
          recipient = recipient->next;
 
512
                       r->status == GPG_ERR_NO_SECKEY ? "No" : "Yes");
425
513
        }
426
514
      }
427
515
    }
483
571
  return plaintext_length;
484
572
}
485
573
 
 
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
 
486
581
__attribute__((warn_unused_result))
487
582
static const char *safer_gnutls_strerror(int value){
488
583
  const char *ret = gnutls_strerror(value);
489
 
  if(ret == NULL)
490
 
    ret = "(unknown)";
491
 
  return ret;
 
584
  return safe_string(ret);
492
585
}
493
586
 
494
587
/* GnuTLS log function callback */
498
591
  fprintf_plus(stderr, "GnuTLS: %s", string);
499
592
}
500
593
 
501
 
__attribute__((nonnull, warn_unused_result))
 
594
__attribute__((nonnull(1, 2, 4), warn_unused_result))
502
595
static int init_gnutls_global(const char *pubkeyfilename,
503
596
                              const char *seckeyfilename,
 
597
                              const char *dhparamsfilename,
504
598
                              mandos_context *mc){
505
599
  int ret;
 
600
  unsigned int uret;
506
601
  
507
602
  if(debug){
508
603
    fprintf_plus(stderr, "Initializing GnuTLS\n");
509
604
  }
510
605
  
511
 
  ret = gnutls_global_init();
512
 
  if(ret != GNUTLS_E_SUCCESS){
513
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
514
 
                 safer_gnutls_strerror(ret));
515
 
    return -1;
516
 
  }
517
 
  
518
606
  if(debug){
519
607
    /* "Use a log level over 10 to enable all debugging options."
520
608
     * - GnuTLS manual
528
616
  if(ret != GNUTLS_E_SUCCESS){
529
617
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
530
618
                 safer_gnutls_strerror(ret));
531
 
    gnutls_global_deinit();
532
619
    return -1;
533
620
  }
534
621
  
559
646
                 safer_gnutls_strerror(ret));
560
647
    goto globalfail;
561
648
  }
562
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
563
 
  if(ret != GNUTLS_E_SUCCESS){
564
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
565
 
                 safer_gnutls_strerror(ret));
566
 
    goto globalfail;
567
 
  }
568
 
  
 
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
  }
569
826
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
570
827
  
571
828
  return 0;
573
830
 globalfail:
574
831
  
575
832
  gnutls_certificate_free_credentials(mc->cred);
576
 
  gnutls_global_deinit();
577
833
  gnutls_dh_params_deinit(mc->dh_params);
578
834
  return -1;
579
835
}
631
887
  /* ignore client certificate if any. */
632
888
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
633
889
  
634
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
635
 
  
636
890
  return 0;
637
891
}
638
892
 
640
894
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
641
895
                      __attribute__((unused)) const char *txt){}
642
896
 
 
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
 
643
1115
/* Called when a Mandos server is found */
644
1116
__attribute__((nonnull, warn_unused_result))
645
1117
static int start_mandos_communication(const char *ip, in_port_t port,
656
1128
  int retval = -1;
657
1129
  gnutls_session_t session;
658
1130
  int pf;                       /* Protocol family */
 
1131
  bool route_added = false;
659
1132
  
660
1133
  errno = 0;
661
1134
  
683
1156
    bool match = false;
684
1157
    {
685
1158
      char *interface = NULL;
686
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
687
 
                                 interface))){
 
1159
      while((interface = argz_next(mc->interfaces,
 
1160
                                   mc->interfaces_size,
 
1161
                                   interface))){
688
1162
        if(if_nametoindex(interface) == (unsigned int)if_index){
689
1163
          match = true;
690
1164
          break;
719
1193
                 PRIuMAX "\n", ip, (uintmax_t)port);
720
1194
  }
721
1195
  
722
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
1196
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
723
1197
  if(tcp_sd < 0){
724
1198
    int e = errno;
725
1199
    perror_plus("socket");
732
1206
    goto mandos_end;
733
1207
  }
734
1208
  
735
 
  memset(&to, 0, sizeof(to));
736
1209
  if(af == AF_INET6){
737
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
738
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
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);
739
1213
  } else {                      /* IPv4 */
740
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
741
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
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);
742
1217
  }
743
1218
  if(ret < 0 ){
744
1219
    int e = errno;
814
1289
    goto mandos_end;
815
1290
  }
816
1291
  
817
 
  if(af == AF_INET6){
818
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
819
 
                  sizeof(struct sockaddr_in6));
820
 
  } else {
821
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
822
 
                  sizeof(struct sockaddr_in));
823
 
  }
824
 
  if(ret < 0){
825
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
826
 
      int e = errno;
827
 
      perror_plus("connect");
828
 
      errno = e;
829
 
    }
830
 
    goto mandos_end;
831
 
  }
832
 
  
833
 
  if(quit_now){
834
 
    errno = EINTR;
835
 
    goto mandos_end;
 
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;
836
1347
  }
837
1348
  
838
1349
  const char *out = mandos_protocol_version;
992
1503
                                               &decrypted_buffer, mc);
993
1504
    if(decrypted_buffer_size >= 0){
994
1505
      
 
1506
      clearerr(stdout);
995
1507
      written = 0;
996
1508
      while(written < (size_t) decrypted_buffer_size){
997
1509
        if(quit_now){
1013
1525
        }
1014
1526
        written += (size_t)ret;
1015
1527
      }
 
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
      }
1016
1538
      retval = 0;
1017
1539
    }
1018
1540
  }
1021
1543
  
1022
1544
 mandos_end:
1023
1545
  {
 
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
    }
1024
1552
    int e = errno;
1025
1553
    free(decrypted_buffer);
1026
1554
    free(buffer);
1027
1555
    if(tcp_sd >= 0){
1028
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
1556
      ret = close(tcp_sd);
1029
1557
    }
1030
1558
    if(ret == -1){
1031
1559
      if(e == 0){
1043
1571
  return retval;
1044
1572
}
1045
1573
 
1046
 
__attribute__((nonnull))
1047
1574
static void resolve_callback(AvahiSServiceResolver *r,
1048
1575
                             AvahiIfIndex interface,
1049
1576
                             AvahiProtocol proto,
1066
1593
     timed out */
1067
1594
  
1068
1595
  if(quit_now){
 
1596
    avahi_s_service_resolver_free(r);
1069
1597
    return;
1070
1598
  }
1071
1599
  
1185
1713
__attribute__((nonnull, warn_unused_result))
1186
1714
bool get_flags(const char *ifname, struct ifreq *ifr){
1187
1715
  int ret;
1188
 
  error_t ret_errno;
 
1716
  int old_errno;
1189
1717
  
1190
1718
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1191
1719
  if(s < 0){
1192
 
    ret_errno = errno;
 
1720
    old_errno = errno;
1193
1721
    perror_plus("socket");
1194
 
    errno = ret_errno;
 
1722
    errno = old_errno;
1195
1723
    return false;
1196
1724
  }
1197
 
  strcpy(ifr->ifr_name, ifname);
 
1725
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
 
1726
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1198
1727
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1199
1728
  if(ret == -1){
1200
1729
    if(debug){
1201
 
      ret_errno = errno;
 
1730
      old_errno = errno;
1202
1731
      perror_plus("ioctl SIOCGIFFLAGS");
1203
 
      errno = ret_errno;
 
1732
      errno = old_errno;
 
1733
    }
 
1734
    if((close(s) == -1) and debug){
 
1735
      old_errno = errno;
 
1736
      perror_plus("close");
 
1737
      errno = old_errno;
1204
1738
    }
1205
1739
    return false;
1206
1740
  }
 
1741
  if((close(s) == -1) and debug){
 
1742
    old_errno = errno;
 
1743
    perror_plus("close");
 
1744
    errno = old_errno;
 
1745
  }
1207
1746
  return true;
1208
1747
}
1209
1748
 
1451
1990
  }
1452
1991
}
1453
1992
 
1454
 
/* Set effective uid to 0, return errno */
1455
 
__attribute__((warn_unused_result))
1456
 
error_t raise_privileges(void){
1457
 
  error_t old_errno = errno;
1458
 
  error_t ret_errno = 0;
1459
 
  if(seteuid(0) == -1){
1460
 
    ret_errno = errno;
1461
 
  }
1462
 
  errno = old_errno;
1463
 
  return ret_errno;
1464
 
}
1465
 
 
1466
 
/* Set effective and real user ID to 0.  Return errno. */
1467
 
__attribute__((warn_unused_result))
1468
 
error_t raise_privileges_permanently(void){
1469
 
  error_t old_errno = errno;
1470
 
  error_t ret_errno = raise_privileges();
1471
 
  if(ret_errno != 0){
1472
 
    errno = old_errno;
1473
 
    return ret_errno;
1474
 
  }
1475
 
  if(setuid(0) == -1){
1476
 
    ret_errno = errno;
1477
 
  }
1478
 
  errno = old_errno;
1479
 
  return ret_errno;
1480
 
}
1481
 
 
1482
 
/* Set effective user ID to unprivileged saved user ID */
1483
 
__attribute__((warn_unused_result))
1484
 
error_t lower_privileges(void){
1485
 
  error_t old_errno = errno;
1486
 
  error_t ret_errno = 0;
1487
 
  if(seteuid(uid) == -1){
1488
 
    ret_errno = errno;
1489
 
  }
1490
 
  errno = old_errno;
1491
 
  return ret_errno;
1492
 
}
1493
 
 
1494
 
/* Lower privileges permanently */
1495
 
__attribute__((warn_unused_result))
1496
 
error_t lower_privileges_permanently(void){
1497
 
  error_t old_errno = errno;
1498
 
  error_t ret_errno = 0;
1499
 
  if(setuid(uid) == -1){
1500
 
    ret_errno = errno;
1501
 
  }
1502
 
  errno = old_errno;
1503
 
  return ret_errno;
1504
 
}
1505
 
 
1506
1993
__attribute__((nonnull))
1507
1994
void run_network_hooks(const char *mode, const char *interface,
1508
1995
                       const float delay){
1509
1996
  struct dirent **direntries = NULL;
1510
1997
  if(hookdir_fd == -1){
1511
 
    hookdir_fd = open(hookdir, O_RDONLY);
 
1998
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
 
1999
                      | O_CLOEXEC);
1512
2000
    if(hookdir_fd == -1){
1513
2001
      if(errno == ENOENT){
1514
2002
        if(debug){
1521
2009
      return;
1522
2010
    }
1523
2011
  }
1524
 
#ifdef __GLIBC__
1525
 
#if __GLIBC_PREREQ(2, 15)
 
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
  }
1526
2017
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1527
2018
                           runnable_hook, alphasort);
1528
 
#else  /* not __GLIBC_PREREQ(2, 15) */
1529
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1530
 
                         alphasort);
1531
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
1532
 
#else   /* not __GLIBC__ */
1533
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1534
 
                         alphasort);
1535
 
#endif  /* not __GLIBC__ */
1536
2019
  if(numhooks == -1){
1537
2020
    perror_plus("scandir");
 
2021
    close(devnull);
1538
2022
    return;
1539
2023
  }
1540
2024
  struct dirent *direntry;
1541
2025
  int ret;
1542
 
  int devnull = open("/dev/null", O_RDONLY);
1543
2026
  for(int i = 0; i < numhooks; i++){
1544
2027
    direntry = direntries[i];
1545
2028
    if(debug){
1569
2052
        perror_plus("setgroups");
1570
2053
        _exit(EX_NOPERM);
1571
2054
      }
1572
 
      ret = dup2(devnull, STDIN_FILENO);
1573
 
      if(ret == -1){
1574
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
1575
 
        _exit(EX_OSERR);
1576
 
      }
1577
 
      ret = close(devnull);
1578
 
      if(ret == -1){
1579
 
        perror_plus("close");
1580
 
        _exit(EX_OSERR);
1581
 
      }
1582
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1583
 
      if(ret == -1){
1584
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1585
 
        _exit(EX_OSERR);
1586
 
      }
1587
2055
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1588
2056
      if(ret == -1){
1589
2057
        perror_plus("setenv");
1624
2092
          _exit(EX_OSERR);
1625
2093
        }
1626
2094
      }
1627
 
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
 
2095
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
 
2096
                                                   direntry->d_name,
 
2097
                                                   O_RDONLY));
1628
2098
      if(hook_fd == -1){
1629
2099
        perror_plus("openat");
1630
2100
        _exit(EXIT_FAILURE);
1631
2101
      }
1632
 
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2102
      if(close(hookdir_fd) == -1){
1633
2103
        perror_plus("close");
1634
2104
        _exit(EXIT_FAILURE);
1635
2105
      }
 
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
      }
1636
2121
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
1637
2122
                 environ) == -1){
1638
2123
        perror_plus("fexecve");
1639
2124
        _exit(EXIT_FAILURE);
1640
2125
      }
1641
2126
    } else {
 
2127
      if(hook_pid == -1){
 
2128
        perror_plus("fork");
 
2129
        free(direntry);
 
2130
        continue;
 
2131
      }
1642
2132
      int status;
1643
2133
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1644
2134
        perror_plus("waitpid");
 
2135
        free(direntry);
1645
2136
        continue;
1646
2137
      }
1647
2138
      if(WIFEXITED(status)){
1649
2140
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1650
2141
                       " with status %d\n", direntry->d_name,
1651
2142
                       WEXITSTATUS(status));
 
2143
          free(direntry);
1652
2144
          continue;
1653
2145
        }
1654
2146
      } else if(WIFSIGNALED(status)){
1655
2147
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1656
2148
                     " signal %d\n", direntry->d_name,
1657
2149
                     WTERMSIG(status));
 
2150
        free(direntry);
1658
2151
        continue;
1659
2152
      } else {
1660
2153
        fprintf_plus(stderr, "Warning: network hook \"%s\""
1661
2154
                     " crashed\n", direntry->d_name);
 
2155
        free(direntry);
1662
2156
        continue;
1663
2157
      }
1664
2158
    }
1666
2160
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1667
2161
                   direntry->d_name);
1668
2162
    }
 
2163
    free(direntry);
1669
2164
  }
1670
2165
  free(direntries);
1671
 
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
2166
  if(close(hookdir_fd) == -1){
1672
2167
    perror_plus("close");
1673
2168
  } else {
1674
2169
    hookdir_fd = -1;
1677
2172
}
1678
2173
 
1679
2174
__attribute__((nonnull, warn_unused_result))
1680
 
error_t bring_up_interface(const char *const interface,
1681
 
                           const float delay){
1682
 
  error_t old_errno = errno;
 
2175
int bring_up_interface(const char *const interface,
 
2176
                       const float delay){
 
2177
  int old_errno = errno;
1683
2178
  int ret;
1684
2179
  struct ifreq network;
1685
2180
  unsigned int if_index = if_nametoindex(interface);
1695
2190
  }
1696
2191
  
1697
2192
  if(not interface_is_up(interface)){
1698
 
    error_t ret_errno = 0, ioctl_errno = 0;
 
2193
    int ret_errno = 0;
 
2194
    int ioctl_errno = 0;
1699
2195
    if(not get_flags(interface, &network)){
1700
2196
      ret_errno = errno;
1701
2197
      fprintf_plus(stderr, "Failed to get flags for interface "
1714
2210
    }
1715
2211
    
1716
2212
    if(quit_now){
1717
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2213
      ret = close(sd);
1718
2214
      if(ret == -1){
1719
2215
        perror_plus("close");
1720
2216
      }
1770
2266
    }
1771
2267
    
1772
2268
    /* Close the socket */
1773
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2269
    ret = close(sd);
1774
2270
    if(ret == -1){
1775
2271
      perror_plus("close");
1776
2272
    }
1788
2284
  
1789
2285
  /* Sleep checking until interface is running.
1790
2286
     Check every 0.25s, up to total time of delay */
1791
 
  for(int i=0; i < delay * 4; i++){
 
2287
  for(int i = 0; i < delay * 4; i++){
1792
2288
    if(interface_is_running(interface)){
1793
2289
      break;
1794
2290
    }
1804
2300
}
1805
2301
 
1806
2302
__attribute__((nonnull, warn_unused_result))
1807
 
error_t take_down_interface(const char *const interface){
1808
 
  error_t old_errno = errno;
 
2303
int take_down_interface(const char *const interface){
 
2304
  int old_errno = errno;
1809
2305
  struct ifreq network;
1810
2306
  unsigned int if_index = if_nametoindex(interface);
1811
2307
  if(if_index == 0){
1814
2310
    return ENXIO;
1815
2311
  }
1816
2312
  if(interface_is_up(interface)){
1817
 
    error_t ret_errno = 0, ioctl_errno = 0;
 
2313
    int ret_errno = 0;
 
2314
    int ioctl_errno = 0;
1818
2315
    if(not get_flags(interface, &network) and debug){
1819
2316
      ret_errno = errno;
1820
2317
      fprintf_plus(stderr, "Failed to get flags for interface "
1858
2355
    }
1859
2356
    
1860
2357
    /* Close the socket */
1861
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2358
    int ret = close(sd);
1862
2359
    if(ret == -1){
1863
2360
      perror_plus("close");
1864
2361
    }
1879
2376
}
1880
2377
 
1881
2378
int main(int argc, char *argv[]){
1882
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1883
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1884
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1885
 
                        .interfaces = NULL, .interfaces_size = 0 };
 
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 };
1886
2384
  AvahiSServiceBrowser *sb = NULL;
1887
2385
  error_t ret_errno;
1888
2386
  int ret;
1897
2395
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1898
2396
  const char *seckey = PATHDIR "/" SECKEY;
1899
2397
  const char *pubkey = PATHDIR "/" PUBKEY;
 
2398
  const char *dh_params_file = NULL;
1900
2399
  char *interfaces_hooks = NULL;
1901
2400
  
1902
2401
  bool gnutls_initialized = false;
1955
2454
        .doc = "Bit length of the prime number used in the"
1956
2455
        " Diffie-Hellman key exchange",
1957
2456
        .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 },
1958
2462
      { .name = "priority", .key = 130,
1959
2463
        .arg = "STRING",
1960
2464
        .doc = "GnuTLS priority string for the TLS handshake",
2015
2519
        }
2016
2520
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2017
2521
        break;
 
2522
      case 134:                 /* --dh-params */
 
2523
        dh_params_file = arg;
 
2524
        break;
2018
2525
      case 130:                 /* --priority */
2019
2526
        mc.priority = arg;
2020
2527
        break;
2060
2567
                         .args_doc = "",
2061
2568
                         .doc = "Mandos client -- Get and decrypt"
2062
2569
                         " passwords from a Mandos server" };
2063
 
    ret = argp_parse(&argp, argc, argv,
2064
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2065
 
    switch(ret){
 
2570
    ret_errno = argp_parse(&argp, argc, argv,
 
2571
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2572
    switch(ret_errno){
2066
2573
    case 0:
2067
2574
      break;
2068
2575
    case ENOMEM:
2069
2576
    default:
2070
 
      errno = ret;
 
2577
      errno = ret_errno;
2071
2578
      perror_plus("argp_parse");
2072
2579
      exitcode = EX_OSERR;
2073
2580
      goto end;
2076
2583
      goto end;
2077
2584
    }
2078
2585
  }
2079
 
    
 
2586
  
2080
2587
  {
2081
2588
    /* Work around Debian bug #633582:
2082
 
       <http://bugs.debian.org/633582> */
 
2589
       <https://bugs.debian.org/633582> */
2083
2590
    
2084
2591
    /* Re-raise privileges */
2085
 
    ret_errno = raise_privileges();
2086
 
    if(ret_errno != 0){
2087
 
      errno = ret_errno;
 
2592
    ret = raise_privileges();
 
2593
    if(ret != 0){
 
2594
      errno = ret;
2088
2595
      perror_plus("Failed to raise privileges");
2089
2596
    } else {
2090
2597
      struct stat st;
2106
2613
              }
2107
2614
            }
2108
2615
          }
2109
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2616
          close(seckey_fd);
2110
2617
        }
2111
2618
      }
2112
 
    
 
2619
      
2113
2620
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2114
2621
        int pubkey_fd = open(pubkey, O_RDONLY);
2115
2622
        if(pubkey_fd == -1){
2127
2634
              }
2128
2635
            }
2129
2636
          }
2130
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
2131
 
        }
2132
 
      }
2133
 
    
 
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
      
2134
2663
      /* Lower privileges */
2135
 
      ret_errno = lower_privileges();
2136
 
      if(ret_errno != 0){
2137
 
        errno = ret_errno;
 
2664
      ret = lower_privileges();
 
2665
      if(ret != 0){
 
2666
        errno = ret;
2138
2667
        perror_plus("Failed to lower privileges");
2139
2668
      }
2140
2669
    }
2265
2794
        if(ret_errno != 0){
2266
2795
          errno = ret_errno;
2267
2796
          perror_plus("argz_add");
 
2797
          free(direntries[i]);
2268
2798
          continue;
2269
2799
        }
2270
2800
        if(debug){
2271
2801
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2272
2802
                       direntries[i]->d_name);
2273
2803
        }
 
2804
        free(direntries[i]);
2274
2805
      }
2275
2806
      free(direntries);
2276
2807
    } else {
2308
2839
      errno = bring_up_interface(interface, delay);
2309
2840
      if(not interface_was_up){
2310
2841
        if(errno != 0){
2311
 
          perror_plus("Failed to bring up interface");
 
2842
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
 
2843
                       " %s\n", interface, strerror(errno));
2312
2844
        } else {
2313
2845
          errno = argz_add(&interfaces_to_take_down,
2314
2846
                           &interfaces_to_take_down_size,
2337
2869
    goto end;
2338
2870
  }
2339
2871
  
2340
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2872
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
2341
2873
  if(ret == -1){
2342
2874
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2343
2875
    exitcode = EX_UNAVAILABLE;
2465
2997
    
2466
2998
    /* Allocate a new server */
2467
2999
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2468
 
                                 &config, NULL, NULL, &ret_errno);
 
3000
                                 &config, NULL, NULL, &ret);
2469
3001
    
2470
3002
    /* Free the Avahi configuration data */
2471
3003
    avahi_server_config_free(&config);
2474
3006
  /* Check if creating the Avahi server object succeeded */
2475
3007
  if(mc.server == NULL){
2476
3008
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2477
 
                 avahi_strerror(ret_errno));
 
3009
                 avahi_strerror(ret));
2478
3010
    exitcode = EX_UNAVAILABLE;
2479
3011
    goto end;
2480
3012
  }
2515
3047
 end:
2516
3048
  
2517
3049
  if(debug){
2518
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
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
    }
2519
3057
  }
2520
3058
  
2521
3059
  /* Cleanup things */
2532
3070
  
2533
3071
  if(gnutls_initialized){
2534
3072
    gnutls_certificate_free_credentials(mc.cred);
2535
 
    gnutls_global_deinit();
2536
3073
    gnutls_dh_params_deinit(mc.dh_params);
2537
3074
  }
2538
3075
  
2546
3083
    mc.current_server->prev->next = NULL;
2547
3084
    while(mc.current_server != NULL){
2548
3085
      server *next = mc.current_server->next;
 
3086
#ifdef __GNUC__
 
3087
#pragma GCC diagnostic push
 
3088
#pragma GCC diagnostic ignored "-Wcast-qual"
 
3089
#endif
 
3090
      free((char *)(mc.current_server->ip));
 
3091
#ifdef __GNUC__
 
3092
#pragma GCC diagnostic pop
 
3093
#endif
2549
3094
      free(mc.current_server);
2550
3095
      mc.current_server = next;
2551
3096
    }
2553
3098
  
2554
3099
  /* Re-raise privileges */
2555
3100
  {
2556
 
    ret_errno = raise_privileges();
2557
 
    if(ret_errno != 0){
2558
 
      errno = ret_errno;
 
3101
    ret = raise_privileges();
 
3102
    if(ret != 0){
 
3103
      errno = ret;
2559
3104
      perror_plus("Failed to raise privileges");
2560
3105
    } else {
2561
3106
      
2566
3111
      /* Take down the network interfaces which were brought up */
2567
3112
      {
2568
3113
        char *interface = NULL;
2569
 
        while((interface=argz_next(interfaces_to_take_down,
2570
 
                                   interfaces_to_take_down_size,
2571
 
                                   interface))){
2572
 
          ret_errno = take_down_interface(interface);
2573
 
          if(ret_errno != 0){
2574
 
            errno = ret_errno;
 
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;
2575
3120
            perror_plus("Failed to take down interface");
2576
3121
          }
2577
3122
        }
2582
3127
      }
2583
3128
    }
2584
3129
    
2585
 
    ret_errno = lower_privileges_permanently();
2586
 
    if(ret_errno != 0){
2587
 
      errno = ret_errno;
 
3130
    ret = lower_privileges_permanently();
 
3131
    if(ret != 0){
 
3132
      errno = ret;
2588
3133
      perror_plus("Failed to lower privileges permanently");
2589
3134
    }
2590
3135
  }
2592
3137
  free(interfaces_to_take_down);
2593
3138
  free(interfaces_hooks);
2594
3139
  
 
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
  
2595
3194
  /* Removes the GPGME temp directory and all files inside */
2596
3195
  if(tempdir != NULL){
2597
 
    struct dirent **direntries = NULL;
2598
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY |
2599
 
                                                  O_NOFOLLOW));
2600
 
    if(tempdir_fd == -1){
2601
 
      perror_plus("open");
2602
 
    } else {
2603
 
#ifdef __GLIBC__
2604
 
#if __GLIBC_PREREQ(2, 15)
2605
 
      int numentries = scandirat(tempdir_fd, ".", &direntries,
2606
 
                                 notdotentries, alphasort);
2607
 
#else  /* not __GLIBC_PREREQ(2, 15) */
2608
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2609
 
                               alphasort);
2610
 
#endif  /* not __GLIBC_PREREQ(2, 15) */
2611
 
#else   /* not __GLIBC__ */
2612
 
      int numentries = scandir(tempdir, &direntries, notdotentries,
2613
 
                               alphasort);
2614
 
#endif  /* not __GLIBC__ */
2615
 
      if(numentries >= 0){
2616
 
        for(int i = 0; i < numentries; i++){
2617
 
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
2618
 
          if(ret == -1){
2619
 
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
2620
 
                         " \"%s\", 0): %s\n", tempdir,
2621
 
                         direntries[i]->d_name, strerror(errno));
2622
 
          }
2623
 
        }
2624
 
        
2625
 
        /* need to clean even if 0 because man page doesn't specify */
2626
 
        free(direntries);
2627
 
        if(numentries == -1){
2628
 
          perror_plus("scandir");
2629
 
        }
2630
 
        ret = rmdir(tempdir);
2631
 
        if(ret == -1 and errno != ENOENT){
2632
 
          perror_plus("rmdir");
2633
 
        }
2634
 
      }
2635
 
      TEMP_FAILURE_RETRY(close(tempdir_fd));
2636
 
    }
 
3196
    clean_dir_at(-1, tempdir, 0);
2637
3197
  }
2638
3198
  
2639
3199
  if(quit_now){