/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

  • Committer: Teddy Hogeborn
  • Date: 2018-08-15 09:18:22 UTC
  • mto: (237.7.594 trunk)
  • mto: This revision was merged to the branch mainline in revision 368.
  • 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-2013 Teddy Hogeborn
13
 
 * Copyright © 2008-2013 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
 */
32
33
/* Needed by GPGME, specifically gpgme_data_seek() */
33
34
#ifndef _LARGEFILE_SOURCE
34
35
#define _LARGEFILE_SOURCE
35
 
#endif
 
36
#endif  /* not _LARGEFILE_SOURCE */
36
37
#ifndef _FILE_OFFSET_BITS
37
38
#define _FILE_OFFSET_BITS 64
38
 
#endif
 
39
#endif  /* not _FILE_OFFSET_BITS */
39
40
 
40
41
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
42
 
42
43
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror(), remove() */
 
44
                                   stdout, ferror() */
44
45
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
46
#include <stddef.h>             /* NULL, size_t, ssize_t */
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() */
 
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,
73
79
                                */
74
80
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
81
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit() */
 
82
                                   setgid(), pause(), _exit(),
 
83
                                   unlinkat() */
77
84
#include <arpa/inet.h>          /* inet_pton(), htons() */
78
85
#include <iso646.h>             /* not, or, and */
79
86
#include <argp.h>               /* struct argp_option, error_t, struct
136
143
 
137
144
bool debug = false;
138
145
static const char mandos_protocol_version[] = "1";
139
 
const char * argp_program_version = "mandos-client " VERSION;
140
 
const char * argp_program_bug_address = "<mandos@recompile.se>";
 
146
const char *argp_program_version = "mandos-client " VERSION;
 
147
const char *argp_program_bug_address = "<mandos@recompile.se>";
141
148
static const char sys_class_net[] = "/sys/class/net";
142
149
char *connect_to = NULL;
143
150
const char *hookdir = HOOKDIR;
 
151
int hookdir_fd = -1;
144
152
uid_t uid = 65534;
145
153
gid_t gid = 65534;
146
154
 
232
240
                          .af = af };
233
241
  if(new_server->ip == NULL){
234
242
    perror_plus("strdup");
 
243
    free(new_server);
235
244
    return false;
236
245
  }
237
246
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
238
247
  if(ret == -1){
239
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);
240
258
    return false;
241
259
  }
242
260
  /* Special case of first server */
292
310
                   gpgme_strsource(rc), gpgme_strerror(rc));
293
311
      return false;
294
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
    }
295
388
    
296
 
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
 
389
    ret = close(fd);
297
390
    if(ret == -1){
298
391
      perror_plus("close");
299
392
    }
338
431
  /* Create new GPGME "context" */
339
432
  rc = gpgme_new(&(mc->ctx));
340
433
  if(rc != GPG_ERR_NO_ERROR){
341
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
342
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
343
 
                 gpgme_strerror(rc));
 
434
    fprintf_plus(stderr, "bad gpgme_new: %s: %s\n",
 
435
                 gpgme_strsource(rc), gpgme_strerror(rc));
344
436
    return false;
345
437
  }
346
438
  
382
474
  /* Create new empty GPGME data buffer for the plaintext */
383
475
  rc = gpgme_data_new(&dh_plain);
384
476
  if(rc != GPG_ERR_NO_ERROR){
385
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
386
 
                 "bad gpgme_data_new: %s: %s\n",
 
477
    fprintf_plus(stderr, "bad gpgme_data_new: %s: %s\n",
387
478
                 gpgme_strsource(rc), gpgme_strerror(rc));
388
479
    gpgme_data_release(dh_crypto);
389
480
    return -1;
402
493
      if(result == NULL){
403
494
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
404
495
      } else {
405
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
406
 
                     result->unsupported_algorithm);
407
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
408
 
                     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");
409
502
        if(result->file_name != NULL){
410
503
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
411
504
        }
412
 
        gpgme_recipient_t recipient;
413
 
        recipient = result->recipients;
414
 
        while(recipient != NULL){
 
505
 
 
506
        for(gpgme_recipient_t r = result->recipients; r != NULL;
 
507
            r = r->next){
415
508
          fprintf_plus(stderr, "Public key algorithm: %s\n",
416
 
                       gpgme_pubkey_algo_name
417
 
                       (recipient->pubkey_algo));
418
 
          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);
419
511
          fprintf_plus(stderr, "Secret key available: %s\n",
420
 
                       recipient->status == GPG_ERR_NO_SECKEY
421
 
                       ? "No" : "Yes");
422
 
          recipient = recipient->next;
 
512
                       r->status == GPG_ERR_NO_SECKEY ? "No" : "Yes");
423
513
        }
424
514
      }
425
515
    }
481
571
  return plaintext_length;
482
572
}
483
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
 
484
581
__attribute__((warn_unused_result))
485
582
static const char *safer_gnutls_strerror(int value){
486
583
  const char *ret = gnutls_strerror(value);
487
 
  if(ret == NULL)
488
 
    ret = "(unknown)";
489
 
  return ret;
 
584
  return safe_string(ret);
490
585
}
491
586
 
