/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2015-07-06 20:09:47 UTC
  • mto: This revision was merged to the branch mainline in revision 759.
  • Revision ID: teddy@recompile.se-20150706200947-w21u4eq74efgl6r5
Fix minor bugs and typos and add some more debug output.

* Makefile (install-client-nokey): Create plugin-helpers directory and
                                   the mandos-client-iprouteadddel
                                   helper program.
* initramfs-tools-hook (PLUGINHELPERDIR): Fix typo.
* plugins.d/mandos-client.c: Change terminology; routes are "deleted",
                             not "removed".  All occurences changed.
  (add_remove_local_route): Renamed to "add_delete_local_route".  All
                            callers changed.  Also pass "--debug" flag
                            to helper if in debug mode.
  (add_local_route): Add debugging output.
  (remove_local_route): Renamed to "delete_local_route".  All callers
                        changed.  Also pass "--debug" flag to helper
                        if in debug mode.
  (start_mandos_communication): Add debug output when adding route.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2018 Teddy Hogeborn
13
 
 * Copyright © 2008-2018 Björn Påhlsson
14
 
 * 
15
 
 * This file is part of Mandos.
16
 
 * 
17
 
 * Mandos is free software: you can redistribute it and/or modify it
18
 
 * under the terms of the GNU General Public License as published by
19
 
 * the Free Software Foundation, either version 3 of the License, or
20
 
 * (at your option) any later version.
21
 
 * 
22
 
 * Mandos is distributed in the hope that it will be useful, but
 
12
 * Copyright © 2008-2015 Teddy Hogeborn
 
13
 * Copyright © 2008-2015 Björn Påhlsson
 
14
 * 
 
15
 * This program is free software: you can redistribute it and/or
 
16
 * modify it under the terms of the GNU General Public License as
 
17
 * published by the Free Software Foundation, either version 3 of the
 
18
 * License, or (at your option) any later version.
 
19
 * 
 
20
 * This program is distributed in the hope that it will be useful, but
23
21
 * WITHOUT ANY WARRANTY; without even the implied warranty of
24
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25
23
 * General Public License for more details.
26
24
 * 
27
25
 * You should have received a copy of the GNU General Public License
28
 
 * along with Mandos.  If not, see <http://www.gnu.org/licenses/>.
 
26
 * along with this program.  If not, see
 
27
 * <http://www.gnu.org/licenses/>.
29
28
 * 
30
29
 * Contact the authors at <mandos@recompile.se>.
31
30
 */
47
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
48
47
                                   strtof(), abort() */
49
48
#include <stdbool.h>            /* bool, false, true */
50
 
#include <string.h>             /* strcmp(), strlen(), strerror(),
51
 
                                   asprintf(), strncpy(), strsignal()
52
 
                                */
 
49
#include <string.h>             /* memset(), strcmp(), strlen(),
 
50
                                   strerror(), asprintf(), strcpy() */
53
51
#include <sys/ioctl.h>          /* ioctl */
54
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
55
53
                                   sockaddr_in6, PF_INET6,
59
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
60
58
                                   inet_pton(), connect(),
61
59
                                   getnameinfo() */
62
 
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
 
60
#include <fcntl.h>              /* open(), unlinkat() */
63
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
64
62
                                 */
65
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
66
64
                                   strtoimax() */
67
 
#include <errno.h>              /* perror(), errno, EINTR, EINVAL,
68
 
                                   EAI_SYSTEM, ENETUNREACH,
69
 
                                   EHOSTUNREACH, ECONNREFUSED, EPROTO,
70
 
                                   EIO, ENOENT, ENXIO, ENOMEM, EISDIR,
71
 
                                   ENOTEMPTY,
 
65
#include <errno.h>              /* perror(), errno,
72
66
                                   program_invocation_short_name */
73
67
#include <time.h>               /* nanosleep(), time(), sleep() */
74
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
310
304
                   gpgme_strsource(rc), gpgme_strerror(rc));
311
305
      return false;
312
306
    }
