/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2014-03-06 02:26:04 UTC
  • Revision ID: teddy@recompile.se-20140306022604-4uc43taz25cflgi3
Bug fix: Free all memory and give better messages when memory is full.

* plugin-runner.c (add_to_char_array): Bug fix: If realloc fails, do
                                       not change old array pointer.
  (add_environment): Bug fix: If realloc fails, do not change old
                     environment pointer.  Also rename "e" to "envdef"
                     for clarity.
  (main): Bug fix: If realloc fails, do not change old pointers.  Also
          wrap "#pragma GCC" with "#ifdef ___GNUC___".
* plugins.d/mandos-client.c (incbuffer): Bug fix: if realloc fails,
                                         free old buffer.
  (run_network_hooks): Moved variables "directory" and "ret" to their
                       innermost possible scope.
  (take_down_interface): Moved variables "sd", "ret_errno", and
                         "ret_setflags" to their innermost possible
                         scope.
  (main): Removed variable "interfaces_hooks_size".  Also, if argz_add
          fails when adding all found interfaces, the error message
          will now be correct.  Also print error message if, after
          having taken up an interface, argz_add fails to add
          interface to list of interfaces to be taken down.
* plugins.d/mandos-client.xml (OPTIONS): Explain better what "none"
                                         means as argument to
                                         "--interface" by negating
                                         sense.
* plugins.d/password-prompt.c (fprintf_plus): Removed (unused).

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-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
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
 */
33
32
/* Needed by GPGME, specifically gpgme_data_seek() */
34
33
#ifndef _LARGEFILE_SOURCE
35
34
#define _LARGEFILE_SOURCE
36
 
#endif  /* not _LARGEFILE_SOURCE */
 
35
#endif
37
36
#ifndef _FILE_OFFSET_BITS
38
37
#define _FILE_OFFSET_BITS 64
39
 
#endif  /* not _FILE_OFFSET_BITS */
 
38
#endif
40
39
 
41
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
42
41
 
43
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
44
 
                                   stdout, ferror() */
 
43
                                   stdout, ferror(), remove() */
45
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
46
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
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,
57
55
                                   opendir(), DIR */
58
56
#include <sys/stat.h>           /* open(), S_ISREG */
59
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
60
 
                                   inet_pton(), connect(),
61
 
                                   getnameinfo() */
62
 
#include <fcntl.h>              /* open(), unlinkat(), AT_REMOVEDIR */
 
58
                                   inet_pton(), connect() */
 
59
#include <fcntl.h>              /* open() */
63
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
64
61
                                 */
65
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
66
63
                                   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,
 
64
#include <errno.h>              /* perror(), errno,
72
65
                                   program_invocation_short_name */
73
66
#include <time.h>               /* nanosleep(), time(), sleep() */
74
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
79
72
                                */
80
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
81
74
                                   getuid(), getgid(), seteuid(),
82
 
                                   setgid(), pause(), _exit(),
83
 
                                   unlinkat() */
84
 
#include <arpa/inet.h>          /* inet_pton(), htons() */
 
75
                                   setgid(), pause(), _exit() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
85
77
#include <iso646.h>             /* not, or, and */
86
78
#include <argp.h>               /* struct argp_option, error_t, struct
87
79
                                   argp_state, struct argp,
99
91
                                   argz_delete(), argz_append(),
100
92
                                   argz_stringify(), argz_add(),
101
93
                                   argz_count() */
102
 
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
103
 
                                   EAI_SYSTEM, gai_strerror() */
104
94
 
105
95
#ifdef __linux__
106
96
#include <sys/klog.h>           /* klogctl() */
148
138
static const char sys_class_net[] = "/sys/class/net";
149
139
char *connect_to = NULL;
150
140
const char *hookdir = HOOKDIR;
151
 
int hookdir_fd = -1;
152
141
uid_t uid = 65534;
153
142
gid_t gid = 65534;
154
143
 
191
180
  perror(print_text);
192
181
}
193
182
 
194
 
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
183
__attribute__((format (gnu_printf, 2, 3)))
195
184
int fprintf_plus(FILE *stream, const char *format, ...){
196
185
  va_list ap;
197
186
  va_start (ap, format);
206
195
 * bytes. "buffer_capacity" is how much is currently allocated,
207
196
 * "buffer_length" is how much is already used.
208
197
 */
209
 
__attribute__((nonnull, warn_unused_result))
210
198
size_t incbuffer(char **buffer, size_t buffer_length,
211
199
                 size_t buffer_capacity){
212
200
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
225
213
}
226
214
 
227
215
/* Add server to set of servers to retry periodically */
228
 
__attribute__((nonnull, warn_unused_result))
229
216
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
230
217
                int af, server **current_server){
231
218
  int ret;
240
227
                          .af = af };
241
228
  if(new_server->ip == NULL){
242
229
    perror_plus("strdup");
243
 
    free(new_server);
244
 
    return false;
245
 
  }
246
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
247
 
  if(ret == -1){
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);
258
230
    return false;
259
231
  }
260
232
  /* Special case of first server */
262
234
    new_server->next = new_server;
263
235
    new_server->prev = new_server;
264
236
    *current_server = new_server;
 
237
  /* Place the new server last in the list */
265
238
  } else {
266
 
    /* Place the new server last in the list */
267
239
    new_server->next = *current_server;
268
240
    new_server->prev = (*current_server)->prev;
269
241
    new_server->prev->next = new_server;
270
242
    (*current_server)->prev = new_server;
271
243
  }
 
244
  ret = clock_gettime(CLOCK_MONOTONIC, &(*current_server)->last_seen);
 
245
  if(ret == -1){
 
246
    perror_plus("clock_gettime");
 
247
    return false;
 
248
  }
272
249
  return true;
273
250
}
274
251
 
275
252
/* 
276
253
 * Initialize GPGME.
277
254
 */
278
 
__attribute__((nonnull, warn_unused_result))
279
 
static bool init_gpgme(const char * const seckey,
280
 
                       const char * const pubkey,
281
 
                       const char * const tempdir,
282
 
                       mandos_context *mc){
 
255
static bool init_gpgme(const char *seckey, const char *pubkey,
 
256
                       const char *tempdir, mandos_context *mc){
283
257
  gpgme_error_t rc;
284
258
  gpgme_engine_info_t engine_info;
285
259
  
286
260
  /*
287
261
   * Helper function to insert pub and seckey to the engine keyring.
288
262
   */
289
 
  bool import_key(const char * const filename){
 
263
  bool import_key(const char *filename){
290
264
    int ret;
291
265
    int fd;
292
266
    gpgme_data_t pgp_data;
310
284
                   gpgme_strsource(rc), gpgme_strerror(rc));
311
285
      return false;
312
286
    }
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
287
    
389
 
    ret = close(fd);
 
288
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
390
289
    if(ret == -1){
391
290
      perror_plus("close");
392
291
    }
431
330
  /* Create new GPGME "context" */
432
331
  rc = gpgme_new(&(mc->ctx));
433
332
  if(rc != GPG_ERR_NO_ERROR){
434
 
    fprintf_plus(stderr, "bad gpgme_new: %s: %s\n",
435
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
333
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
334
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
335
                 gpgme_strerror(rc));
436
336
    return false;
437
337
  }
438
338
  
447
347
 * Decrypt OpenPGP data.
448
348
 * Returns -1 on error
449
349
 */
450
 
__attribute__((nonnull, warn_unused_result))
451
350
static ssize_t pgp_packet_decrypt(const char *cryptotext,
452
351
                                  size_t crypto_size,
453
352
                                  char **plaintext,
474
373
  /* Create new empty GPGME data buffer for the plaintext */
475
374
  rc = gpgme_data_new(&dh_plain);
476
375
  if(rc != GPG_ERR_NO_ERROR){
477
 
    fprintf_plus(stderr, "bad gpgme_data_new: %s: %s\n",
 
376
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
377
                 "bad gpgme_data_new: %s: %s\n",
478
378
                 gpgme_strsource(rc), gpgme_strerror(rc));
479
379
    gpgme_data_release(dh_crypto);
480
380
    return -1;
493
393
      if(result == NULL){
494
394
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
495
395
      } 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");
 
396
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
397
                     result->unsupported_algorithm);
 
398
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
399
                     result->wrong_key_usage);
502
400
        if(result->file_name != NULL){
503
401
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
504
402
        }
505
 
 
506
 
        for(gpgme_recipient_t r = result->recipients; r != NULL;
507
 
            r = r->next){
 
403
        gpgme_recipient_t recipient;
 
404
        recipient = result->recipients;
 
405
        while(recipient != NULL){
508
406
          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);
 
407
                       gpgme_pubkey_algo_name
 
408
                       (recipient->pubkey_algo));
 
409
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
511
410
          fprintf_plus(stderr, "Secret key available: %s\n",
512
 
                       r->status == GPG_ERR_NO_SECKEY ? "No" : "Yes");
 
411
                       recipient->status == GPG_ERR_NO_SECKEY
 
412
                       ? "No" : "Yes");
 
413
          recipient = recipient->next;
513
414
        }