492
587
/* GnuTLS log function callback */
496
591
  fprintf_plus(stderr, "GnuTLS: %s", string);
497
592
}
498
593
 
499
 
__attribute__((nonnull, warn_unused_result))
 
594
__attribute__((nonnull(1, 2, 4), warn_unused_result))
500
595
static int init_gnutls_global(const char *pubkeyfilename,
501
596
                              const char *seckeyfilename,
 
597
                              const char *dhparamsfilename,
502
598
                              mandos_context *mc){
503
599
  int ret;
 
600
  unsigned int uret;
504
601
  
505
602
  if(debug){
506
603
    fprintf_plus(stderr, "Initializing GnuTLS\n");
507
604
  }
508
605
  
509
 
  ret = gnutls_global_init();
510
 
  if(ret != GNUTLS_E_SUCCESS){
511
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
512
 
                 safer_gnutls_strerror(ret));
513
 
    return -1;
514
 
  }
515
 
  
516
606
  if(debug){
517
607
    /* "Use a log level over 10 to enable all debugging options."
518
608
     * - GnuTLS manual
526
616
  if(ret != GNUTLS_E_SUCCESS){
527
617
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
528
618
                 safer_gnutls_strerror(ret));
529
 
    gnutls_global_deinit();
530
619
    return -1;
531
620
  }
532
621
  
557
646
                 safer_gnutls_strerror(ret));
558
647
    goto globalfail;
559
648
  }
560
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
561
 
  if(ret != GNUTLS_E_SUCCESS){
562
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
563
 
                 safer_gnutls_strerror(ret));
564
 
    goto globalfail;
565
 
  }
566
 
  
 
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
  }
567
826
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
568
827
  
569
828
  return 0;
571
830
 globalfail:
572
831
  
573
832
  gnutls_certificate_free_credentials(mc->cred);
574
 
  gnutls_global_deinit();
575
833
  gnutls_dh_params_deinit(mc->dh_params);
576
834
  return -1;
577
835
}
629
887
  /* ignore client certificate if any. */
630
888
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
631
889
  
632
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
633
 
  
634
890
  return 0;
635
891
}
636
892
 
638
894
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
639
895
                      __attribute__((unused)) const char *txt){}
640
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
 
641
1115
/* Called when a Mandos server is found */
642
1116
__attribute__((nonnull, warn_unused_result))
643
1117
static int start_mandos_communication(const char *ip, in_port_t port,
654
1128
  int retval = -1;
655
1129
  gnutls_session_t session;
656
1130
  int pf;                       /* Protocol family */
 
1131
  bool route_added = false;
657
1132
  
658
1133
  errno = 0;
659
1134
  
681
1156
    bool match = false;
682
1157
    {
683
1158
      char *interface = NULL;
684
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
685
 
                                 interface))){
 
1159
      while((interface = argz_next(mc->interfaces,
 
1160
                                   mc->interfaces_size,
 
1161
                                   interface))){
686
1162
        if(if_nametoindex(interface) == (unsigned int)if_index){
687
1163
          match = true;
688
1164
          break;
717
1193
                 PRIuMAX "\n", ip, (uintmax_t)port);
718
1194
  }
719
1195
  
720
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
1196
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
721
1197
  if(tcp_sd < 0){
722
1198
    int e = errno;
723
1199
    perror_plus("socket");
730
1206
    goto mandos_end;
731
1207
  }
732
1208
  
733
 
  memset(&to, 0, sizeof(to));
734
1209
  if(af == AF_INET6){
735
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
736
 
    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);
737
1213
  } else {                      /* IPv4 */
738
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
739
 
    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);
740
1217
  }
741
1218
  if(ret < 0 ){
742
1219
    int e = errno;
812
1289
    goto mandos_end;
813
1290
  }
814
1291
  
815
 
  if(af == AF_INET6){
816
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
817
 
                  sizeof(struct sockaddr_in6));
818
 
  } else {
819
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
820
 
                  sizeof(struct sockaddr_in));
821
 
  }
822
 
  if(ret < 0){
823
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
824
 
      int e = errno;
825
 
      perror_plus("connect");
826
 
      errno = e;
827
 
    }
828
 
    goto mandos_end;
829
 
  }
830
 
  
831
 
  if(quit_now){
832
 
    errno = EINTR;
833
 
    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;
834
1347
  }
835
1348
  
836
1349
  const char *out = mandos_protocol_version;
990
1503
                                               &decrypted_buffer, mc);
991
1504
    if(decrypted_buffer_size >= 0){
992
1505
      
 
1506
      clearerr(stdout);
993
1507
      written = 0;
994
1508
      while(written < (size_t) decrypted_buffer_size){
995
1509
        if(quit_now){
1011
1525
        }
1012
1526
        written += (size_t)ret;
1013
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
      }
1014
1538
      retval = 0;
1015
1539
    }
1016
1540
  }
1019
1543
  
1020
1544
 mandos_end:
1021
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
    }
1022
1552
    int e = errno;
1023
1553
    free(decrypted_buffer);
1024
1554
    free(buffer);
1025
1555
    if(tcp_sd >= 0){
1026
 
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
1556
      ret = close(tcp_sd);
1027
1557
    }
1028
1558
    if(ret == -1){
1029
1559
      if(e == 0){
1041
1571
  return retval;
1042
1572
}
1043
1573
 
1044
 
__attribute__((nonnull))
1045
1574
static void resolve_callback(AvahiSServiceResolver *r,
1046
1575
                             AvahiIfIndex interface,
1047
1576
                             AvahiProtocol proto,
1064
1593
     timed out */
1065
1594
  
1066
1595
  if(quit_now){
 
1596
    avahi_s_service_resolver_free(r);
1067
1597
    return;
1068
1598
  }
1069
1599
  
1183
1713
__attribute__((nonnull, warn_unused_result))
1184
1714
bool get_flags(const char *ifname, struct ifreq *ifr){
1185
1715
  int ret;
1186
 
  error_t ret_errno;
 
1716
  int old_errno;
1187
1717
  
1188
1718
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1189
1719
  if(s < 0){
1190
 
    ret_errno = errno;
 
1720
    old_errno = errno;
1191
1721
    perror_plus("socket");
1192
 
    errno = ret_errno;
 
1722
    errno = old_errno;
1193
1723
    return false;
1194
1724
  }
1195
 
  strcpy(ifr->ifr_name, ifname);
 
1725
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
 
1726
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1196
1727
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1197
1728
  if(ret == -1){
1198
1729
    if(debug){
1199
 
      ret_errno = errno;
 
1730
      old_errno = errno;
1200
1731
      perror_plus("ioctl SIOCGIFFLAGS");
1201
 
      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;
1202
1738
    }
1203
1739
    return false;
1204
1740
  }
 
1741
  if((close(s) == -1) and debug){
 
1742
    old_errno = errno;
 
1743
    perror_plus("close");
 
1744
    errno = old_errno;
 
1745
  }
1205
1746
  return true;
1206
1747
}
1207
1748
 
1335
1876
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1336
1877
                "abcdefghijklmnopqrstuvwxyz"
1337
1878
                "0123456789"
1338
 
                "_-");
 
1879
                "_.-");
1339
1880
  if((direntry->d_name)[sret] != '\0'){
1340
1881
    /* Contains non-allowed characters */
1341
1882
    if(debug){
1345
1886
    return 0;
1346
1887
  }
1347
1888
  
1348
 
  char *fullname = NULL;
1349
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1350
 
  if(ret < 0){
1351
 
    perror_plus("asprintf");
1352
 
    return 0;
1353
 
  }
1354
 
  
1355
 
  ret = stat(fullname, &st);
 
1889
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
1356
1890
  if(ret == -1){
1357
1891
    if(debug){
1358
1892
      perror_plus("Could not stat hook");
1456
1990
  }
1457
1991
}
1458
1992
 
1459
 
/* Set effective uid to 0, return errno */
1460
 
__attribute__((warn_unused_result))
1461
 
error_t raise_privileges(void){
1462
 
  error_t old_errno = errno;
1463
 
  error_t ret_errno = 0;
1464
 
  if(seteuid(0) == -1){
1465
 
    ret_errno = errno;
1466
 
    perror_plus("seteuid");
1467
 
  }
1468
 
  errno = old_errno;
1469
 
  return ret_errno;
1470
 
}
1471
 
 
1472
 
/* Set effective and real user ID to 0.  Return errno. */
1473
 
__attribute__((warn_unused_result))
1474
 
error_t raise_privileges_permanently(void){
1475
 
  error_t old_errno = errno;
1476
 
  error_t ret_errno = raise_privileges();
1477
 
  if(ret_errno != 0){
1478
 
    errno = old_errno;
1479
 
    return ret_errno;
1480
 
  }
1481
 
  if(setuid(0) == -1){
1482
 
    ret_errno = errno;
1483
 
    perror_plus("seteuid");
1484
 
  }
1485
 
  errno = old_errno;
1486
 
  return ret_errno;
1487
 
}
1488
 
 
1489
 
/* Set effective user ID to unprivileged saved user ID */
1490
 
__attribute__((warn_unused_result))
1491
 
error_t lower_privileges(void){
1492
 
  error_t old_errno = errno;
1493
 
  error_t ret_errno = 0;
1494
 
  if(seteuid(uid) == -1){
1495
 
    ret_errno = errno;
1496
 
    perror_plus("seteuid");
1497
 
  }
1498
 
  errno = old_errno;
1499
 
  return ret_errno;
1500
 
}
1501
 
 
1502
 
/* Lower privileges permanently */
1503
 
__attribute__((warn_unused_result))
1504
 
error_t lower_privileges_permanently(void){
1505
 
  error_t old_errno = errno;
1506
 
  error_t ret_errno = 0;
1507
 
  if(setuid(uid) == -1){
1508
 
    ret_errno = errno;
1509
 
    perror_plus("setuid");
1510
 
  }
1511
 
  errno = old_errno;
1512
 
  return ret_errno;
1513
 
}
1514
 
 
1515
1993
__attribute__((nonnull))
1516
1994
void run_network_hooks(const char *mode, const char *interface,
1517
1995
                       const float delay){
1518
 
  struct dirent **direntries;
1519
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1520
 
                         alphasort);
 
1996
  struct dirent **direntries = NULL;
 
1997
  if(hookdir_fd == -1){
 
1998
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
 
1999
                      | O_CLOEXEC);
 
2000
    if(hookdir_fd == -1){
 
2001
      if(errno == ENOENT){
 
2002
        if(debug){
 
2003
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
2004
                       " found\n", hookdir);
 
2005
        }
 
2006
      } else {
 
2007
        perror_plus("open");
 
2008
      }
 
2009
      return;
 
2010
    }
 