313
 
    {
314
 
      gpgme_import_result_t import_result
315
 
        = gpgme_op_import_result(mc->ctx);
316
 
      if((import_result->imported < 1
317
 
          or import_result->not_imported > 0)
318
 
         and import_result->unchanged == 0){
319
 
        fprintf_plus(stderr, "bad gpgme_op_import_results:\n");
320
 
        fprintf_plus(stderr,
321
 
                     "The total number of considered keys: %d\n",
322
 
                     import_result->considered);
323
 
        fprintf_plus(stderr,
324
 
                     "The number of keys without user ID: %d\n",
325
 
                     import_result->no_user_id);
326
 
        fprintf_plus(stderr,
327
 
                     "The total number of imported keys: %d\n",
328
 
                     import_result->imported);
329
 
        fprintf_plus(stderr, "The number of imported RSA keys: %d\n",
330
 
                     import_result->imported_rsa);
331
 
        fprintf_plus(stderr, "The number of unchanged keys: %d\n",
332
 
                     import_result->unchanged);
333
 
        fprintf_plus(stderr, "The number of new user IDs: %d\n",
334
 
                     import_result->new_user_ids);
335
 
        fprintf_plus(stderr, "The number of new sub keys: %d\n",
336
 
                     import_result->new_sub_keys);
337
 
        fprintf_plus(stderr, "The number of new signatures: %d\n",
338
 
                     import_result->new_signatures);
339
 
        fprintf_plus(stderr, "The number of new revocations: %d\n",
340
 
                     import_result->new_revocations);
341
 
        fprintf_plus(stderr,
342
 
                     "The total number of secret keys read: %d\n",
343
 
                     import_result->secret_read);
344
 
        fprintf_plus(stderr,
345
 
                     "The number of imported secret keys: %d\n",
346
 
                     import_result->secret_imported);
347
 
        fprintf_plus(stderr,
348
 
                     "The number of unchanged secret keys: %d\n",
349
 
                     import_result->secret_unchanged);
350
 
        fprintf_plus(stderr, "The number of keys not imported: %d\n",
351
 
                     import_result->not_imported);
352
 
        for(gpgme_import_status_t import_status
353
 
              = import_result->imports;
354
 
            import_status != NULL;
355
 
            import_status = import_status->next){
356
 
          fprintf_plus(stderr, "Import status for key: %s\n",
357
 
                       import_status->fpr);
358
 
          if(import_status->result != GPG_ERR_NO_ERROR){
359
 
            fprintf_plus(stderr, "Import result: %s: %s\n",
360
 
                         gpgme_strsource(import_status->result),
361
 
                         gpgme_strerror(import_status->result));
362
 
          }
363
 
          fprintf_plus(stderr, "Key status:\n");
364
 
          fprintf_plus(stderr,
365
 
                       import_status->status & GPGME_IMPORT_NEW
366
 
                       ? "The key was new.\n"
367
 
                       : "The key was not new.\n");
368
 
          fprintf_plus(stderr,
369
 
                       import_status->status & GPGME_IMPORT_UID
370
 
                       ? "The key contained new user IDs.\n"
371
 
                       : "The key did not contain new user IDs.\n");
372
 
          fprintf_plus(stderr,
373
 
                       import_status->status & GPGME_IMPORT_SIG
374
 
                       ? "The key contained new signatures.\n"
375
 
                       : "The key did not contain new signatures.\n");
376
 
          fprintf_plus(stderr,
377
 
                       import_status->status & GPGME_IMPORT_SUBKEY
378
 
                       ? "The key contained new sub keys.\n"
379
 
                       : "The key did not contain new sub keys.\n");
380
 
          fprintf_plus(stderr,
381
 
                       import_status->status & GPGME_IMPORT_SECRET
382
 
                       ? "The key contained a secret key.\n"
383
 
                       : "The key did not contain a secret key.\n");
384
 
        }
385
 
        return false;
386
 
      }
387
 
    }
388
307
    
389
 
    ret = close(fd);
 
308
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
390
309
    if(ret == -1){
391
310
      perror_plus("close");
392
311
    }
431
350
  /* Create new GPGME "context" */
432
351
  rc = gpgme_new(&(mc->ctx));
433
352
  if(rc != GPG_ERR_NO_ERROR){
434
 
    fprintf_plus(stderr, "bad gpgme_new: %s: %s\n",
435
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
353
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
354
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
355
                 gpgme_strerror(rc));
436
356
    return false;
437
357
  }
438
358
  
474
394
  /* Create new empty GPGME data buffer for the plaintext */
475
395
  rc = gpgme_data_new(&dh_plain);
476
396
  if(rc != GPG_ERR_NO_ERROR){
477
 
    fprintf_plus(stderr, "bad gpgme_data_new: %s: %s\n",
 
397
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
398
                 "bad gpgme_data_new: %s: %s\n",
478
399
                 gpgme_strsource(rc), gpgme_strerror(rc));
479
400
    gpgme_data_release(dh_crypto);
480
401
    return -1;
493
414
      if(result == NULL){
494
415
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
495
416
      } else {
496
 
        if(result->unsupported_algorithm != NULL) {
497
 
          fprintf_plus(stderr, "Unsupported algorithm: %s\n",
498
 
                       result->unsupported_algorithm);
499
 
        }
500
 
        fprintf_plus(stderr, "Wrong key usage: %s\n",
501
 
                     result->wrong_key_usage ? "Yes" : "No");
 
417
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
418
                     result->unsupported_algorithm);
 
419
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
420
                     result->wrong_key_usage);
502
421
        if(result->file_name != NULL){
503
422
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
504
423
        }
505
 
 
506
 
        for(gpgme_recipient_t r = result->recipients; r != NULL;
507
 
            r = r->next){
 
424
        gpgme_recipient_t recipient;
 
425
        recipient = result->recipients;
 
426
        while(recipient != NULL){
508
427
          fprintf_plus(stderr, "Public key algorithm: %s\n",
509
 
                       gpgme_pubkey_algo_name(r->pubkey_algo));
510
 
          fprintf_plus(stderr, "Key ID: %s\n", r->keyid);
 
428
                       gpgme_pubkey_algo_name
 
429
                       (recipient->pubkey_algo));
 
430
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
511
431
          fprintf_plus(stderr, "Secret key available: %s\n",
512
 
                       r->status == GPG_ERR_NO_SECKEY ? "No" : "Yes");
 
432
                       recipient->status == GPG_ERR_NO_SECKEY
 
433
                       ? "No" : "Yes");
 
434
          recipient = recipient->next;
513
435
        }
514
436
      }
515
437
    }
571
493
  return plaintext_length;
572
494
}
573
495
 
574
 
__attribute__((warn_unused_result, const))
575
 
static const char *safe_string(const char *str){
576
 
  if(str == NULL)
577
 
    return "(unknown)";
578
 
  return str;
579
 
}
580
 
 
581
496
__attribute__((warn_unused_result))
582
497
static const char *safer_gnutls_strerror(int value){
583
498
  const char *ret = gnutls_strerror(value);
584
 
  return safe_string(ret);
 
499
  if(ret == NULL)
 
500
    ret = "(unknown)";
 
501
  return ret;
585
502
}
586
503
 
587
504
/* GnuTLS log function callback */
591
508
  fprintf_plus(stderr, "GnuTLS: %s", string);
592
509
}
593
510
 
594
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
 