514
415
      }
515
416
    }
571
472
  return plaintext_length;
572
473
}
573
474
 
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
 
__attribute__((warn_unused_result))
582
 
static const char *safer_gnutls_strerror(int value){
 
475
static const char * safer_gnutls_strerror(int value){
583
476
  const char *ret = gnutls_strerror(value);
584
 
  return safe_string(ret);
 
477
  if(ret == NULL)
 
478
    ret = "(unknown)";
 
479
  return ret;
585
480
}
586
481
 
587
482
/* GnuTLS log function callback */
588
 
__attribute__((nonnull))
589
483
static void debuggnutls(__attribute__((unused)) int level,
590
484
                        const char* string){
591
485
  fprintf_plus(stderr, "GnuTLS: %s", string);
592
486
}
593
487
 
594
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
595
488
static int init_gnutls_global(const char *pubkeyfilename,
596
489
                              const char *seckeyfilename,
597
 
                              const char *dhparamsfilename,
598
490
                              mandos_context *mc){
599
491
  int ret;
600
 
  unsigned int uret;
601
492
  
602
493
  if(debug){
603
494
    fprintf_plus(stderr, "Initializing GnuTLS\n");
604
495
  }
605
496
  
 
497
  ret = gnutls_global_init();
 
498
  if(ret != GNUTLS_E_SUCCESS){
 
499
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
500
                 safer_gnutls_strerror(ret));
 
501
    return -1;
 
502
  }
 
503
  
606
504
  if(debug){
607
505
    /* "Use a log level over 10 to enable all debugging options."
608
506
     * - GnuTLS manual
616
514
  if(ret != GNUTLS_E_SUCCESS){
617
515
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
618
516
                 safer_gnutls_strerror(ret));
 
517
    gnutls_global_deinit();
619
518
    return -1;
620
519
  }
621
520
  
646
545
                 safer_gnutls_strerror(ret));
647
546
    goto globalfail;
648
547
  }
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
 
  }
 
548
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
549
  if(ret != GNUTLS_E_SUCCESS){
 
550
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
551
                 safer_gnutls_strerror(ret));
 
552
    goto globalfail;
 
553
  }
 
554
  
826
555
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
827
556
  
828
557
  return 0;
830
559
 globalfail:
831
560
  
832
561
  gnutls_certificate_free_credentials(mc->cred);
 
562
  gnutls_global_deinit();
833
563
  gnutls_dh_params_deinit(mc->dh_params);
834
564
  return -1;
835
565
}
836
566
 
837
 
__attribute__((nonnull, warn_unused_result))
838
567
static int init_gnutls_session(gnutls_session_t *session,
839
568
                               mandos_context *mc){
840
569
  int ret;
887
616
  /* ignore client certificate if any. */
888
617
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
889
618
  
 
619
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
620
  
890
621
  return 0;
891
622
}
892
623
 
894
625
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
895
626
                      __attribute__((unused)) const char *txt){}
896
627
 
897
 
/* Set effective uid to 0, return errno */
898
 
__attribute__((warn_unused_result))
899
 
int raise_privileges(void){
900
 
  int old_errno = errno;
901
 
  int ret = 0;
902
 
  if(seteuid(0) == -1){
903
 
    ret = errno;
904
 
  }
905
 
  errno = old_errno;
906
 
  return ret;
907
 
}
908
 
 
909
 
/* Set effective and real user ID to 0.  Return errno. */
910
 
__attribute__((warn_unused_result))
911
 
int raise_privileges_permanently(void){
912
 
  int old_errno = errno;
913
 
  int ret = raise_privileges();
914
 
  if(ret != 0){
915
 
    errno = old_errno;
916
 
    return ret;
917
 
  }
918
 
  if(setuid(0) == -1){
919
 
    ret = errno;
920
 
  }
921
 
  errno = old_errno;
922
 
  return ret;
923
 
}
924
 
 
925
 
/* Set effective user ID to unprivileged saved user ID */
926
 
__attribute__((warn_unused_result))
927
 
int lower_privileges(void){
928
 
  int old_errno = errno;
929
 
  int ret = 0;
930
 
  if(seteuid(uid) == -1){
931
 
    ret = errno;
932
 
  }
933
 
  errno = old_errno;
934
 
  return ret;
935
 
}
936
 
 
937
 
/* Lower privileges permanently */
938
 
__attribute__((warn_unused_result))
939
 
int lower_privileges_permanently(void){
940
 
  int old_errno = errno;
941
 
  int ret = 0;
942
 
  if(setuid(uid) == -1){
943
 
    ret = errno;
944
 
  }
945
 
  errno = old_errno;
946
 
  return ret;
947
 
}
948
 
 
949
 
/* Helper function to add_local_route() and delete_local_route() */
950
 
__attribute__((nonnull, warn_unused_result))
951
 
static bool add_delete_local_route(const bool add,
952
 
                                   const char *address,
953
 
                                   AvahiIfIndex if_index){
954
 
  int ret;
955
 
  char helper[] = "mandos-client-iprouteadddel";
956
 
  char add_arg[] = "add";
957
 
  char delete_arg[] = "delete";
958
 
  char debug_flag[] = "--debug";
959
 
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
960
 
  if(pluginhelperdir == NULL){
961
 
    if(debug){
962
 
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
963
 
                   " variable not set; cannot run helper\n");
964
 
    }
965
 
    return false;
966
 
  }
967
 
  
968
 
  char interface[IF_NAMESIZE];
969
 
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
970
 
    perror_plus("if_indextoname");
971
 
    return false;
972
 
  }
973
 
  
974
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
975
 
  if(devnull == -1){
976
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
977
 
    return false;
978
 
  }
979
 
  pid_t pid = fork();