2011
  }
 
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
  }
 
2017
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
 
2018
                           runnable_hook, alphasort);
1521
2019
  if(numhooks == -1){
1522
 
    if(errno == ENOENT){
1523
 
      if(debug){
1524
 
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
1525
 
                     " found\n", hookdir);
1526
 
      }
1527
 
    } else {
1528
 
      perror_plus("scandir");
 
2020
    perror_plus("scandir");
 
2021
    close(devnull);
 
2022
    return;
 
2023
  }
 
2024
  struct dirent *direntry;
 
2025
  int ret;
 
2026
  for(int i = 0; i < numhooks; i++){
 
2027
    direntry = direntries[i];
 
2028
    if(debug){
 
2029
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
2030
                   direntry->d_name);
1529
2031
    }
1530
 
  } else {
1531
 
    struct dirent *direntry;
1532
 
    int ret;
1533
 
    int devnull = open("/dev/null", O_RDONLY);
1534
 
    for(int i = 0; i < numhooks; i++){
1535
 
      direntry = direntries[i];
1536
 
      char *fullname = NULL;
1537
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1538
 
      if(ret < 0){
 
2032
    pid_t hook_pid = fork();
 
2033
    if(hook_pid == 0){
 
2034
      /* Child */
 
2035
      /* Raise privileges */
 
2036
      errno = raise_privileges_permanently();
 
2037
      if(errno != 0){
 
2038
        perror_plus("Failed to raise privileges");
 
2039
        _exit(EX_NOPERM);
 
2040
      }
 
2041
      /* Set group */
 
2042
      errno = 0;
 
2043
      ret = setgid(0);
 
2044
      if(ret == -1){
 
2045
        perror_plus("setgid");
 
2046
        _exit(EX_NOPERM);
 
2047
      }
 
2048
      /* Reset supplementary groups */
 
2049
      errno = 0;
 
2050
      ret = setgroups(0, NULL);
 
2051
      if(ret == -1){
 
2052
        perror_plus("setgroups");
 
2053
        _exit(EX_NOPERM);
 
2054
      }
 
2055
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
2056
      if(ret == -1){
 
2057
        perror_plus("setenv");
 
2058
        _exit(EX_OSERR);
 
2059
      }
 
2060
      ret = setenv("DEVICE", interface, 1);
 
2061
      if(ret == -1){
 
2062
        perror_plus("setenv");
 
2063
        _exit(EX_OSERR);
 
2064
      }
 
2065
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
2066
      if(ret == -1){
 
2067
        perror_plus("setenv");
 
2068
        _exit(EX_OSERR);
 
2069
      }
 
2070
      ret = setenv("MODE", mode, 1);
 
2071
      if(ret == -1){
 
2072
        perror_plus("setenv");
 
2073
        _exit(EX_OSERR);
 
2074
      }
 
2075
      char *delaystring;
 
2076
      ret = asprintf(&delaystring, "%f", (double)delay);
 
2077
      if(ret == -1){
1539
2078
        perror_plus("asprintf");
1540
 
        continue;
1541
 
      }
1542
 
      if(debug){
1543
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1544
 
                     direntry->d_name);
1545
 
      }
1546
 
      pid_t hook_pid = fork();
1547
 
      if(hook_pid == 0){
1548
 
        /* Child */
1549
 
        /* Raise privileges */
1550
 
        if(raise_privileges_permanently() != 0){
1551
 
          perror_plus("Failed to raise privileges");
1552
 
          _exit(EX_NOPERM);
1553
 
        }
1554
 
        /* Set group */
1555
 
        errno = 0;
1556
 
        ret = setgid(0);
1557
 
        if(ret == -1){
1558
 
          perror_plus("setgid");
1559
 
          _exit(EX_NOPERM);
1560
 
        }
1561
 
        /* Reset supplementary groups */
1562
 
        errno = 0;
1563
 
        ret = setgroups(0, NULL);
1564
 
        if(ret == -1){
1565
 
          perror_plus("setgroups");
1566
 
          _exit(EX_NOPERM);
1567
 
        }
1568
 
        ret = dup2(devnull, STDIN_FILENO);
1569
 
        if(ret == -1){
1570
 
          perror_plus("dup2(devnull, STDIN_FILENO)");
1571
 
          _exit(EX_OSERR);
1572
 
        }
1573
 
        ret = close(devnull);
1574
 
        if(ret == -1){
1575
 
          perror_plus("close");
1576
 
          _exit(EX_OSERR);
1577
 
        }
1578
 
        ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1579
 
        if(ret == -1){
1580
 
          perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1581
 
          _exit(EX_OSERR);
1582
 
        }
1583
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1584
 
        if(ret == -1){
1585
 
          perror_plus("setenv");
1586
 
          _exit(EX_OSERR);
1587
 
        }
1588
 
        ret = setenv("DEVICE", interface, 1);
1589
 
        if(ret == -1){
1590
 
          perror_plus("setenv");
1591
 
          _exit(EX_OSERR);
1592
 
        }
1593
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1594
 
        if(ret == -1){
1595
 
          perror_plus("setenv");
1596
 
          _exit(EX_OSERR);
1597
 
        }
1598
 
        ret = setenv("MODE", mode, 1);
1599
 
        if(ret == -1){
1600
 
          perror_plus("setenv");
1601
 
          _exit(EX_OSERR);
1602
 
        }
1603
 
        char *delaystring;
1604
 
        ret = asprintf(&delaystring, "%f", (double)delay);
1605
 
        if(ret == -1){
1606
 
          perror_plus("asprintf");
1607
 
          _exit(EX_OSERR);
1608
 
        }
1609
 
        ret = setenv("DELAY", delaystring, 1);
1610
 
        if(ret == -1){
1611
 
          free(delaystring);
1612
 
          perror_plus("setenv");
1613
 
          _exit(EX_OSERR);
1614
 
        }
 
2079
        _exit(EX_OSERR);
 
2080
      }
 
2081
      ret = setenv("DELAY", delaystring, 1);
 
2082
      if(ret == -1){
1615
2083
        free(delaystring);
1616
 
        if(connect_to != NULL){
1617
 
          ret = setenv("CONNECT", connect_to, 1);
1618
 
          if(ret == -1){
1619
 
            perror_plus("setenv");
1620
 
            _exit(EX_OSERR);
1621
 
          }
1622
 
        }
1623
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1624
 
          perror_plus("execl");
1625
 
          _exit(EXIT_FAILURE);
1626
 
        }
 
2084
        perror_plus("setenv");
 
2085
        _exit(EX_OSERR);
 
2086
      }
 
2087
      free(delaystring);
 
2088
      if(connect_to != NULL){
 
2089
        ret = setenv("CONNECT", connect_to, 1);
 
2090
        if(ret == -1){
 
2091
          perror_plus("setenv");
 
2092
          _exit(EX_OSERR);
 
2093
        }
 
2094
      }
 
2095
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
 
2096
                                                   direntry->d_name,
 
2097
                                                   O_RDONLY));
 