511
__attribute__((nonnull, warn_unused_result))
595
512
static int init_gnutls_global(const char *pubkeyfilename,
596
513
                              const char *seckeyfilename,
597
 
                              const char *dhparamsfilename,
598
514
                              mandos_context *mc){
599
515
  int ret;
600
 
  unsigned int uret;
601
516
  
602
517
  if(debug){
603
518
    fprintf_plus(stderr, "Initializing GnuTLS\n");
604
519
  }
605
520
  
 
521
  ret = gnutls_global_init();
 
522
  if(ret != GNUTLS_E_SUCCESS){
 
523
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
524
                 safer_gnutls_strerror(ret));
 
525
    return -1;
 
526
  }
 
527
  
606
528
  if(debug){
607
529
    /* "Use a log level over 10 to enable all debugging options."
608
530
     * - GnuTLS manual
616
538
  if(ret != GNUTLS_E_SUCCESS){
617
539
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
618
540
                 safer_gnutls_strerror(ret));
 
541
    gnutls_global_deinit();
619
542
    return -1;
620
543
  }
621
544
  
646
569
                 safer_gnutls_strerror(ret));
647
570
    goto globalfail;
648
571
  }
649
 
  /* If a Diffie-Hellman parameters file was given, try to use it */
650
 
  if(dhparamsfilename != NULL){
651
 
    gnutls_datum_t params = { .data = NULL, .size = 0 };
652
 
    do {
653
 
      int dhpfile = open(dhparamsfilename, O_RDONLY);
654
 
      if(dhpfile == -1){
655
 
        perror_plus("open");
656
 
        dhparamsfilename = NULL;
657
 
        break;
658
 
      }
659
 
      size_t params_capacity = 0;
660
 
      while(true){
661
 
        params_capacity = incbuffer((char **)&params.data,
662
 
                                    (size_t)params.size,
663
 
                                    (size_t)params_capacity);
664
 
        if(params_capacity == 0){
665
 
          perror_plus("incbuffer");
666
 
          free(params.data);
667
 
          params.data = NULL;
668
 
          dhparamsfilename = NULL;
669
 
          break;
670
 
        }
671
 
        ssize_t bytes_read = read(dhpfile,
672
 
                                  params.data + params.size,
673
 
                                  BUFFER_SIZE);
674
 
        /* EOF */
675
 
        if(bytes_read == 0){
676
 
          break;
677
 
        }
678
 
        /* check bytes_read for failure */
679
 
        if(bytes_read < 0){
680
 
          perror_plus("read");
681
 
          free(params.data);
682
 
          params.data = NULL;
683
 
          dhparamsfilename = NULL;
684
 
          break;
685
 
        }
686
 
        params.size += (unsigned int)bytes_read;
687
 
      }
688
 
      ret = close(dhpfile);
689
 
      if(ret == -1){
690
 
        perror_plus("close");
691
 
      }
692
 
      if(params.data == NULL){
693
 
        dhparamsfilename = NULL;
694
 
      }
695
 
      if(dhparamsfilename == NULL){
696
 
        break;
697
 
      }
698
 
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
699
 
                                          GNUTLS_X509_FMT_PEM);
700
 
      if(ret != GNUTLS_E_SUCCESS){
701
 
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
702
 
                     " \"%s\": %s\n", dhparamsfilename,
703
 
                     safer_gnutls_strerror(ret));
704
 
        dhparamsfilename = NULL;
705
 
      }
706
 
      free(params.data);
707
 
    } while(false);
708
 
  }
709
 
  if(dhparamsfilename == NULL){
710
 
    if(mc->dh_bits == 0){
711
 
      /* Find out the optimal number of DH bits */
712
 
      /* Try to read the private key file */
713
 
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
714
 
      do {
715
 
        int secfile = open(seckeyfilename, O_RDONLY);
716
 
        if(secfile == -1){
717
 
          perror_plus("open");
718
 
          break;
719
 
        }
720
 
        size_t buffer_capacity = 0;
721
 
        while(true){
722
 
          buffer_capacity = incbuffer((char **)&buffer.data,
723
 
                                      (size_t)buffer.size,
724
 
                                      (size_t)buffer_capacity);
725
 
          if(buffer_capacity == 0){
726
 
            perror_plus("incbuffer");
727
 
            free(buffer.data);
728
 
            buffer.data = NULL;
729
 
            break;
730
 
          }
731
 
          ssize_t bytes_read = read(secfile,
732
 
                                    buffer.data + buffer.size,
733
 
                                    BUFFER_SIZE);
734
 
          /* EOF */
735
 
          if(bytes_read == 0){
736
 
            break;
737
 
          }
738
 
          /* check bytes_read for failure */
739
 
          if(bytes_read < 0){
740
 
            perror_plus("read");
741
 
            free(buffer.data);
742
 
            buffer.data = NULL;
743
 
            break;
744
 
          }
745
 
          buffer.size += (unsigned int)bytes_read;
746
 
        }
747
 
        close(secfile);
748
 
      } while(false);
749
 
      /* If successful, use buffer to parse private key */
750
 
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
751
 
      if(buffer.data != NULL){
752
 
        {
753
 
          gnutls_openpgp_privkey_t privkey = NULL;
754
 
          ret = gnutls_openpgp_privkey_init(&privkey);
755
 
          if(ret != GNUTLS_E_SUCCESS){
756
 
            fprintf_plus(stderr, "Error initializing OpenPGP key"
757
 
                         " structure: %s",
758
 
                         safer_gnutls_strerror(ret));
759
 
            free(buffer.data);
760
 
            buffer.data = NULL;
761
 
          } else {
762
 
            ret = gnutls_openpgp_privkey_import
763
 
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
764
 
            if(ret != GNUTLS_E_SUCCESS){
765
 
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
766
 
                           safer_gnutls_strerror(ret));
767
 
              privkey = NULL;
768
 
            }
769
 
            free(buffer.data);
770
 
            buffer.data = NULL;
771
 
            if(privkey != NULL){
772
 
              /* Use private key to suggest an appropriate
773
 
                 sec_param */
774
 
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
775
 
              gnutls_openpgp_privkey_deinit(privkey);
776
 
              if(debug){
777
 
                fprintf_plus(stderr, "This OpenPGP key implies using"
778
 
                             " a GnuTLS security parameter \"%s\".\n",
779
 
                             safe_string(gnutls_sec_param_get_name
780
 
                                         (sec_param)));
781
 
              }
782
 
            }
783
 
          }
784
 
        }
785
 
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
786
 
          /* Err on the side of caution */
787
 
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
788
 
          if(debug){
789
 
            fprintf_plus(stderr, "Falling back to security parameter"
790
 
                         " \"%s\"\n",
791
 
                         safe_string(gnutls_sec_param_get_name
792
 
                                     (sec_param)));
793
 
          }
794
 
        }
795
 
      }