980
 
  if(pid == 0){
981
 
    /* Child */
982
 
    /* Raise privileges */
983
 
    errno = raise_privileges_permanently();
984
 
    if(errno != 0){
985
 
      perror_plus("Failed to raise privileges");
986
 
      /* _exit(EX_NOPERM); */
987
 
    } else {
988
 
      /* Set group */
989
 
      errno = 0;
990
 
      ret = setgid(0);
991
 
      if(ret == -1){
992
 
        perror_plus("setgid");
993
 
        _exit(EX_NOPERM);
994
 
      }
995
 
      /* Reset supplementary groups */
996
 
      errno = 0;
997
 
      ret = setgroups(0, NULL);
998
 
      if(ret == -1){
999
 
        perror_plus("setgroups");
1000
 
        _exit(EX_NOPERM);
1001
 
      }
1002
 
    }
1003
 
    ret = dup2(devnull, STDIN_FILENO);
1004
 
    if(ret == -1){
1005
 
      perror_plus("dup2(devnull, STDIN_FILENO)");
1006
 
      _exit(EX_OSERR);
1007
 
    }
1008
 
    ret = close(devnull);
1009
 
    if(ret == -1){
1010
 
      perror_plus("close");
1011
 
      _exit(EX_OSERR);
1012
 
    }
1013
 
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1014
 
    if(ret == -1){
1015
 
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1016
 
      _exit(EX_OSERR);
1017
 
    }
1018
 
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
1019
 
                                                    O_RDONLY
1020
 
                                                    | O_DIRECTORY
1021
 
                                                    | O_PATH
1022
 
                                                    | O_CLOEXEC));
1023
 
    if(helperdir_fd == -1){
1024
 
      perror_plus("open");
1025
 
      _exit(EX_UNAVAILABLE);
1026
 
    }
1027
 
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
1028
 
                                                   helper, O_RDONLY));
1029
 
    if(helper_fd == -1){
1030
 
      perror_plus("openat");
1031
 
      close(helperdir_fd);
1032
 
      _exit(EX_UNAVAILABLE);
1033
 
    }
1034
 
    close(helperdir_fd);
1035
 
#ifdef __GNUC__
1036
 
#pragma GCC diagnostic push
1037
 
#pragma GCC diagnostic ignored "-Wcast-qual"
1038
 
#endif
1039
 
    if(fexecve(helper_fd, (char *const [])
1040
 
               { helper, add ? add_arg : delete_arg, (char *)address,
1041
 
                   interface, debug ? debug_flag : NULL, NULL },
1042
 
               environ) == -1){
1043
 
#ifdef __GNUC__
1044
 
#pragma GCC diagnostic pop
1045
 
#endif
1046
 
      perror_plus("fexecve");
1047
 
      _exit(EXIT_FAILURE);
1048
 
    }
1049
 
  }
1050
 
  if(pid == -1){
1051
 
    perror_plus("fork");
1052
 
    return false;
1053
 
  }
1054
 
  int status;
1055
 
  pid_t pret = -1;
1056
 
  errno = 0;
1057
 
  do {
1058
 
    pret = waitpid(pid, &status, 0);
1059
 
    if(pret == -1 and errno == EINTR and quit_now){
1060
 
      int errno_raising = 0;
1061
 
      if((errno = raise_privileges()) != 0){
1062
 
        errno_raising = errno;
1063
 
        perror_plus("Failed to raise privileges in order to"
1064
 
                    " kill helper program");
1065
 
      }
1066
 
      if(kill(pid, SIGTERM) == -1){
1067
 
        perror_plus("kill");
1068
 
      }
1069
 
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
1070
 
        perror_plus("Failed to lower privileges after killing"
1071
 
                    " helper program");
1072
 
      }
1073
 
      return false;
1074
 
    }
1075
 
  } while(pret == -1 and errno == EINTR);
1076
 
  if(pret == -1){
1077
 
    perror_plus("waitpid");
1078
 
    return false;
1079
 
  }
1080
 
  if(WIFEXITED(status)){
1081
 
    if(WEXITSTATUS(status) != 0){
1082
 
      fprintf_plus(stderr, "Error: iprouteadddel exited"
1083
 
                   " with status %d\n", WEXITSTATUS(status));
1084
 
      return false;
1085
 
    }
1086
 
    return true;
1087
 
  }
1088
 
  if(WIFSIGNALED(status)){
1089
 
    fprintf_plus(stderr, "Error: iprouteadddel died by"
1090
 
                 " signal %d\n", WTERMSIG(status));
1091
 
    return false;
1092
 
  }
1093
 
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
1094
 
  return false;
1095
 
}
1096
 
 
1097
 
__attribute__((nonnull, warn_unused_result))
1098
 
static bool add_local_route(const char *address,
1099
 
                            AvahiIfIndex if_index){
1100
 
  if(debug){
1101
 
    fprintf_plus(stderr, "Adding route to %s\n", address);
1102
 
  }
1103
 
  return add_delete_local_route(true, address, if_index);
1104
 
}
1105
 
 
1106
 
__attribute__((nonnull, warn_unused_result))
1107
 
static bool delete_local_route(const char *address,
1108
 
                               AvahiIfIndex if_index){
1109
 
  if(debug){
1110
 
    fprintf_plus(stderr, "Removing route to %s\n", address);
1111
 
  }
1112
 
  return add_delete_local_route(false, address, if_index);
1113
 
}
1114
 
 
1115
628
/* Called when a Mandos server is found */
1116
 
__attribute__((nonnull, warn_unused_result))
1117
629
static int start_mandos_communication(const char *ip, in_port_t port,
1118
630
                                      AvahiIfIndex if_index,
1119
631
                                      int af, mandos_context *mc){
1120
632
  int ret, tcp_sd = -1;
1121
633
  ssize_t sret;
1122
 
  struct sockaddr_storage to;
 
634
  union {
 
635
    struct sockaddr_in in;
 
636
    struct sockaddr_in6 in6;
 
637
  } to;
1123
638
  char *buffer = NULL;
1124
639
  char *decrypted_buffer = NULL;
1125
640
  size_t buffer_length = 0;
1128
643
  int retval = -1;
1129
644
  gnutls_session_t session;
1130
645
  int pf;                       /* Protocol family */
1131
 
  bool route_added = false;
1132
646
  
1133
647
  errno = 0;
1134
648
  
1156
670
    bool match = false;
1157
671
    {
1158
672
      char *interface = NULL;
1159
 
      while((interface = argz_next(mc->interfaces,
1160
 
                                   mc->interfaces_size,
1161
 
                                   interface))){
 
673
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
674
                                 interface))){
1162
675
        if(if_nametoindex(interface) == (unsigned int)if_index){
1163
676
          match = true;
1164
677
          break;
1193
706
                 PRIuMAX "\n", ip, (uintmax_t)port);
1194
707
  }
1195
708
  
1196
 
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
 
709
  tcp_sd = socket(pf, SOCK_STREAM, 0);
1197
710
  if(tcp_sd < 0){
1198
711
    int e = errno;
1199
712
    perror_plus("socket");
1206
719
    goto mandos_end;
1207
720
  }
1208
721
  
 
722
  memset(&to, 0, sizeof(to));
1209
723
  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);
 
724
    to.in6.sin6_family = (sa_family_t)af;
 
725
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
1213
726
  } 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);
 
727
    to.in.sin_family = (sa_family_t)af;
 
728
    ret = inet_pton(af, ip, &to.in.sin_addr);
1217
729
  }
1218
730
  if(ret < 0 ){
1219
731
    int e = errno;
1228
740
    goto mandos_end;
1229
741
  }