2098
      if(hook_fd == -1){
 
2099
        perror_plus("openat");
 
2100
        _exit(EXIT_FAILURE);
 
2101
      }
 
2102
      if(close(hookdir_fd) == -1){
 
2103
        perror_plus("close");
 
2104
        _exit(EXIT_FAILURE);
 
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
      }
 
2121
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
 
2122
                 environ) == -1){
 
2123
        perror_plus("fexecve");
 
2124
        _exit(EXIT_FAILURE);
 
2125
      }
 
2126
    } else {
 
2127
      if(hook_pid == -1){
 
2128
        perror_plus("fork");
 
2129
        free(direntry);
 
2130
        continue;
 
2131
      }
 
2132
      int status;
 
2133
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
2134
        perror_plus("waitpid");
 
2135
        free(direntry);
 
2136
        continue;
 
2137
      }
 
2138
      if(WIFEXITED(status)){
 
2139
        if(WEXITSTATUS(status) != 0){
 
2140
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
2141
                       " with status %d\n", direntry->d_name,
 
2142
                       WEXITSTATUS(status));
 
2143
          free(direntry);
 
2144
          continue;
 
2145
        }
 
2146
      } else if(WIFSIGNALED(status)){
 
2147
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
2148
                     " signal %d\n", direntry->d_name,
 
2149
                     WTERMSIG(status));
 
2150
        free(direntry);
 
2151
        continue;
1627
2152
      } else {
1628
 
        int status;
1629
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1630
 
          perror_plus("waitpid");
1631
 
          free(fullname);
1632
 
          continue;
1633
 
        }
1634
 
        if(WIFEXITED(status)){
1635
 
          if(WEXITSTATUS(status) != 0){
1636
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1637
 
                         " with status %d\n", direntry->d_name,
1638
 
                         WEXITSTATUS(status));
1639
 
            free(fullname);
1640
 
            continue;
1641
 
          }
1642
 
        } else if(WIFSIGNALED(status)){
1643
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1644
 
                       " signal %d\n", direntry->d_name,
1645
 
                       WTERMSIG(status));
1646
 
          free(fullname);
1647
 
          continue;