796
 
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
797
 
      if(uret != 0){
798
 
        mc->dh_bits = uret;
799
 
        if(debug){
800
 
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
801
 
                       " implies %u DH bits; using that.\n",
802
 
                       safe_string(gnutls_sec_param_get_name
803
 
                                   (sec_param)),
804
 
                       mc->dh_bits);
805
 
        }
806
 
      } else {
807
 
        fprintf_plus(stderr, "Failed to get implied number of DH"
808
 
                     " bits for security parameter \"%s\"): %s\n",
809
 
                     safe_string(gnutls_sec_param_get_name
810
 
                                 (sec_param)),
811
 
                     safer_gnutls_strerror(ret));
812
 
        goto globalfail;
813
 
      }
814
 
    } else if(debug){
815
 
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
816
 
                   mc->dh_bits);
817
 
    }
818
 
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
819
 
    if(ret != GNUTLS_E_SUCCESS){
820
 
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
821
 
                   " bits): %s\n", mc->dh_bits,
822
 
                   safer_gnutls_strerror(ret));
823
 
      goto globalfail;
824
 
    }
825
 
  }
 
572
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
573
  if(ret != GNUTLS_E_SUCCESS){
 
574
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
575
                 safer_gnutls_strerror(ret));
 
576
    goto globalfail;
 
577
  }
 
578
  
826
579
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
827
580
  
828
581
  return 0;
830
583
 globalfail:
831
584
  
832
585
  gnutls_certificate_free_credentials(mc->cred);
 
586
  gnutls_global_deinit();
833
587
  gnutls_dh_params_deinit(mc->dh_params);
834
588
  return -1;
835
589
}
887
641
  /* ignore client certificate if any. */
888
642
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
889
643
  
 
644
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
645
  
890
646
  return 0;
891
647
}
892
648
 
896
652
 
897
653
/* Set effective uid to 0, return errno */
898
654
__attribute__((warn_unused_result))
899
 