1230
742
  if(af == AF_INET6){
1231
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
1232
 
    if(IN6_IS_ADDR_LINKLOCAL
1233
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
743
    to.in6.sin6_port = htons(port);    
 
744
#ifdef __GNUC__
 
745
#pragma GCC diagnostic push
 
746
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
 
747
#endif
 
748
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
749
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower */
 
750
#ifdef __GNUC__
 
751
#pragma GCC diagnostic pop
 
752
#endif
1234
753
      if(if_index == AVAHI_IF_UNSPEC){
1235
754
        fprintf_plus(stderr, "An IPv6 link-local address is"
1236
755
                     " incomplete without a network interface\n");
1238
757
        goto mandos_end;
1239
758
      }
1240
759
      /* Set the network interface number as scope */
1241
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
760
      to.in6.sin6_scope_id = (uint32_t)if_index;
1242
761
    }
1243
762
  } else {
1244
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
763
    to.in.sin_port = htons(port);
1245
764
  }
1246
765
  
1247
766
  if(quit_now){
1264
783
    }
1265
784
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
1266
785
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
1267
 
    if(af == AF_INET6){
1268
 
      ret = getnameinfo((struct sockaddr *)&to,
1269
 
                        sizeof(struct sockaddr_in6),
1270
 
                        addrstr, sizeof(addrstr), NULL, 0,
1271
 
                        NI_NUMERICHOST);
1272
 
    } else {
1273
 
      ret = getnameinfo((struct sockaddr *)&to,
1274
 
                        sizeof(struct sockaddr_in),
1275
 
                        addrstr, sizeof(addrstr), NULL, 0,
1276
 
                        NI_NUMERICHOST);
1277
 
    }
1278
 
    if(ret == EAI_SYSTEM){
1279
 
      perror_plus("getnameinfo");
1280
 
    } else if(ret != 0) {
1281
 
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
1282
 
    } else if(strcmp(addrstr, ip) != 0){
1283
 
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
1284
 
    }
1285
 
  }
1286
 
  
1287
 
  if(quit_now){
1288
 
    errno = EINTR;
1289
 
    goto mandos_end;
1290
 
  }
1291
 
  
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;
 
786
    const char *pcret;
 
787
    if(af == AF_INET6){
 
788
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
789
                        sizeof(addrstr));
 
790
    } else {
 
791
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
792
                        sizeof(addrstr));
 
793
    }
 
794
    if(pcret == NULL){
 
795
      perror_plus("inet_ntop");
 
796
    } else {
 
797
      if(strcmp(addrstr, ip) != 0){
 
798
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
799
      }
 
800
    }
 
801
  }
 
802
  
 
803
  if(quit_now){
 
804
    errno = EINTR;
 
805
    goto mandos_end;
 
806
  }
 
807
  
 
808
  if(af == AF_INET6){
 
809
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
810
  } else {
 
811
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
812
  }
 
813
  if(ret < 0){
 
814
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
815
      int e = errno;
 
816
      perror_plus("connect");
 
817
      errno = e;
 
818
    }
 
819
    goto mandos_end;
 
820
  }
 
821
  
 
822
  if(quit_now){
 
823
    errno = EINTR;
 
824
    goto mandos_end;
1347
825
  }
1348
826
  
1349
827
  const char *out = mandos_protocol_version;
1503
981
                                               &decrypted_buffer, mc);
1504
982
    if(decrypted_buffer_size >= 0){
1505
983
      
1506
 
      clearerr(stdout);
1507
984
      written = 0;
1508
985
      while(written < (size_t) decrypted_buffer_size){
1509
986
        if(quit_now){
1525
1002
        }
1526
1003
        written += (size_t)ret;
1527
1004
      }
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
1005
      retval = 0;
1539
1006
    }
1540
1007
  }
1543
1010
  
1544
1011
 mandos_end:
1545
1012
  {
1546
 
    if(route_added){
1547
 
      if(not delete_local_route(ip, if_index)){
1548
 
        fprintf_plus(stderr, "Failed to delete local route to %s on"
1549
 
                     " interface %d", ip, if_index);
1550
 
      }
1551
 
    }
1552
1013
    int e = errno;
1553
1014
    free(decrypted_buffer);
1554
1015
    free(buffer);
1555
1016
    if(tcp_sd >= 0){
1556
 
      ret = close(tcp_sd);
 
1017
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1557
1018
    }
1558
1019
    if(ret == -1){
1559
1020
      if(e == 0){
1584
1045
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1585
1046
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1586
1047
                             flags,
1587
 
                             void *mc){
 
1048
                             void* mc){
1588
1049
  if(r == NULL){
1589
1050
    return;
1590
1051
  }
1593
1054
     timed out */
1594
1055
  
1595
1056
  if(quit_now){
1596
 
    avahi_s_service_resolver_free(r);
1597
1057
    return;
1598
1058
  }
1599
1059
  
1644
1104
                            const char *domain,
1645
1105
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1646
1106
                            flags,
1647
 
                            void *mc){
 
1107
                            void* mc){
1648
1108
  if(b == NULL){
1649
1109
    return;
1650
1110
  }
1710
1170
  errno = old_errno;
1711
1171
}
1712
1172
 
1713
 
__attribute__((nonnull, warn_unused_result))
1714
1173
bool get_flags(const char *ifname, struct ifreq *ifr){
1715
1174
  int ret;
1716
 
  int old_errno;
 
1175
  error_t ret_errno;
1717
1176
  
1718
1177
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1719
1178
  if(s < 0){
1720
 
    old_errno = errno;
 
1179
    ret_errno = errno;
1721
1180
    perror_plus("socket");
1722
 
    errno = old_errno;
 
1181
    errno = ret_errno;
1723
1182
    return false;
1724
1183
  }
1725
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1726
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
 
1184
  strcpy(ifr->ifr_name, ifname);
1727
1185
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1728
1186
  if(ret == -1){
1729
1187
    if(debug){
1730
 
      old_errno = errno;
 
1188
      ret_errno = errno;
1731
1189
      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;
 
1190
      errno = ret_errno;
1738
1191
    }
1739
1192
    return false;
1740
1193
  }
1741
 
  if((close(s) == -1) and debug){
1742
 
    old_errno = errno;
1743
 
    perror_plus("close");
1744
 
    errno = old_errno;
1745
 
  }
1746
1194
  return true;
1747
1195
}
1748
1196
 
1749
 
__attribute__((nonnull, warn_unused_result))
1750
1197
bool good_flags(const char *ifname, const struct ifreq *ifr){
1751
1198
  
1752
1199
  /* Reject the loopback device */
1794
1241
 * corresponds to an acceptable network device.
1795
1242
 * (This function is passed to scandir(3) as a filter function.)
1796
1243
 */
1797
 
__attribute__((nonnull, warn_unused_result))
1798
1244
int good_interface(const struct dirent *if_entry){
1799
1245
  if(if_entry->d_name[0] == '.'){
1800
1246
    return 0;
1818
1264
/* 
1819
1265
 * This function determines if a network interface is up.
1820
1266
 */
1821
 
__attribute__((nonnull, warn_unused_result))
1822
1267
bool interface_is_up(const char *interface){
1823
1268
  struct ifreq ifr;
1824
1269
  if(not get_flags(interface, &ifr)){
1835
1280
/* 
1836
1281
 * This function determines if a network interface is running
1837
1282
 */
1838
 
__attribute__((nonnull, warn_unused_result))
1839
1283
bool interface_is_running(const char *interface){
1840
1284
  struct ifreq ifr;
1841
1285
  if(not get_flags(interface, &ifr)){
1849
1293
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1850
1294
}
1851
1295
 
1852
 
__attribute__((nonnull, pure, warn_unused_result))
1853
1296
int notdotentries(const struct dirent *direntry){
1854
1297
  /* Skip "." and ".." */
1855
1298
  if(direntry->d_name[0] == '.'
1862
1305
}
1863
1306
 
1864
1307
/* Is this directory entry a runnable program? */
1865
 
__attribute__((nonnull, warn_unused_result))
1866
1308
int runnable_hook(const struct dirent *direntry){
1867
1309
  int ret;
1868
1310
  size_t sret;
1876
1318
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1877
1319
                "abcdefghijklmnopqrstuvwxyz"
1878
1320
                "0123456789"
1879
 
                "_.-");
 
1321
                "_-");
1880
1322
  if((direntry->d_name)[sret] != '\0'){
1881
1323
    /* Contains non-allowed characters */
1882
1324
    if(debug){
1886
1328
    return 0;
1887
1329
  }
1888
1330
  
1889
 
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
 
1331
  char *fullname = NULL;
 
1332
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1333
  if(ret < 0){
 
1334
    perror_plus("asprintf");
 
1335
    return 0;
 
1336
  }
 
1337
  
 
1338
  ret = stat(fullname, &st);
1890
1339
  if(ret == -1){
1891
1340
    if(debug){
1892
1341
      perror_plus("Could not stat hook");
1916
1365
  return 1;
1917
1366
}
1918
1367
 
1919
 
__attribute__((nonnull, warn_unused_result))
1920
1368
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1921
1369
                            mandos_context *mc){
1922
1370
  int ret;
1926
1374
  
1927
1375
  while(true){
1928
1376
    if(mc->current_server == NULL){
1929
 
      if(debug){
 
1377
      if (debug){
1930
1378
        fprintf_plus(stderr, "Wait until first server is found."
1931
1379
                     " No timeout!\n");
1932
1380
      }
1933
1381
      ret = avahi_simple_poll_iterate(s, -1);
1934
1382
    } else {
1935
 
      if(debug){
 
1383
      if (debug){
1936
1384
        fprintf_plus(stderr, "Check current_server if we should run"
1937
1385
                     " it, or wait\n");
1938
1386
      }
1955
1403
                     - ((intmax_t)waited_time.tv_sec * 1000))
1956
1404
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1957
1405
      
1958
 
      if(debug){
 
1406
      if (debug){
1959
1407
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1960
1408
                     block_time);
1961
1409
      }
1983
1431
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1984
1432
    }
1985
1433
    if(ret != 0){
1986
 
      if(ret > 0 or errno != EINTR){
 
1434
      if (ret > 0 or errno != EINTR){
1987
1435
        return (ret != 1) ? ret : 0;
1988
1436
      }
1989
1437
    }
1990
1438
  }
1991
1439
}
1992
1440
 
1993
 
__attribute__((nonnull))
1994
 
void run_network_hooks(const char *mode, const char *interface,
 
1441
/* Set effective uid to 0, return errno */
 
1442
error_t raise_privileges(void){
 
1443
  error_t old_errno = errno;
 
1444
  error_t ret_errno = 0;
 
1445
  if(seteuid(0) == -1){
 
1446
    ret_errno = errno;
 
1447
    perror_plus("seteuid");
 
1448
  }
 
1449
  errno = old_errno;
 
1450
  return ret_errno;
 
1451
}
 
1452
 
 
1453
/* Set effective and real user ID to 0.  Return errno. */
 
1454
error_t raise_privileges_permanently(void){
 
1455
  error_t old_errno = errno;
 
1456
  error_t ret_errno = raise_privileges();
 
1457
  if(ret_errno != 0){
 
1458
    errno = old_errno;
 
1459
    return ret_errno;
 
1460
  }
 
1461
  if(setuid(0) == -1){
 
1462
    ret_errno = errno;
 
1463
    perror_plus("seteuid");
 
1464
  }
 
1465
  errno = old_errno;
 
1466
  return ret_errno;
 
1467
}
 
1468
 
 
1469
/* Set effective user ID to unprivileged saved user ID */
 
1470
error_t lower_privileges(void){
 
1471
  error_t old_errno = errno;
 
1472
  error_t ret_errno = 0;
 
1473
  if(seteuid(uid) == -1){
 
1474
    ret_errno = errno;
 
1475
    perror_plus("seteuid");
 
1476
  }
 
1477
  errno = old_errno;
 
1478
  return ret_errno;
 
1479
}
 
1480
 
 
1481
/* Lower privileges permanently */
 
1482
error_t lower_privileges_permanently(void){
 
1483
  error_t old_errno = errno;
 
1484
  error_t ret_errno = 0;
 
1485
  if(setuid(uid) == -1){
 
1486
    ret_errno = errno;
 
1487
    perror_plus("setuid");
 
1488
  }
 
1489
  errno = old_errno;
 
1490
  return ret_errno;
 
1491
}
 
1492
 
 
1493
bool run_network_hooks(const char *mode, const char *interface,
1995
1494
                       const float delay){
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);
 
1495
  struct dirent **direntries;
 
1496
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1497
                         alphasort);
2019
1498
  if(numhooks == -1){
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);
 
1499
    if(errno == ENOENT){
 
1500
      if(debug){
 
1501
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1502
                     " found\n", hookdir);
 
1503
      }
 
1504
    } else {
 
1505
      perror_plus("scandir");
2031
1506
    }
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){
 
1507
  } else {
 
1508
    struct dirent *direntry;
 
1509
    int ret;
 
1510
    int devnull = open("/dev/null", O_RDONLY);
 
1511
    for(int i = 0; i < numhooks; i++){
 
1512
      direntry = direntries[i];
 
1513
      char *fullname = NULL;
 
1514
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1515
      if(ret < 0){
2078
1516
        perror_plus("asprintf");
2079
 
        _exit(EX_OSERR);
2080
 
      }
2081
 
      ret = setenv("DELAY", delaystring, 1);
2082
 
      if(ret == -1){
 
1517
        continue;
 
1518
      }
 
1519
      if(debug){
 
1520
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1521
                     direntry->d_name);
 
1522
      }
 
1523
      pid_t hook_pid = fork();
 
1524
      if(hook_pid == 0){
 
1525
        /* Child */
 
1526
        /* Raise privileges */
 
1527
        raise_privileges_permanently();
 
1528
        /* Set group */
 
1529
        errno = 0;
 
1530
        ret = setgid(0);
 
1531
        if(ret == -1){
 
1532
          perror_plus("setgid");
 
1533
        }
 
1534
        /* Reset supplementary groups */
 
1535
        errno = 0;
 
1536
        ret = setgroups(0, NULL);
 
1537
        if(ret == -1){
 
1538
          perror_plus("setgroups");
 
1539
        }
 
1540
        dup2(devnull, STDIN_FILENO);
 
1541
        close(devnull);
 
1542
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1543
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1544
        if(ret == -1){
 
1545
          perror_plus("setenv");
 
1546
          _exit(EX_OSERR);
 
1547
        }
 
1548
        ret = setenv("DEVICE", interface, 1);
 
1549
        if(ret == -1){
 
1550
          perror_plus("setenv");
 
1551
          _exit(EX_OSERR);
 
1552
        }
 
1553
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1554
        if(ret == -1){
 
1555
          perror_plus("setenv");
 
1556
          _exit(EX_OSERR);
 
1557
        }
 
1558
        ret = setenv("MODE", mode, 1);
 
1559
        if(ret == -1){
 
1560
          perror_plus("setenv");
 
1561
          _exit(EX_OSERR);
 
1562
        }
 
1563
        char *delaystring;
 
1564
        ret = asprintf(&delaystring, "%f", delay);
 
1565
        if(ret == -1){
 
1566
          perror_plus("asprintf");
 
1567
          _exit(EX_OSERR);
 
1568
        }
 
1569
        ret = setenv("DELAY", delaystring, 1);
 
1570
        if(ret == -1){
 
1571
          free(delaystring);
 
1572
          perror_plus("setenv");
 
1573
          _exit(EX_OSERR);
 
1574
        }
2083
1575
        free(delaystring);
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;
 
1576
        if(connect_to != NULL){
 
1577
          ret = setenv("CONNECT", connect_to, 1);
 
1578
          if(ret == -1){
 
1579
            perror_plus("setenv");
 
1580
            _exit(EX_OSERR);
 
1581
          }
 
1582
        }
 
1583
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1584
          perror_plus("execl");
 
1585
          _exit(EXIT_FAILURE);
 
1586
        }
2152
1587
      } else {
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);
 
1588
        int status;
 
1589
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1590
          perror_plus("waitpid");
 
1591
          free(fullname);
 
1592
          continue;
 
1593
        }
 
1594
        if(WIFEXITED(status)){
 
1595
          if(WEXITSTATUS(status) != 0){
 
1596
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1597
                         " with status %d\n", direntry->d_name,
 
1598
                         WEXITSTATUS(status));
 
1599
            free(fullname);
 
1600
            continue;
 
1601
          }
 
1602
        } else if(WIFSIGNALED(status)){
 
1603
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1604
                       " signal %d\n", direntry->d_name,
 
1605
                       WTERMSIG(status));
 
1606
          free(fullname);
 
1607
          continue;
 
1608
        } else {
 
1609
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1610
                       " crashed\n", direntry->d_name);
 
1611
          free(fullname);
 
1612
          continue;
 
1613
        }
 
1614
      }
 
1615
      free(fullname);
 
1616
      if(debug){
 
1617
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1618
                     direntry->d_name);
 
1619
      }
 
1620
    }
 
1621
    close(devnull);
 
1622
  }
 
1623
  return true;
2172
1624
}
2173
1625
 