1648
 
        } else {
1649
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1650
 
                       " crashed\n", direntry->d_name);
1651
 
          free(fullname);
1652
 
          continue;
1653
 
        }
1654
 
      }
1655
 
      free(fullname);
1656
 
      if(debug){
1657
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1658
 
                     direntry->d_name);
1659
 
      }
1660
 
    }
1661
 
    close(devnull);
1662
 
  }
 
2153
        fprintf_plus(stderr, "Warning: network hook \"%s\""
 
2154
                     " crashed\n", direntry->d_name);
 
2155
        free(direntry);
 
2156
        continue;
 
2157
      }
 
2158
    }
 
2159
    if(debug){
 
2160
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
2161
                   direntry->d_name);
 
2162
    }
 
2163
    free(direntry);
 
2164
  }
 
2165
  free(direntries);
 
2166
  if(close(hookdir_fd) == -1){
 
2167
    perror_plus("close");
 
2168
  } else {
 
2169
    hookdir_fd = -1;
 
2170
  }
 
2171
  close(devnull);
1663
2172
}
1664
2173
 
1665
2174
__attribute__((nonnull, warn_unused_result))
1666
 
error_t bring_up_interface(const char *const interface,
1667
 
                           const float delay){
1668
 
  error_t old_errno = errno;
 
2175
int bring_up_interface(const char *const interface,
 
2176
                       const float delay){
 
2177
  int old_errno = errno;
1669
2178
  int ret;
1670
2179
  struct ifreq network;
1671
2180
  unsigned int if_index = if_nametoindex(interface);
1681
2190
  }
1682
2191
  
1683
2192
  if(not interface_is_up(interface)){
1684
 
    error_t ret_errno = 0, ioctl_errno = 0;
 
2193
    int ret_errno = 0;
 
2194
    int ioctl_errno = 0;
1685
2195
    if(not get_flags(interface, &network)){
1686
2196
      ret_errno = errno;
1687
2197
      fprintf_plus(stderr, "Failed to get flags for interface "
1700
2210
    }
1701
2211
    
1702
2212
    if(quit_now){
1703
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2213
      ret = close(sd);
1704
2214
      if(ret == -1){
1705
2215
        perror_plus("close");
1706
2216
      }
1715
2225
    
1716
2226
    /* Raise privileges */
1717
2227
    ret_errno = raise_privileges();
 
2228
    if(ret_errno != 0){
 
2229
      errno = ret_errno;
 
2230
      perror_plus("Failed to raise privileges");
 
2231
    }
 
2232
    
 
2233
#ifdef __linux__
 
2234
    int ret_linux;
1718
2235
    bool restore_loglevel = false;
1719
 
    if(ret_errno != 0){
1720
 
      perror_plus("Failed to raise privileges");
1721
 
    }
1722
 
#ifdef __linux__
1723
 
    int ret_linux;
1724
2236
    if(ret_errno == 0){
1725
2237
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1726
2238
         messages about the network interface to mess up the prompt */
1754
2266
    }
1755
2267
    
1756
2268
    /* Close the socket */
1757
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2269
    ret = close(sd);
1758
2270
    if(ret == -1){
1759
2271
      perror_plus("close");
1760
2272
    }
1772
2284
  
1773
2285
  /* Sleep checking until interface is running.
1774
2286
     Check every 0.25s, up to total time of delay */
1775
 
  for(int i=0; i < delay * 4; i++){
 
2287
  for(int i = 0; i < delay * 4; i++){
1776
2288
    if(interface_is_running(interface)){
1777
2289
      break;
1778
2290
    }
1788
2300
}
1789
2301
 
1790
2302
__attribute__((nonnull, warn_unused_result))
1791
 
error_t take_down_interface(const char *const interface){
1792
 
  error_t old_errno = errno;
 
2303
int take_down_interface(const char *const interface){
 
2304
  int old_errno = errno;
1793
2305
  struct ifreq network;
1794
2306
  unsigned int if_index = if_nametoindex(interface);
1795
2307
  if(if_index == 0){
1798
2310
    return ENXIO;
1799
2311
  }
1800
2312
  if(interface_is_up(interface)){
1801
 
    error_t ret_errno = 0, ioctl_errno = 0;
 
2313
    int ret_errno = 0;
 
2314
    int ioctl_errno = 0;
1802
2315
    if(not get_flags(interface, &network) and debug){
1803
2316
      ret_errno = errno;
1804
2317
      fprintf_plus(stderr, "Failed to get flags for interface "
1824
2337
    /* Raise privileges */
1825
2338
    ret_errno = raise_privileges();
1826
2339
    if(ret_errno != 0){
 
2340
      errno = ret_errno;
1827
2341
      perror_plus("Failed to raise privileges");
1828
2342
    }
 
2343
    
1829
2344
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1830
2345
    ioctl_errno = errno;
1831
2346
    
1840
2355
    }
1841
2356
    
1842
2357
    /* Close the socket */
1843
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2358
    int ret = close(sd);
1844
2359
    if(ret == -1){
1845
2360
      perror_plus("close");
1846
2361
    }
1861
2376
}
1862
2377
 
1863
2378
int main(int argc, char *argv[]){
1864
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1865
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1866
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1867
 
                        .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 };
1868
2384
  AvahiSServiceBrowser *sb = NULL;
1869
2385
  error_t ret_errno;
1870
2386
  int ret;
1879
2395
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1880
2396
  const char *seckey = PATHDIR "/" SECKEY;
1881
2397
  const char *pubkey = PATHDIR "/" PUBKEY;
 
2398
  const char *dh_params_file = NULL;
1882
2399
  char *interfaces_hooks = NULL;
1883
2400
  
1884
2401
  bool gnutls_initialized = false;
1937
2454
        .doc = "Bit length of the prime number used in the"
1938
2455
        " Diffie-Hellman key exchange",
1939
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 },
1940
2462
      { .name = "priority", .key = 130,
1941
2463
        .arg = "STRING",
1942
2464
        .doc = "GnuTLS priority string for the TLS handshake",
1997
2519
        }
1998
2520
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1999
2521
        break;
 
2522
      case 134:                 /* --dh-params */
 
2523
        dh_params_file = arg;
 
2524
        break;
2000
2525
      case 130:                 /* --priority */
2001
2526
        mc.priority = arg;
2002
2527
        break;
2042
2567
                         .args_doc = "",
2043
2568
                         .doc = "Mandos client -- Get and decrypt"
2044
2569
                         " passwords from a Mandos server" };
2045
 
    ret = argp_parse(&argp, argc, argv,
2046
 
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2047
 
    switch(ret){
 
2570
    ret_errno = argp_parse(&argp, argc, argv,
 
2571
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2572
    switch(ret_errno){
2048
2573
    case 0:
2049
2574
      break;
2050
2575
    case ENOMEM:
2051
2576
    default:
2052
 
      errno = ret;
 
2577
      errno = ret_errno;
2053
2578
      perror_plus("argp_parse");
2054
2579
      exitcode = EX_OSERR;
2055
2580
      goto end;
2058
2583
      goto end;
2059
2584
    }
2060
2585
  }
2061
 
    
 
2586
  
2062
2587
  {
2063
2588
    /* Work around Debian bug #633582:
2064
 
       <http://bugs.debian.org/633582> */
 
2589
       <https://bugs.debian.org/633582> */
2065
2590
    
2066
2591
    /* Re-raise privileges */
2067
 
    ret_errno = raise_privileges();
2068
 
    if(ret_errno != 0){
2069
 
      errno = ret_errno;
 
2592
    ret = raise_privileges();
 
2593
    if(ret != 0){
 
2594
      errno = ret;
2070
2595
      perror_plus("Failed to raise privileges");
2071
2596
    } else {
2072
2597
      struct stat st;
2088
2613
              }
2089
2614
            }
2090
2615
          }
2091
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2616
          close(seckey_fd);
2092
2617
        }
2093
2618
      }
2094
 
    
 
2619
      
2095
2620
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2096
2621
        int pubkey_fd = open(pubkey, O_RDONLY);
2097
2622
        if(pubkey_fd == -1){
2109
2634
              }
2110
2635
            }
2111
2636
          }
2112
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
2113
 
        }
2114
 
      }
2115
 
    
 
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
      
2116
2663
      /* Lower privileges */
2117
 
      ret_errno = lower_privileges();
2118
 
      if(ret_errno != 0){
2119
 
        errno = ret_errno;
 
2664
      ret = lower_privileges();
 
2665
      if(ret != 0){
 
2666
        errno = ret;
2120
2667
        perror_plus("Failed to lower privileges");
2121
2668
      }
2122
2669
    }
2235
2782
  
2236
2783
  /* If no interfaces were specified, make a list */
2237
2784
  if(mc.interfaces == NULL){
2238
 
    struct dirent **direntries;
 
2785
    struct dirent **direntries = NULL;
2239
2786
    /* Look for any good interfaces */
2240
2787
    ret = scandir(sys_class_net, &direntries, good_interface,
2241
2788
                  alphasort);
2247
2794
        if(ret_errno != 0){
2248
2795
          errno = ret_errno;
2249
2796
          perror_plus("argz_add");
 
2797
          free(direntries[i]);
2250
2798
          continue;
2251
2799
        }
2252
2800
        if(debug){
2253
2801
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2254
2802
                       direntries[i]->d_name);
2255
2803
        }
 
2804
        free(direntries[i]);
2256
2805
      }
2257
2806
      free(direntries);
2258
2807
    } else {
2259
 
      free(direntries);
 
2808
      if(ret == 0){
 
2809
        free(direntries);
 
2810
      }
2260
2811
      fprintf_plus(stderr, "Could not find a network interface\n");
2261
2812
      exitcode = EXIT_FAILURE;
2262
2813
      goto end;
2288
2839
      errno = bring_up_interface(interface, delay);
2289
2840
      if(not interface_was_up){
2290
2841
        if(errno != 0){
2291
 
          perror_plus("Failed to bring up interface");
 
2842
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
 
2843
                       " %s\n", interface, strerror(errno));
2292
2844
        } else {
2293
2845
          errno = argz_add(&interfaces_to_take_down,
2294
2846
                           &interfaces_to_take_down_size,
2317
2869
    goto end;
2318
2870
  }
2319
2871
  
2320
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2872
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
2321
2873
  if(ret == -1){
2322
2874
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2323
2875
    exitcode = EX_UNAVAILABLE;
2445
2997
    
2446
2998
    /* Allocate a new server */
2447
2999
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2448
 
                                 &config, NULL, NULL, &ret_errno);
 
3000
                                 &config, NULL, NULL, &ret);
2449
3001
    
2450
3002
    /* Free the Avahi configuration data */
2451
3003
    avahi_server_config_free(&config);
2454
3006
  /* Check if creating the Avahi server object succeeded */
2455
3007
  if(mc.server == NULL){
2456
3008
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2457
 
                 avahi_strerror(ret_errno));
 
3009
                 avahi_strerror(ret));