int raise_privileges(void){
900
 
  int old_errno = errno;
901
 
  int ret = 0;
 
655
error_t raise_privileges(void){
 
656
  error_t old_errno = errno;
 
657
  error_t ret_errno = 0;
902
658
  if(seteuid(0) == -1){
903
 
    ret = errno;
 
659
    ret_errno = errno;
904
660
  }
905
661
  errno = old_errno;
906
 
  return ret;
 
662
  return ret_errno;
907
663
}
908
664
 
909
665
/* Set effective and real user ID to 0.  Return errno. */
910
666
__attribute__((warn_unused_result))
911
 
int raise_privileges_permanently(void){
912
 
  int old_errno = errno;
913
 
  int ret = raise_privileges();
914
 
  if(ret != 0){
 
667
error_t raise_privileges_permanently(void){
 
668
  error_t old_errno = errno;
 
669
  error_t ret_errno = raise_privileges();
 
670
  if(ret_errno != 0){
915
671
    errno = old_errno;
916
 
    return ret;
 
672
    return ret_errno;
917
673
  }
918
674
  if(setuid(0) == -1){
919
 
    ret = errno;
 
675
    ret_errno = errno;
920
676
  }
921
677
  errno = old_errno;
922
 
  return ret;
 
678
  return ret_errno;
923
679
}
924
680
 
925
681
/* Set effective user ID to unprivileged saved user ID */
926
682
__attribute__((warn_unused_result))
927
 
int lower_privileges(void){
928
 
  int old_errno = errno;
929
 
  int ret = 0;
 
683
error_t lower_privileges(void){
 
684
  error_t old_errno = errno;
 
685
  error_t ret_errno = 0;
930
686
  if(seteuid(uid) == -1){
931
 
    ret = errno;
 
687
    ret_errno = errno;
932
688
  }
933
689
  errno = old_errno;
934
 
  return ret;
 
690
  return ret_errno;
935
691
}
936
692
 
937
693
/* Lower privileges permanently */
938
694
__attribute__((warn_unused_result))
939
 
int lower_privileges_permanently(void){
940
 
  int old_errno = errno;
941
 
  int ret = 0;
 
695
error_t lower_privileges_permanently(void){
 
696
  error_t old_errno = errno;
 
697
  error_t ret_errno = 0;
942
698
  if(setuid(uid) == -1){
943
 
    ret = errno;
 
699
    ret_errno = errno;
944
700
  }
945
701
  errno = old_errno;
946
 
  return ret;
 
702
  return ret_errno;
947
703
}
948
704
 
949
705
/* Helper function to add_local_route() and delete_local_route() */
1005
761
      perror_plus("dup2(devnull, STDIN_FILENO)");
1006
762
      _exit(EX_OSERR);
1007
763
    }
1008
 
    ret = close(devnull);
 
764
    ret = (int)TEMP_FAILURE_RETRY(close(devnull));
1009
765
    if(ret == -1){
1010
766
      perror_plus("close");
1011
767
      _exit(EX_OSERR);
1028
784
                                                   helper, O_RDONLY));
1029
785
    if(helper_fd == -1){
1030
786
      perror_plus("openat");
1031
 
      close(helperdir_fd);
1032
787
      _exit(EX_UNAVAILABLE);
1033
788
    }
1034
 
    close(helperdir_fd);
 
789
    TEMP_FAILURE_RETRY(close(helperdir_fd));
1035
790
#ifdef __GNUC__
1036
791
#pragma GCC diagnostic push
1037
792
#pragma GCC diagnostic ignored "-Wcast-qual"
1156
911
    bool match = false;
1157
912
    {
1158
913
      char *interface = NULL;
1159
 
      while((interface = argz_next(mc->interfaces,
1160
 
                                   mc->interfaces_size,
1161
 
                                   interface))){
 
914
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
915
                                 interface))){
1162
916
        if(if_nametoindex(interface) == (unsigned int)if_index){
1163
917
          match = true;
1164
918
          break;
1206
960
    goto mandos_end;
1207
961
  }
1208
962
  
 
963
  memset(&to, 0, sizeof(to));
1209
964
  if(af == AF_INET6){
1210
 
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
1211
 
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
1212
 
    ret = inet_pton(af, ip, &to6->sin6_addr);
 
965
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
966
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
1213
967
  } else {                      /* IPv4 */
1214
 
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
1215
 
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
1216
 
    ret = inet_pton(af, ip, &to4->sin_addr);
 
968
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
969
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
1217
970
  }
1218
971
  if(ret < 0 ){
1219
972
    int e = errno;
1298
1051
                    sizeof(struct sockaddr_in));
1299
1052
    }
1300
1053
    if(ret < 0){
1301
 
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
 
1054
      if(errno == ENETUNREACH
1302
1055
         and if_index != AVAHI_IF_UNSPEC
1303
1056
         and connect_to == NULL
1304
1057
         and not route_added and
1317
1070
           with an explicit route added with the server's address.
1318
1071
           
1319
1072
           Avahi bug reference:
1320
 
           https://lists.freedesktop.org/archives/avahi/2010-February/001833.html
 
1073
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1321
1074
           https://bugs.debian.org/587961
1322
1075
        */
1323
1076
        if(debug){
1503
1256
                                               &decrypted_buffer, mc);
1504
1257
    if(decrypted_buffer_size >= 0){
1505
1258
      
1506
 
      clearerr(stdout);
1507
1259
      written = 0;
1508
1260
      while(written < (size_t) decrypted_buffer_size){
1509
1261
        if(quit_now){
1525
1277
        }
1526
1278
        written += (size_t)ret;
1527
1279
      }
1528
 
      ret = fflush(stdout);
1529
 
      if(ret != 0){
1530
 
        int e = errno;
1531
 
        if(debug){
1532
 
          fprintf_plus(stderr, "Error writing encrypted data: %s\n",
1533
 
                       strerror(errno));
1534
 
        }
1535
 
        errno = e;
1536
 
        goto mandos_end;
1537
 
      }
1538
1280
      retval = 0;
1539
1281
    }
1540
1282
  }
1553
1295
    free(decrypted_buffer);
1554
1296
    free(buffer);
1555
1297
    if(tcp_sd >= 0){
1556
 
      ret = close(tcp_sd);
 
1298
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1557
1299
    }
1558
1300
    if(ret == -1){
1559
1301
      if(e == 0){
1571
1313
  return retval;
1572
1314
}
1573
1315
 
 
1316
__attribute__((nonnull))
1574
1317
static void resolve_callback(AvahiSServiceResolver *r,
1575
1318
                             AvahiIfIndex interface,
1576
1319
                             AvahiProtocol proto,
1713
1456
__attribute__((nonnull, warn_unused_result))
1714
1457
bool get_flags(const char *ifname, struct ifreq *ifr){
1715
1458
  int ret;
1716
 
  int old_errno;
 
1459
  error_t ret_errno;
1717
1460
  
1718
1461
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1719
1462
  if(s < 0){
1720
 
    old_errno = errno;
 
1463
    ret_errno = errno;
1721
1464
    perror_plus("socket");
1722
 
    errno = old_errno;
 
1465
    errno = ret_errno;
1723
1466
    return false;
1724
1467
  }
1725
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1726
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
 
1468
  strcpy(ifr->ifr_name, ifname);
1727
1469
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1728
1470
  if(ret == -1){
1729
1471
    if(debug){
1730
 
      old_errno = errno;
 
1472
      ret_errno = errno;
1731
1473
      perror_plus("ioctl SIOCGIFFLAGS");
1732
 
      errno = old_errno;
1733
 
    }
1734
 
    if((close(s) == -1) and debug){
1735
 
      old_errno = errno;
1736
 
      perror_plus("close");
1737
 
      errno = old_errno;
 
1474
      errno = ret_errno;
1738
1475
    }
1739
1476
    return false;
1740
1477
  }
1741
 
  if((close(s) == -1) and debug){
1742
 
    old_errno = errno;
1743
 
    perror_plus("close");
1744
 
    errno = old_errno;
1745
 
  }
1746
1478
  return true;
1747
1479
}
1748
1480
 
2009
1741
      return;
2010
1742
    }
2011
1743
  }
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
 
  }
 
1744
#ifdef __GLIBC__
 
1745
#if __GLIBC_PREREQ(2, 15)
2017
1746
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
2018
1747
                           runnable_hook, alphasort);
 
1748
#else  /* not __GLIBC_PREREQ(2, 15) */
 
1749
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1750
                         alphasort);
 
1751
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
1752
#else   /* not __GLIBC__ */
 
1753
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1754
                         alphasort);
 