2174
 
__attribute__((nonnull, warn_unused_result))
2175
 
int bring_up_interface(const char *const interface,
2176
 
                       const float delay){
2177
 
  int old_errno = errno;
2178
 
  int ret;
 
1626
error_t bring_up_interface(const char *const interface,
 
1627
                           const float delay){
 
1628
  int sd = -1;
 
1629
  error_t old_errno = errno;
 
1630
  error_t ret_errno = 0;
 
1631
  int ret, ret_setflags;
2179
1632
  struct ifreq network;
2180
1633
  unsigned int if_index = if_nametoindex(interface);
2181
1634
  if(if_index == 0){
2190
1643
  }
2191
1644
  
2192
1645
  if(not interface_is_up(interface)){
2193
 
    int ret_errno = 0;
2194
 
    int ioctl_errno = 0;
2195
 
    if(not get_flags(interface, &network)){
 
1646
    if(not get_flags(interface, &network) and debug){
2196
1647
      ret_errno = errno;
2197
1648
      fprintf_plus(stderr, "Failed to get flags for interface "
2198
1649
                   "\"%s\"\n", interface);
2199
 
      errno = old_errno;
2200
1650
      return ret_errno;
2201
1651
    }
2202
 
    network.ifr_flags |= IFF_UP; /* set flag */
 
1652
    network.ifr_flags |= IFF_UP;
2203
1653
    
2204
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
2205
 
    if(sd == -1){
 
1654
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1655
    if(sd < 0){
2206
1656
      ret_errno = errno;
2207
1657
      perror_plus("socket");
2208
1658
      errno = old_errno;
2209
1659
      return ret_errno;
2210
1660
    }
2211
 
    
 
1661
  
2212
1662
    if(quit_now){
2213
 
      ret = close(sd);
2214
 
      if(ret == -1){
2215
 
        perror_plus("close");
2216
 
      }
 
1663
      close(sd);
2217
1664
      errno = old_errno;
2218
1665
      return EINTR;
2219
1666
    }
2223
1670
                   interface);
2224
1671
    }
2225
1672
    
2226
 
    /* Raise privileges */
2227
 
    ret_errno = raise_privileges();
2228
 
    if(ret_errno != 0){
2229
 
      errno = ret_errno;
2230
 
      perror_plus("Failed to raise privileges");
2231
 
    }
 
1673
    /* Raise priviliges */
 
1674
    raise_privileges();
2232
1675
    
2233
1676
#ifdef __linux__
2234
 
    int ret_linux;
2235
 
    bool restore_loglevel = false;
2236
 
    if(ret_errno == 0){
2237
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
2238
 
         messages about the network interface to mess up the prompt */
2239
 
      ret_linux = klogctl(8, NULL, 5);
2240
 
      if(ret_linux == -1){
2241
 
        perror_plus("klogctl");
2242
 
      } else {
2243
 
        restore_loglevel = true;
2244
 
      }
 
1677
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1678
       messages about the network interface to mess up the prompt */
 
1679
    int ret_linux = klogctl(8, NULL, 5);
 
1680
    bool restore_loglevel = true;
 
1681
    if(ret_linux == -1){
 
1682
      restore_loglevel = false;
 
1683
      perror_plus("klogctl");
2245
1684
    }
2246
1685
#endif  /* __linux__ */
2247
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
2248
 
    ioctl_errno = errno;
 
1686
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1687
    ret_errno = errno;
2249
1688
#ifdef __linux__
2250
1689
    if(restore_loglevel){
2251
1690
      ret_linux = klogctl(7, NULL, 0);
2255
1694
    }
2256
1695
#endif  /* __linux__ */
2257
1696
    
2258
 
    /* If raise_privileges() succeeded above */
2259
 
    if(ret_errno == 0){
2260
 
      /* Lower privileges */
2261
 
      ret_errno = lower_privileges();
2262
 
      if(ret_errno != 0){
2263
 
        errno = ret_errno;
2264
 
        perror_plus("Failed to lower privileges");
2265
 
      }
2266
 
    }
 
1697
    /* Lower privileges */
 
1698
    lower_privileges();
2267
1699
    
2268
1700
    /* Close the socket */
2269
 
    ret = close(sd);
 
1701
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
2270
1702
    if(ret == -1){
2271
1703
      perror_plus("close");
2272
1704
    }
2273
1705
    
2274
1706
    if(ret_setflags == -1){
2275
 
      errno = ioctl_errno;
 
1707
      errno = ret_errno;
2276
1708
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
2277
1709
      errno = old_errno;
2278
 
      return ioctl_errno;
 
1710
      return ret_errno;
2279
1711
    }
2280
1712
  } else if(debug){
2281
1713
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
2284
1716
  
2285
1717
  /* Sleep checking until interface is running.
2286
1718
     Check every 0.25s, up to total time of delay */
2287
 
  for(int i = 0; i < delay * 4; i++){
 
1719
  for(int i=0; i < delay * 4; i++){
2288
1720
    if(interface_is_running(interface)){
2289
1721
      break;
2290
1722
    }
2299
1731
  return 0;
2300
1732
}
2301
1733
 
2302
 
__attribute__((nonnull, warn_unused_result))
2303
 
int take_down_interface(const char *const interface){
2304
 
  int old_errno = errno;
 
1734
error_t take_down_interface(const char *const interface){
 
1735
  error_t old_errno = errno;
2305
1736
  struct ifreq network;
2306
1737
  unsigned int if_index = if_nametoindex(interface);
2307
1738
  if(if_index == 0){
2310
1741
    return ENXIO;
2311
1742
  }
2312
1743
  if(interface_is_up(interface)){
2313
 
    int ret_errno = 0;
2314
 
    int ioctl_errno = 0;
 
1744
    error_t ret_errno = 0;
2315
1745
    if(not get_flags(interface, &network) and debug){
2316
1746
      ret_errno = errno;
2317
1747
      fprintf_plus(stderr, "Failed to get flags for interface "
2318
1748
                   "\"%s\"\n", interface);
2319
 
      errno = old_errno;
2320
1749
      return ret_errno;
2321
1750
    }
2322
1751
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2323
1752
    
2324
1753
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
2325
 
    if(sd == -1){
 
1754
    if(sd < 0){
2326
1755
      ret_errno = errno;
2327
1756
      perror_plus("socket");
2328
1757
      errno = old_errno;
2334
1763
                   interface);
2335
1764
    }
2336
1765
    
2337
 
    /* Raise privileges */
2338
 
    ret_errno = raise_privileges();
2339
 
    if(ret_errno != 0){
2340
 
      errno = ret_errno;
2341
 
      perror_plus("Failed to raise privileges");
2342
 
    }
 
1766
    /* Raise priviliges */
 
1767
    raise_privileges();
2343
1768
    
2344
1769
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
2345
 
    ioctl_errno = errno;
 
1770
    ret_errno = errno;
2346
1771
    
2347
 
    /* If raise_privileges() succeeded above */
2348
 
    if(ret_errno == 0){
2349
 
      /* Lower privileges */
2350
 
      ret_errno = lower_privileges();
2351
 
      if(ret_errno != 0){
2352
 
        errno = ret_errno;
2353
 
        perror_plus("Failed to lower privileges");
2354
 
      }
2355
 
    }
 
1772
    /* Lower privileges */
 
1773
    lower_privileges();
2356
1774
    
2357
1775
    /* Close the socket */
2358
 
    int ret = close(sd);
 
1776
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
2359
1777
    if(ret == -1){
2360
1778
      perror_plus("close");
2361
1779
    }
2362
1780
    
2363
1781
    if(ret_setflags == -1){
2364
 
      errno = ioctl_errno;
 
1782
      errno = ret_errno;
2365
1783
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2366
1784
      errno = old_errno;
2367
 
      return ioctl_errno;
 
1785
      return ret_errno;
2368
1786
    }
2369
1787
  } else if(debug){
2370
1788
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
2376
1794
}
2377
1795
 
2378
1796
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 };
 
1797
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1798
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1799
                        "+CTYPE-OPENPGP", .current_server = NULL, 
 
1800
                        .interfaces = NULL, .interfaces_size = 0 };
2384
1801
  AvahiSServiceBrowser *sb = NULL;
2385
1802
  error_t ret_errno;
2386
1803
  int ret;
2389
1806
  int exitcode = EXIT_SUCCESS;
2390
1807
  char *interfaces_to_take_down = NULL;
2391
1808
  size_t interfaces_to_take_down_size = 0;
2392
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
2393
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
2394
 
  char *tempdir = NULL;
 
1809
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1810
  bool tempdir_created = false;
2395
1811
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2396
1812
  const char *seckey = PATHDIR "/" SECKEY;
2397
1813
  const char *pubkey = PATHDIR "/" PUBKEY;
2398
 
  const char *dh_params_file = NULL;
2399
1814
  char *interfaces_hooks = NULL;
2400
1815
  
2401
1816
  bool gnutls_initialized = false;
2454
1869
        .doc = "Bit length of the prime number used in the"
2455
1870
        " Diffie-Hellman key exchange",
2456
1871
        .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
1872
      { .name = "priority", .key = 130,
2463
1873
        .arg = "STRING",
2464
1874
        .doc = "GnuTLS priority string for the TLS handshake",
2519
1929
        }
2520
1930
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2521
1931
        break;
2522
 
      case 134:                 /* --dh-params */
2523
 
        dh_params_file = arg;
2524
 
        break;
2525
1932
      case 130:                 /* --priority */
2526
1933
        mc.priority = arg;
2527
1934
        break;
2567
1974
                         .args_doc = "",
2568
1975
                         .doc = "Mandos client -- Get and decrypt"
2569
1976
                         " 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){
 
1977
    ret = argp_parse(&argp, argc, argv,
 
1978
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1979
    switch(ret){
2573
1980
    case 0:
2574
1981
      break;
2575
1982
    case ENOMEM:
2576
1983
    default:
2577
 
      errno = ret_errno;
 
1984
      errno = ret;
2578
1985
      perror_plus("argp_parse");
2579
1986
      exitcode = EX_OSERR;
2580
1987
      goto end;
2583
1990
      goto end;
2584
1991
    }
2585
1992
  }
2586
 
  
 
1993
    
2587
1994
  {
2588
1995
    /* Work around Debian bug #633582:
2589
 
       <https://bugs.debian.org/633582> */
 
1996
       <http://bugs.debian.org/633582> */
2590
1997
    
2591
 
    /* Re-raise privileges */
2592
 
    ret = raise_privileges();
2593
 
    if(ret != 0){
2594
 
      errno = ret;
2595
 
      perror_plus("Failed to raise privileges");
2596
 
    } else {
 
1998
    /* Re-raise priviliges */
 
1999
    if(raise_privileges() == 0){
2597
2000
      struct stat st;
2598
2001
      
2599
2002
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2613
2016
              }
2614
2017
            }
2615
2018
          }
2616
 
          close(seckey_fd);
 
2019
          TEMP_FAILURE_RETRY(close(seckey_fd));
2617
2020
        }
2618
2021
      }
2619
 
      
 
2022
    
2620
2023
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2621
2024
        int pubkey_fd = open(pubkey, O_RDONLY);
2622
2025
        if(pubkey_fd == -1){
2634
2037
              }
2635
2038
            }
2636
2039
          }
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
 
      
 
2040
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2041
        }
 