2458
3010
    exitcode = EX_UNAVAILABLE;
2459
3011
    goto end;
2460
3012
  }
2484
3036
  if(debug){
2485
3037
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2486
3038
  }
2487
 
 
 
3039
  
2488
3040
  ret = avahi_loop_with_timeout(simple_poll,
2489
3041
                                (int)(retry_interval * 1000), &mc);
2490
3042
  if(debug){
2495
3047
 end:
2496
3048
  
2497
3049
  if(debug){
2498
 
    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
    }
2499
3057
  }
2500
3058
  
2501
3059
  /* Cleanup things */
2512
3070
  
2513
3071
  if(gnutls_initialized){
2514
3072
    gnutls_certificate_free_credentials(mc.cred);
2515
 
    gnutls_global_deinit();
2516
3073
    gnutls_dh_params_deinit(mc.dh_params);
2517
3074
  }
2518
3075
  
2526
3083
    mc.current_server->prev->next = NULL;
2527
3084
    while(mc.current_server != NULL){
2528
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
2529
3094
      free(mc.current_server);
2530
3095
      mc.current_server = next;
2531
3096
    }
2533
3098
  
2534
3099
  /* Re-raise privileges */
2535
3100
  {
2536
 
    ret_errno = raise_privileges();
2537
 
    if(ret_errno != 0){
 
3101
    ret = raise_privileges();
 
3102
    if(ret != 0){
 
3103
      errno = ret;
2538
3104
      perror_plus("Failed to raise privileges");
2539
3105
    } else {
2540
3106
      
2545
3111
      /* Take down the network interfaces which were brought up */
2546
3112
      {
2547
3113
        char *interface = NULL;
2548
 
        while((interface=argz_next(interfaces_to_take_down,
2549
 
                                   interfaces_to_take_down_size,
2550
 
                                   interface))){
2551
 
          ret_errno = take_down_interface(interface);
2552
 
          if(ret_errno != 0){
2553
 
            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;
2554
3120
            perror_plus("Failed to take down interface");
2555
3121
          }
2556
3122
        }
2560
3126
        }
2561
3127
      }
2562
3128
    }
2563
 
    ret_errno = lower_privileges_permanently();
2564
 
    if(ret_errno != 0){
 
3129
    
 
3130
    ret = lower_privileges_permanently();
 
3131
    if(ret != 0){
 
3132
      errno = ret;
2565
3133
      perror_plus("Failed to lower privileges permanently");
2566
3134
    }
2567
3135
  }
2569
3137
  free(interfaces_to_take_down);
2570
3138
  free(interfaces_hooks);
2571
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
  
2572
3194
  /* Removes the GPGME temp directory and all files inside */
2573
3195
  if(tempdir != NULL){
2574
 
    struct dirent **direntries = NULL;
2575
 
    struct dirent *direntry = NULL;
2576
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2577
 
                             alphasort);
2578
 
    if(numentries > 0){
2579
 
      for(int i = 0; i < numentries; i++){
2580
 
        direntry = direntries[i];
2581
 
        char *fullname = NULL;
2582
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
2583
 
                       direntry->d_name);
2584
 
        if(ret < 0){
2585
 
          perror_plus("asprintf");
2586
 
          continue;
2587
 
        }
2588
 
        ret = remove(fullname);
2589
 
        if(ret == -1){
2590
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2591
 
                       strerror(errno));
2592
 
        }
2593
 
        free(fullname);
2594
 
      }
2595
 
    }
2596
 
 
2597
 
    /* need to clean even if 0 because man page doesn't specify */
2598
 
    free(direntries);
2599
 
    if(numentries == -1){
2600
 
      perror_plus("scandir");
2601
 
    }
2602
 
    ret = rmdir(tempdir);
2603
 
    if(ret == -1 and errno != ENOENT){
2604
 
      perror_plus("rmdir");
2605
 
    }
 
3196
    clean_dir_at(-1, tempdir, 0);
2606
3197
  }
2607
3198
  
2608
3199
  if(quit_now){