1755
#endif  /* not __GLIBC__ */
2019
1756
  if(numhooks == -1){
2020
1757
    perror_plus("scandir");
2021
 
    close(devnull);
2022
1758
    return;
2023
1759
  }
2024
1760
  struct dirent *direntry;
2025
1761
  int ret;
 
1762
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
 
1763
  if(devnull == -1){
 
1764
    perror_plus("open(\"/dev/null\", O_RDONLY)");
 
1765
    return;
 
1766
  }
2026
1767
  for(int i = 0; i < numhooks; i++){
2027
1768
    direntry = direntries[i];
2028
1769
    if(debug){
2099
1840
        perror_plus("openat");
2100
1841
        _exit(EXIT_FAILURE);
2101
1842
      }
2102
 
      if(close(hookdir_fd) == -1){
 
1843
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2103
1844
        perror_plus("close");
2104
1845
        _exit(EXIT_FAILURE);
2105
1846
      }
2108
1849
        perror_plus("dup2(devnull, STDIN_FILENO)");
2109
1850
        _exit(EX_OSERR);
2110
1851
      }
2111
 
      ret = close(devnull);
 
1852
      ret = (int)TEMP_FAILURE_RETRY(close(devnull));
2112
1853
      if(ret == -1){
2113
1854
        perror_plus("close");
2114
1855
        _exit(EX_OSERR);
2163
1904
    free(direntry);
2164
1905
  }
2165
1906
  free(direntries);
2166
 
  if(close(hookdir_fd) == -1){
 
1907
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
2167
1908
    perror_plus("close");
2168
1909
  } else {
2169
1910
    hookdir_fd = -1;
2172
1913
}
2173
1914
 
2174
1915
__attribute__((nonnull, warn_unused_result))
2175
 
int bring_up_interface(const char *const interface,
2176
 
                       const float delay){
2177
 
  int old_errno = errno;
 
1916
error_t bring_up_interface(const char *const interface,
 
1917
                           const float delay){
 
1918
  error_t old_errno = errno;
2178
1919
  int ret;
2179
1920
  struct ifreq network;
2180
1921
  unsigned int if_index = if_nametoindex(interface);
2190
1931
  }
2191
1932
  
2192
1933
  if(not interface_is_up(interface)){
2193
 
    int ret_errno = 0;
2194
 
    int ioctl_errno = 0;
 
1934
    error_t ret_errno = 0, ioctl_errno = 0;
2195
1935
    if(not get_flags(interface, &network)){
2196
1936
      ret_errno = errno;
2197
1937
      fprintf_plus(stderr, "Failed to get flags for interface "
2210
1950
    }
2211
1951
    
2212
1952
    if(quit_now){
2213
 
      ret = close(sd);
 
1953
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2214
1954
      if(ret == -1){
2215
1955
        perror_plus("close");
2216
1956
      }
2266
2006
    }
2267
2007
    
2268
2008
    /* Close the socket */
2269
 
    ret = close(sd);
 
2009
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
2270
2010
    if(ret == -1){
2271
2011
      perror_plus("close");
2272
2012
    }
2284
2024
  
2285
2025
  /* Sleep checking until interface is running.
2286
2026
     Check every 0.25s, up to total time of delay */
2287
 
  for(int i = 0; i < delay * 4; i++){
 
2027
  for(int i=0; i < delay * 4; i++){
2288
2028
    if(interface_is_running(interface)){
2289
2029
      break;
2290
2030
    }
2300
2040
}
2301
2041
 
2302
2042
__attribute__((nonnull, warn_unused_result))
2303
 
int take_down_interface(const char *const interface){
2304
 
  int old_errno = errno;
 
2043
error_t take_down_interface(const char *const interface){
 
2044
  error_t old_errno = errno;
2305
2045
  struct ifreq network;
2306
2046
  unsigned int if_index = if_nametoindex(interface);
2307
2047
  if(if_index == 0){
2310
2050
    return ENXIO;
2311
2051
  }
2312
2052
  if(interface_is_up(interface)){
2313
 
    int ret_errno = 0;
2314
 
    int ioctl_errno = 0;
 
2053
    error_t ret_errno = 0, ioctl_errno = 0;
2315
2054
    if(not get_flags(interface, &network) and debug){
2316
2055
      ret_errno = errno;
2317
2056
      fprintf_plus(stderr, "Failed to get flags for interface "
2355
2094
    }
2356
2095
    
2357
2096
    /* Close the socket */
2358
 
    int ret = close(sd);
 
2097
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
2359
2098
    if(ret == -1){
2360
2099
      perror_plus("close");
2361
2100
    }
2376
2115
}
2377
2116
 
2378
2117
int main(int argc, char *argv[]){
2379
 
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2380
 
                        .priority = "SECURE256:!CTYPE-X.509"
2381
 
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
2382
 
                        .current_server = NULL, .interfaces = NULL,
2383
 
                        .interfaces_size = 0 };
 
2118
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
2119
                        .priority = "SECURE256:!CTYPE-X.509:"
 
2120
                        "+CTYPE-OPENPGP", .current_server = NULL,
 
2121
                        .interfaces = NULL, .interfaces_size = 0 };
2384
2122
  AvahiSServiceBrowser *sb = NULL;
2385
2123
  error_t ret_errno;
2386
2124
  int ret;
2395
2133
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2396
2134
  const char *seckey = PATHDIR "/" SECKEY;
2397
2135
  const char *pubkey = PATHDIR "/" PUBKEY;
2398
 
  const char *dh_params_file = NULL;
2399
2136
  char *interfaces_hooks = NULL;
2400
2137
  
2401
2138
  bool gnutls_initialized = false;
2454
2191
        .doc = "Bit length of the prime number used in the"
2455
2192
        " Diffie-Hellman key exchange",
2456
2193
        .group = 2 },
2457
 
      { .name = "dh-params", .key = 134,
2458
 
        .arg = "FILE",
2459
 
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
2460
 
        " for the Diffie-Hellman key exchange",
2461
 
        .group = 2 },
2462
2194
      { .name = "priority", .key = 130,
2463
2195
        .arg = "STRING",
2464
2196
        .doc = "GnuTLS priority string for the TLS handshake",
2519
2251
        }
2520
2252
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2521
2253
        break;
2522
 
      case 134:                 /* --dh-params */
2523
 
        dh_params_file = arg;
2524
 
        break;
2525
2254
      case 130:                 /* --priority */
2526
2255
        mc.priority = arg;
2527
2256
        break;
2567
2296
                         .args_doc = "",
2568
2297
                         .doc = "Mandos client -- Get and decrypt"
2569
2298
                         " passwords from a Mandos server" };
2570
 
    ret_errno = argp_parse(&argp, argc, argv,
2571
 
                           ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
2572
 
    switch(ret_errno){
 
2299
    ret = argp_parse(&argp, argc, argv,
 
2300
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
2301
    switch(ret){
2573
2302
    case 0:
2574
2303
      break;
2575
2304
    case ENOMEM:
2576
2305
    default:
2577
 
      errno = ret_errno;
 
2306
      errno = ret;
2578
2307
      perror_plus("argp_parse");
2579
2308
      exitcode = EX_OSERR;
2580
2309
      goto end;
2586
2315
  
2587
2316
  {
2588
2317
    /* Work around Debian bug #633582:
2589
 
       <https://bugs.debian.org/633582> */
 
2318
       <http://bugs.debian.org/633582> */
2590
2319
    
2591
2320
    /* Re-raise privileges */
2592
 
    ret = raise_privileges();
2593
 
    if(ret != 0){
2594
 
      errno = ret;
 
2321
    ret_errno = raise_privileges();
 
2322
    if(ret_errno != 0){
 
2323
      errno = ret_errno;
2595
2324
      perror_plus("Failed to raise privileges");
2596
2325
    } else {
2597
2326
      struct stat st;
2613
2342
              }
2614
2343
            }
2615
2344
          }
2616
 
          close(seckey_fd);
 
2345
          TEMP_FAILURE_RETRY(close(seckey_fd));
2617
2346
        }
2618
2347
      }
2619
2348
      
2634
2363
              }
2635
2364
            }
2636
2365
          }
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);
 
2366
          TEMP_FAILURE_RETRY(close(pubkey_fd));
2660
2367
        }
2661
2368
      }