2042
      }
 
2043
    
2663
2044
      /* Lower privileges */
2664
 
      ret = lower_privileges();
2665
 
      if(ret != 0){
2666
 
        errno = ret;
2667
 
        perror_plus("Failed to lower privileges");
2668
 
      }
 
2045
      lower_privileges();
2669
2046
    }
2670
2047
  }
2671
2048
  
2697
2074
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2698
2075
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2699
2076
    }
2700
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2701
 
                      interfaces_hooks : "", delay);
 
2077
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
 
2078
                             interfaces_hooks : "", delay)){
 
2079
      goto end;
 
2080
    }
2702
2081
  }
2703
2082
  
2704
2083
  if(not debug){
2782
2161
  
2783
2162
  /* If no interfaces were specified, make a list */
2784
2163
  if(mc.interfaces == NULL){
2785
 
    struct dirent **direntries = NULL;
 
2164
    struct dirent **direntries;
2786
2165
    /* Look for any good interfaces */
2787
2166
    ret = scandir(sys_class_net, &direntries, good_interface,
2788
2167
                  alphasort);
2794
2173
        if(ret_errno != 0){
2795
2174
          errno = ret_errno;
2796
2175
          perror_plus("argz_add");
2797
 
          free(direntries[i]);
2798
2176
          continue;
2799
2177
        }
2800
2178
        if(debug){
2801
2179
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2802
2180
                       direntries[i]->d_name);
2803
2181
        }
2804
 
        free(direntries[i]);
2805
2182
      }
2806
2183
      free(direntries);
2807
2184
    } else {
2808
 
      if(ret == 0){
2809
 
        free(direntries);
2810
 
      }
 
2185
      free(direntries);
2811
2186
      fprintf_plus(stderr, "Could not find a network interface\n");
2812
2187
      exitcode = EXIT_FAILURE;
2813
2188
      goto end;
2836
2211
        break;
2837
2212
      }
2838
2213
      bool interface_was_up = interface_is_up(interface);
2839
 
      errno = bring_up_interface(interface, delay);
 
2214
      ret = bring_up_interface(interface, delay);
2840
2215
      if(not interface_was_up){
2841
 
        if(errno != 0){
2842
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2843
 
                       " %s\n", interface, strerror(errno));
 
2216
        if(ret != 0){
 
2217
          errno = ret;
 
2218
          perror_plus("Failed to bring up interface");
2844
2219
        } else {
2845
 
          errno = argz_add(&interfaces_to_take_down,
2846
 
                           &interfaces_to_take_down_size,
2847
 
                           interface);
2848
 
          if(errno != 0){
 
2220
          ret_errno = argz_add(&interfaces_to_take_down,
 
2221
                               &interfaces_to_take_down_size,
 
2222
                               interface);
 
2223
          if(ret_errno != 0){
 
2224
            errno = ret_errno;
2849
2225
            perror_plus("argz_add");
2850
2226
          }
2851
2227
        }
2869
2245
    goto end;
2870
2246
  }
2871
2247
  
2872
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
2248
  ret = init_gnutls_global(pubkey, seckey, &mc);
2873
2249
  if(ret == -1){
2874
2250
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2875
2251
    exitcode = EX_UNAVAILABLE;
2882
2258
    goto end;
2883
2259
  }
2884
2260
  
2885
 
  /* Try /run/tmp before /tmp */
2886
 
  tempdir = mkdtemp(run_tempdir);
2887
 
  if(tempdir == NULL and errno == ENOENT){
2888
 
      if(debug){
2889
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2890
 
                     run_tempdir, old_tempdir);
2891
 
      }
2892
 
      tempdir = mkdtemp(old_tempdir);
2893
 
  }
2894
 
  if(tempdir == NULL){
 
2261
  if(mkdtemp(tempdir) == NULL){
2895
2262
    perror_plus("mkdtemp");
2896
2263
    goto end;
2897
2264
  }
 
2265
  tempdir_created = true;
2898
2266
  
2899
2267
  if(quit_now){
2900
2268
    goto end;
2975
2343
      sleep((unsigned int)retry_interval);
2976
2344
    }
2977
2345
    
2978
 
    if(not quit_now){
 
2346
    if (not quit_now){
2979
2347
      exitcode = EXIT_SUCCESS;
2980
2348
    }
2981
2349
    
2997
2365
    
2998
2366
    /* Allocate a new server */
2999
2367
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
3000
 
                                 &config, NULL, NULL, &ret);
 
2368
                                 &config, NULL, NULL, &ret_errno);
3001
2369
    
3002
2370
    /* Free the Avahi configuration data */
3003
2371
    avahi_server_config_free(&config);
3006
2374
  /* Check if creating the Avahi server object succeeded */
3007
2375
  if(mc.server == NULL){
3008
2376
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
3009
 
                 avahi_strerror(ret));
 
2377
                 avahi_strerror(ret_errno));
3010
2378
    exitcode = EX_UNAVAILABLE;
3011
2379
    goto end;
3012
2380
  }
3036
2404
  if(debug){
3037
2405
    fprintf_plus(stderr, "Starting Avahi loop search\n");
3038
2406
  }
3039
 
  
 
2407
 
3040
2408
  ret = avahi_loop_with_timeout(simple_poll,
3041
2409
                                (int)(retry_interval * 1000), &mc);
3042
2410
  if(debug){
3047
2415
 end:
3048
2416
  
3049
2417
  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
 
    }
 
2418
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
3057
2419
  }
3058
2420
  
3059
2421
  /* Cleanup things */
3070
2432
  
3071
2433
  if(gnutls_initialized){
3072
2434
    gnutls_certificate_free_credentials(mc.cred);
 
2435
    gnutls_global_deinit();
3073
2436
    gnutls_dh_params_deinit(mc.dh_params);
3074
2437
  }
3075
2438
  
3083
2446
    mc.current_server->prev->next = NULL;
3084
2447
    while(mc.current_server != NULL){
3085
2448
      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
3094
2449
      free(mc.current_server);
3095
2450
      mc.current_server = next;
3096
2451
    }
3097
2452
  }
3098
2453
  
3099
 
  /* Re-raise privileges */
 
2454
  /* Re-raise priviliges */
3100
2455
  {
3101
 
    ret = raise_privileges();
3102
 
    if(ret != 0){
3103
 
      errno = ret;
3104
 
      perror_plus("Failed to raise privileges");
3105
 
    } else {
3106
 
      
3107
 
      /* Run network hooks */
3108
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
3109
 
                        interfaces_hooks : "", delay);
3110
 
      
3111
 
      /* Take down the network interfaces which were brought up */
3112
 
      {
3113
 
        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;
3120
 
            perror_plus("Failed to take down interface");
3121
 
          }
3122
 
        }
3123
 
        if(debug and (interfaces_to_take_down == NULL)){
3124
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
3125
 
                       " down\n");
3126
 
        }
3127
 
      }
3128
 
    }
3129
 
    
3130
 
    ret = lower_privileges_permanently();
3131
 
    if(ret != 0){
3132
 
      errno = ret;
3133
 
      perror_plus("Failed to lower privileges permanently");
3134
 
    }
 
2456
    raise_privileges();
 
2457
    
 
2458
    /* Run network hooks */
 
2459
    run_network_hooks("stop", interfaces_hooks != NULL ?
 
2460
                      interfaces_hooks : "", delay);
 
2461
    
 
2462
    /* Take down the network interfaces which were brought up */
 
2463
    {
 
2464
      char *interface = NULL;
 
2465
      while((interface=argz_next(interfaces_to_take_down,
 
2466
                                 interfaces_to_take_down_size,
 
2467
                                 interface))){
 
2468
        ret_errno = take_down_interface(interface);
 
2469
        if(ret_errno != 0){
 
2470
          errno = ret_errno;
 
2471
          perror_plus("Failed to take down interface");
 
2472
        }
 
2473
      }
 
2474
      if(debug and (interfaces_to_take_down == NULL)){
 
2475
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2476
                     " down\n");
 
2477
      }
 
2478
    }
 
2479
    
 
2480
    lower_privileges_permanently();
3135
2481
  }
3136
2482
  
3137
2483
  free(interfaces_to_take_down);
3138
2484
  free(interfaces_hooks);
3139
2485
  
3140
 
  void clean_dir_at(int base, const char * const dirname,
3141
 
                    uintmax_t level){
 
2486
  /* Removes the GPGME temp directory and all files inside */
 
2487
  if(tempdir_created){
3142
2488
    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){
 
2489
    struct dirent *direntry = NULL;
 
2490
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2491
                             alphasort);
 
2492
    if (numentries > 0){
3156
2493
      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
 
  /* Removes the GPGME temp directory and all files inside */
3195
 
  if(tempdir != NULL){
3196
 
    clean_dir_at(-1, tempdir, 0);
 
2494
        direntry = direntries[i];
 
2495
        char *fullname = NULL;
 
2496
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
2497
                       direntry->d_name);
 
2498
        if(ret < 0){
 
2499
          perror_plus("asprintf");
 
2500
          continue;
 
2501
        }
 
2502
        ret = remove(fullname);
 
2503
        if(ret == -1){
 
2504
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2505
                       strerror(errno));
 
2506
        }
 
2507
        free(fullname);
 
2508
      }
 
2509
    }
 
2510
 
 
2511
    /* need to clean even if 0 because man page doesn't specify */
 
2512
    free(direntries);
 
2513
    if (numentries == -1){
 
2514
      perror_plus("scandir");
 
2515
    }
 
2516
    ret = rmdir(tempdir);
 
2517
    if(ret == -1 and errno != ENOENT){
 
2518
      perror_plus("rmdir");
 
2519
    }
3197
2520
  }
3198
2521
  
3199
2522
  if(quit_now){