2662
2369
      
2663
2370
      /* Lower privileges */
2664
 
      ret = lower_privileges();
2665
 
      if(ret != 0){
2666
 
        errno = ret;
 
2371
      ret_errno = lower_privileges();
 
2372
      if(ret_errno != 0){
 
2373
        errno = ret_errno;
2667
2374
        perror_plus("Failed to lower privileges");
2668
2375
      }
2669
2376
    }
2839
2546
      errno = bring_up_interface(interface, delay);
2840
2547
      if(not interface_was_up){
2841
2548
        if(errno != 0){
2842
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2843
 
                       " %s\n", interface, strerror(errno));
 
2549
          perror_plus("Failed to bring up interface");
2844
2550
        } else {
2845
2551
          errno = argz_add(&interfaces_to_take_down,
2846
2552
                           &interfaces_to_take_down_size,
2869
2575
    goto end;
2870
2576
  }
2871
2577
  
2872
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
2578
  ret = init_gnutls_global(pubkey, seckey, &mc);
2873
2579
  if(ret == -1){
2874
2580
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2875
2581
    exitcode = EX_UNAVAILABLE;
2997
2703
    
2998
2704
    /* Allocate a new server */
2999
2705
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
3000
 
                                 &config, NULL, NULL, &ret);
 
2706
                                 &config, NULL, NULL, &ret_errno);
3001
2707
    
3002
2708
    /* Free the Avahi configuration data */
3003
2709
    avahi_server_config_free(&config);
3006
2712
  /* Check if creating the Avahi server object succeeded */
3007
2713
  if(mc.server == NULL){
3008
2714
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
3009
 
                 avahi_strerror(ret));
 
2715
                 avahi_strerror(ret_errno));
3010
2716
    exitcode = EX_UNAVAILABLE;
3011
2717
    goto end;
3012
2718
  }
3047
2753
 end:
3048
2754
  
3049
2755
  if(debug){
3050
 
    if(signal_received){
3051
 
      fprintf_plus(stderr, "%s exiting due to signal %d: %s\n",
3052
 
                   argv[0], signal_received,
3053
 
                   strsignal(signal_received));
3054
 
    } else {
3055
 
      fprintf_plus(stderr, "%s exiting\n", argv[0]);
3056
 
    }
 
2756
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
3057
2757
  }
3058
2758
  
3059
2759
  /* Cleanup things */
3070
2770
  
3071
2771
  if(gnutls_initialized){
3072
2772
    gnutls_certificate_free_credentials(mc.cred);
 
2773
    gnutls_global_deinit();
3073
2774
    gnutls_dh_params_deinit(mc.dh_params);
3074
2775
  }
3075
2776
  
3098
2799
  
3099
2800
  /* Re-raise privileges */
3100
2801
  {
3101
 
    ret = raise_privileges();
3102
 
    if(ret != 0){
3103
 
      errno = ret;
 
2802
    ret_errno = raise_privileges();
 
2803
    if(ret_errno != 0){
 
2804
      errno = ret_errno;
3104
2805
      perror_plus("Failed to raise privileges");
3105
2806
    } else {
3106
2807
      
3111
2812
      /* Take down the network interfaces which were brought up */
3112
2813
      {
3113
2814
        char *interface = NULL;
3114
 
        while((interface = argz_next(interfaces_to_take_down,
3115
 
                                     interfaces_to_take_down_size,
3116
 
                                     interface))){
3117
 
          ret = take_down_interface(interface);
3118
 
          if(ret != 0){
3119
 
            errno = ret;
 
2815
        while((interface=argz_next(interfaces_to_take_down,
 
2816
                                   interfaces_to_take_down_size,
 
2817
                                   interface))){
 
2818
          ret_errno = take_down_interface(interface);
 
2819
          if(ret_errno != 0){
 
2820
            errno = ret_errno;
3120
2821
            perror_plus("Failed to take down interface");
3121
2822
          }
3122
2823
        }
3127
2828
      }
3128
2829
    }
3129
2830
    
3130
 
    ret = lower_privileges_permanently();
3131
 
    if(ret != 0){
3132
 
      errno = ret;
 
2831
    ret_errno = lower_privileges_permanently();
 
2832
    if(ret_errno != 0){
 
2833
      errno = ret_errno;
3133
2834
      perror_plus("Failed to lower privileges permanently");
3134
2835
    }
3135
2836
  }
3137
2838
  free(interfaces_to_take_down);
3138
2839
  free(interfaces_hooks);
3139
2840
  
3140
 
  void clean_dir_at(int base, const char * const dirname,
3141
 
                    uintmax_t level){
3142
 
    struct dirent **direntries = NULL;
3143
 
    int dret;
3144
 
    int dir_fd = (int)TEMP_FAILURE_RETRY(openat(base, dirname,
3145
 
                                                O_RDONLY
3146
 
                                                | O_NOFOLLOW
3147
 
                                                | O_DIRECTORY
3148
 
                                                | O_PATH));
3149
 
    if(dir_fd == -1){
3150
 
      perror_plus("open");
3151
 
      return;
3152
 
    }
3153
 
    int numentries = scandirat(dir_fd, ".", &direntries,
3154
 
                               notdotentries, alphasort);
3155
 
    if(numentries >= 0){
3156
 
      for(int i = 0; i < numentries; i++){
3157
 
        if(debug){
3158
 
          fprintf_plus(stderr, "Unlinking \"%s/%s\"\n",
3159
 
                       dirname, direntries[i]->d_name);
3160
 
        }
3161
 
        dret = unlinkat(dir_fd, direntries[i]->d_name, 0);
3162
 
        if(dret == -1){
3163
 
          if(errno == EISDIR){
3164
 
              dret = unlinkat(dir_fd, direntries[i]->d_name,
3165
 
                              AT_REMOVEDIR);
3166
 
          }         
3167
 
          if((dret == -1) and (errno == ENOTEMPTY)
3168
 
             and (strcmp(direntries[i]->d_name, "private-keys-v1.d")
3169
 
                  == 0) and (level == 0)){
3170
 
            /* Recurse only in this special case */
3171
 
            clean_dir_at(dir_fd, direntries[i]->d_name, level+1);
3172
 
            dret = 0;
3173
 
          }
3174
 
          if((dret == -1) and (errno != ENOENT)){
3175
 
            fprintf_plus(stderr, "unlink(\"%s/%s\"): %s\n", dirname,
3176
 
                         direntries[i]->d_name, strerror(errno));
3177
 
          }
3178
 
        }
3179
 
        free(direntries[i]);
3180
 
      }
3181
 
      
3182
 
      /* need to clean even if 0 because man page doesn't specify */
3183
 
      free(direntries);
3184
 
      dret = unlinkat(base, dirname, AT_REMOVEDIR);
3185
 
      if(dret == -1 and errno != ENOENT){
3186
 
        perror_plus("rmdir");
3187
 
      }
3188
 
    } else {
3189
 
      perror_plus("scandirat");
3190
 
    }
3191
 
    close(dir_fd);
3192
 
  }
3193
 
  
3194
2841
  /* Removes the GPGME temp directory and all files inside */
3195
2842
  if(tempdir != NULL){
3196
 
    clean_dir_at(-1, tempdir, 0);
 
2843
    struct dirent **direntries = NULL;
 
2844
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
 
2845
                                                  | O_NOFOLLOW
 
2846
                                                  | O_DIRECTORY
 
2847
                                                  | O_PATH));
 
2848
    if(tempdir_fd == -1){
 
2849
      perror_plus("open");
 
2850
    } else {
 
2851
#ifdef __GLIBC__
 
2852
#if __GLIBC_PREREQ(2, 15)
 
2853
      int numentries = scandirat(tempdir_fd, ".", &direntries,
 
2854
                                 notdotentries, alphasort);
 
2855
#else  /* not __GLIBC_PREREQ(2, 15) */
 
2856
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2857
                               alphasort);
 
2858
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
2859
#else   /* not __GLIBC__ */
 
2860
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2861
                               alphasort);
 
2862
#endif  /* not __GLIBC__ */
 
2863
      if(numentries >= 0){
 
2864
        for(int i = 0; i < numentries; i++){
 
2865
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
 
2866
          if(ret == -1){
 
2867
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
 
2868
                         " \"%s\", 0): %s\n", tempdir,
 
2869
                         direntries[i]->d_name, strerror(errno));
 
2870
          }
 
2871
          free(direntries[i]);
 
2872
        }
 
2873
        
 
2874
        /* need to clean even if 0 because man page doesn't specify */
 
2875
        free(direntries);
 
2876
        if(numentries == -1){
 
2877
          perror_plus("scandir");
 
2878
        }
 
2879
        ret = rmdir(tempdir);
 
2880
        if(ret == -1 and errno != ENOENT){
 
2881
          perror_plus("rmdir");
 
2882
        }
 
2883
      }
 
2884
      TEMP_FAILURE_RETRY(close(tempdir_fd));
 
2885
    }
3197
2886
  }
3198
2887
  
3199
2888
  if(quit_now){