/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-06-07 22:37:22 UTC
  • Revision ID: teddy@recompile.se-20140607223722-55qmdr3n9x39pvx4
Make mandos-client use fstatat().

* plugins.d/mandos-client.d (runnable_hook): Use fstatat().

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-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008-2014 Teddy Hogeborn
 
13
 * Copyright © 2008-2014 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
33
33
#ifndef _LARGEFILE_SOURCE
34
34
#define _LARGEFILE_SOURCE
35
 
#endif
 
35
#endif  /* not _LARGEFILE_SOURCE */
36
36
#ifndef _FILE_OFFSET_BITS
37
37
#define _FILE_OFFSET_BITS 64
38
 
#endif
 
38
#endif  /* not _FILE_OFFSET_BITS */
39
39
 
40
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
55
55
                                   opendir(), DIR */
56
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect() */
 
58
                                   inet_pton(), connect(),
 
59
                                   getnameinfo() */
59
60
#include <fcntl.h>              /* open() */
60
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
61
62
                                 */
62
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
64
                                   strtoimax() */
64
 
#include <assert.h>             /* assert() */
65
65
#include <errno.h>              /* perror(), errno,
66
66
                                   program_invocation_short_name */
67
67
#include <time.h>               /* nanosleep(), time(), sleep() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
76
                                   setgid(), pause(), _exit() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons() */
78
78
#include <iso646.h>             /* not, or, and */
79
79
#include <argp.h>               /* struct argp_option, error_t, struct
80
80
                                   argp_state, struct argp,
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
89
                                   WEXITSTATUS(), WTERMSIG() */
 
90
#include <grp.h>                /* setgroups() */
 
91
#include <argz.h>               /* argz_add_sep(), argz_next(),
 
92
                                   argz_delete(), argz_append(),
 
93
                                   argz_stringify(), argz_add(),
 
94
                                   argz_count() */
 
95
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
 
96
                                   EAI_SYSTEM, gai_strerror() */
90
97
 
91
98
#ifdef __linux__
92
99
#include <sys/klog.h>           /* klogctl() */
134
141
static const char sys_class_net[] = "/sys/class/net";
135
142
char *connect_to = NULL;
136
143
const char *hookdir = HOOKDIR;
 
144
int hookdir_fd = -1;
 
145
uid_t uid = 65534;
 
146
gid_t gid = 65534;
137
147
 
138
148
/* Doubly linked list that need to be circularly linked when used */
139
149
typedef struct server{
140
150
  const char *ip;
141
 
  uint16_t port;
 
151
  in_port_t port;
142
152
  AvahiIfIndex if_index;
143
153
  int af;
144
154
  struct timespec last_seen;
148
158
 
149
159
/* Used for passing in values through the Avahi callback functions */
150
160
typedef struct {
151
 
  AvahiSimplePoll *simple_poll;
152
161
  AvahiServer *server;
153
162
  gnutls_certificate_credentials_t cred;
154
163
  unsigned int dh_bits;
156
165
  const char *priority;
157
166
  gpgme_ctx_t ctx;
158
167
  server *current_server;
 
168
  char *interfaces;
 
169
  size_t interfaces_size;
159
170
} mandos_context;
160
171
 
161
 
/* global context so signal handler can reach it*/
162
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
163
 
                      .dh_bits = 1024, .priority = "SECURE256"
164
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
165
 
                      .current_server = NULL };
 
172
/* global so signal handler can reach it*/
 
173
AvahiSimplePoll *simple_poll;
166
174
 
167
175
sig_atomic_t quit_now = 0;
168
176
int signal_received = 0;
169
177
 
170
178
/* Function to use when printing errors */
171
179
void perror_plus(const char *print_text){
 
180
  int e = errno;
172
181
  fprintf(stderr, "Mandos plugin %s: ",
173
182
          program_invocation_short_name);
 
183
  errno = e;
174
184
  perror(print_text);
175
185
}
176
186
 
 
187
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
188
int fprintf_plus(FILE *stream, const char *format, ...){
 
189
  va_list ap;
 
190
  va_start (ap, format);
 
191
  
 
192
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
193
                             program_invocation_short_name));
 
194
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
195
}
 
196
 
177
197
/*
178
198
 * Make additional room in "buffer" for at least BUFFER_SIZE more
179
199
 * bytes. "buffer_capacity" is how much is currently allocated,
180
200
 * "buffer_length" is how much is already used.
181
201
 */
 
202
__attribute__((nonnull, warn_unused_result))
182
203
size_t incbuffer(char **buffer, size_t buffer_length,
183
204
                 size_t buffer_capacity){
184
205
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
185
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
186
 
    if(buffer == NULL){
 
206
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
207
    if(new_buf == NULL){
 
208
      int old_errno = errno;
 
209
      free(*buffer);
 
210
      errno = old_errno;
 
211
      *buffer = NULL;
187
212
      return 0;
188
213
    }
 
214
    *buffer = new_buf;
189
215
    buffer_capacity += BUFFER_SIZE;
190
216
  }
191
217
  return buffer_capacity;
192
218
}
193
219
 
194
220
/* Add server to set of servers to retry periodically */
195
 
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
196
 
               int af){
 
221
__attribute__((nonnull, warn_unused_result))
 
222
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
 
223
                int af, server **current_server){
197
224
  int ret;
198
225
  server *new_server = malloc(sizeof(server));
199
226
  if(new_server == NULL){
200
227
    perror_plus("malloc");
201
 
    return -1;
 
228
    return false;
202
229
  }
203
230
  *new_server = (server){ .ip = strdup(ip),
204
231
                          .port = port,
206
233
                          .af = af };
207
234
  if(new_server->ip == NULL){
208
235
    perror_plus("strdup");
209
 
    return -1;
 
236
    return false;
 
237
  }
 
238
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
 
239
  if(ret == -1){
 
240
    perror_plus("clock_gettime");
 
241
    return false;
210
242
  }
211
243
  /* Special case of first server */
212
 
  if (mc.current_server == NULL){
 
244
  if(*current_server == NULL){
213
245
    new_server->next = new_server;
214
246
    new_server->prev = new_server;
215
 
    mc.current_server = new_server;
216
 
  /* Place the new server last in the list */
 
247
    *current_server = new_server;
217
248
  } else {
218
 
    new_server->next = mc.current_server;
219
 
    new_server->prev = mc.current_server->prev;
 
249
    /* Place the new server last in the list */
 
250
    new_server->next = *current_server;
 
251
    new_server->prev = (*current_server)->prev;
220
252
    new_server->prev->next = new_server;
221
 
    mc.current_server->prev = new_server;
222
 
  }
223
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
224
 
  if(ret == -1){
225
 
    perror_plus("clock_gettime");
226
 
    return -1;
227
 
  }
228
 
  return 0;
 
253
    (*current_server)->prev = new_server;
 
254
  }
 
255
  return true;
229
256
}
230
257
 
231
258
/* 
232
259
 * Initialize GPGME.
233
260
 */
234
 
static bool init_gpgme(const char *seckey, const char *pubkey,
235
 
                       const char *tempdir){
 
261
__attribute__((nonnull, warn_unused_result))
 
262
static bool init_gpgme(const char * const seckey,
 
263
                       const char * const pubkey,
 
264
                       const char * const tempdir,
 
265
                       mandos_context *mc){
236
266
  gpgme_error_t rc;
237
267
  gpgme_engine_info_t engine_info;
238
268
  
239
 
  
240
269
  /*
241
270
   * Helper function to insert pub and seckey to the engine keyring.
242
271
   */
243
 
  bool import_key(const char *filename){
 
272
  bool import_key(const char * const filename){
244
273
    int ret;
245
274
    int fd;
246
275
    gpgme_data_t pgp_data;
253
282
    
254
283
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
255
284
    if(rc != GPG_ERR_NO_ERROR){
256
 
      fprintf(stderr, "Mandos plugin mandos-client: "
257
 
              "bad gpgme_data_new_from_fd: %s: %s\n",
258
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
285
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
286
                   gpgme_strsource(rc), gpgme_strerror(rc));
259
287
      return false;
260
288
    }
261
289
    
262
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
290
    rc = gpgme_op_import(mc->ctx, pgp_data);
263
291
    if(rc != GPG_ERR_NO_ERROR){
264
 
      fprintf(stderr, "Mandos plugin mandos-client: "
265
 
              "bad gpgme_op_import: %s: %s\n",
266
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
292
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
293
                   gpgme_strsource(rc), gpgme_strerror(rc));
267
294
      return false;
268
295
    }
269
296
    
276
303
  }
277
304
  
278
305
  if(debug){
279
 
    fprintf(stderr, "Mandos plugin mandos-client: "
280
 
            "Initializing GPGME\n");
 
306
    fprintf_plus(stderr, "Initializing GPGME\n");
281
307
  }
282
308
  
283
309
  /* Init GPGME */
284
310
  gpgme_check_version(NULL);
285
311
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
286
312
  if(rc != GPG_ERR_NO_ERROR){
287
 
    fprintf(stderr, "Mandos plugin mandos-client: "
288
 
            "bad gpgme_engine_check_version: %s: %s\n",
289
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
313
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
314
                 gpgme_strsource(rc), gpgme_strerror(rc));
290
315
    return false;
291
316
  }
292
317
  
293
318
  /* Set GPGME home directory for the OpenPGP engine only */
294
319
  rc = gpgme_get_engine_info(&engine_info);
295
320
  if(rc != GPG_ERR_NO_ERROR){
296
 
    fprintf(stderr, "Mandos plugin mandos-client: "
297
 
            "bad gpgme_get_engine_info: %s: %s\n",
298
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
321
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
322
                 gpgme_strsource(rc), gpgme_strerror(rc));
299
323
    return false;
300
324
  }
301
325
  while(engine_info != NULL){
307
331
    engine_info = engine_info->next;
308
332
  }
309
333
  if(engine_info == NULL){
310
 
    fprintf(stderr, "Mandos plugin mandos-client: "
311
 
            "Could not set GPGME home dir to %s\n", tempdir);
 
334
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
335
                 tempdir);
312
336
    return false;
313
337
  }
314
338
  
315
339
  /* Create new GPGME "context" */
316
 
  rc = gpgme_new(&(mc.ctx));
 
340
  rc = gpgme_new(&(mc->ctx));
317
341
  if(rc != GPG_ERR_NO_ERROR){
318
 
    fprintf(stderr, "Mandos plugin mandos-client: "
319
 
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
320
 
            gpgme_strerror(rc));
 
342
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
343
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
344
                 gpgme_strerror(rc));
321
345
    return false;
322
346
  }
323
347
  
332
356
 * Decrypt OpenPGP data.
333
357
 * Returns -1 on error
334
358
 */
 
359
__attribute__((nonnull, warn_unused_result))
335
360
static ssize_t pgp_packet_decrypt(const char *cryptotext,
336
361
                                  size_t crypto_size,
337
 
                                  char **plaintext){
 
362
                                  char **plaintext,
 
363
                                  mandos_context *mc){
338
364
  gpgme_data_t dh_crypto, dh_plain;
339
365
  gpgme_error_t rc;
340
366
  ssize_t ret;
342
368
  ssize_t plaintext_length = 0;
343
369
  
344
370
  if(debug){
345
 
    fprintf(stderr, "Mandos plugin mandos-client: "
346
 
            "Trying to decrypt OpenPGP data\n");
 
371
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
347
372
  }
348
373
  
349
374
  /* Create new GPGME data buffer from memory cryptotext */
350
375
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
351
376
                               0);
352
377
  if(rc != GPG_ERR_NO_ERROR){
353
 
    fprintf(stderr, "Mandos plugin mandos-client: "
354
 
            "bad gpgme_data_new_from_mem: %s: %s\n",
355
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
378
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
379
                 gpgme_strsource(rc), gpgme_strerror(rc));
356
380
    return -1;
357
381
  }
358
382
  
359
383
  /* Create new empty GPGME data buffer for the plaintext */
360
384
  rc = gpgme_data_new(&dh_plain);
361
385
  if(rc != GPG_ERR_NO_ERROR){
362
 
    fprintf(stderr, "Mandos plugin mandos-client: "
363
 
            "bad gpgme_data_new: %s: %s\n",
364
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
386
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
387
                 "bad gpgme_data_new: %s: %s\n",
 
388
                 gpgme_strsource(rc), gpgme_strerror(rc));
365
389
    gpgme_data_release(dh_crypto);
366
390
    return -1;
367
391
  }
368
392
  
369
393
  /* Decrypt data from the cryptotext data buffer to the plaintext
370
394
     data buffer */
371
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
395
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
372
396
  if(rc != GPG_ERR_NO_ERROR){
373
 
    fprintf(stderr, "Mandos plugin mandos-client: "
374
 
            "bad gpgme_op_decrypt: %s: %s\n",
375
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
397
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
398
                 gpgme_strsource(rc), gpgme_strerror(rc));
376
399
    plaintext_length = -1;
377
400
    if(debug){
378
401
      gpgme_decrypt_result_t result;
379
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
402
      result = gpgme_op_decrypt_result(mc->ctx);
380
403
      if(result == NULL){
381
 
        fprintf(stderr, "Mandos plugin mandos-client: "
382
 
                "gpgme_op_decrypt_result failed\n");
 
404
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
383
405
      } else {
384
 
        fprintf(stderr, "Mandos plugin mandos-client: "
385
 
                "Unsupported algorithm: %s\n",
386
 
                result->unsupported_algorithm);
387
 
        fprintf(stderr, "Mandos plugin mandos-client: "
388
 
                "Wrong key usage: %u\n",
389
 
                result->wrong_key_usage);
 
406
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
407
                     result->unsupported_algorithm);
 
408
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
409
                     result->wrong_key_usage);
390
410
        if(result->file_name != NULL){
391
 
          fprintf(stderr, "Mandos plugin mandos-client: "
392
 
                  "File name: %s\n", result->file_name);
 
411
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
393
412
        }
394
413
        gpgme_recipient_t recipient;
395
414
        recipient = result->recipients;
396
415
        while(recipient != NULL){
397
 
          fprintf(stderr, "Mandos plugin mandos-client: "
398
 
                  "Public key algorithm: %s\n",
399
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
400
 
          fprintf(stderr, "Mandos plugin mandos-client: "
401
 
                  "Key ID: %s\n", recipient->keyid);
402
 
          fprintf(stderr, "Mandos plugin mandos-client: "
403
 
                  "Secret key available: %s\n",
404
 
                  recipient->status == GPG_ERR_NO_SECKEY
405
 
                  ? "No" : "Yes");
 
416
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
417
                       gpgme_pubkey_algo_name
 
418
                       (recipient->pubkey_algo));
 
419
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
420
          fprintf_plus(stderr, "Secret key available: %s\n",
 
421
                       recipient->status == GPG_ERR_NO_SECKEY
 
422
                       ? "No" : "Yes");
406
423
          recipient = recipient->next;
407
424
        }
408
425
      }
411
428
  }
412
429
  
413
430
  if(debug){
414
 
    fprintf(stderr, "Mandos plugin mandos-client: "
415
 
            "Decryption of OpenPGP data succeeded\n");
 
431
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
416
432
  }
417
433
  
418
434
  /* Seek back to the beginning of the GPGME plaintext data buffer */
449
465
  }
450
466
  
451
467
  if(debug){
452
 
    fprintf(stderr, "Mandos plugin mandos-client: "
453
 
            "Decrypted password is: ");
 
468
    fprintf_plus(stderr, "Decrypted password is: ");
454
469
    for(ssize_t i = 0; i < plaintext_length; i++){
455
470
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
456
471
    }
467
482
  return plaintext_length;
468
483
}
469
484
 
470
 
static const char * safer_gnutls_strerror(int value){
471
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
472
 
                                               -Wunreachable-code */
 
485
__attribute__((warn_unused_result))
 
486
static const char *safer_gnutls_strerror(int value){
 
487
  const char *ret = gnutls_strerror(value);
473
488
  if(ret == NULL)
474
489
    ret = "(unknown)";
475
490
  return ret;
476
491
}
477
492
 
478
493
/* GnuTLS log function callback */
 
494
__attribute__((nonnull))
479
495
static void debuggnutls(__attribute__((unused)) int level,
480
496
                        const char* string){
481
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
497
  fprintf_plus(stderr, "GnuTLS: %s", string);
482
498
}
483
499
 
 
500
__attribute__((nonnull, warn_unused_result))
484
501
static int init_gnutls_global(const char *pubkeyfilename,
485
 
                              const char *seckeyfilename){
 
502
                              const char *seckeyfilename,
 
503
                              mandos_context *mc){
486
504
  int ret;
487
505
  
488
506
  if(debug){
489
 
    fprintf(stderr, "Mandos plugin mandos-client: "
490
 
            "Initializing GnuTLS\n");
 
507
    fprintf_plus(stderr, "Initializing GnuTLS\n");
491
508
  }
492
509
  
493
510
  ret = gnutls_global_init();
494
511
  if(ret != GNUTLS_E_SUCCESS){
495
 
    fprintf(stderr, "Mandos plugin mandos-client: "
496
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
512
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
513
                 safer_gnutls_strerror(ret));
497
514
    return -1;
498
515
  }
499
516
  
506
523
  }
507
524
  
508
525
  /* OpenPGP credentials */
509
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
526
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
510
527
  if(ret != GNUTLS_E_SUCCESS){
511
 
    fprintf(stderr, "Mandos plugin mandos-client: "
512
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
528
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
529
                 safer_gnutls_strerror(ret));
513
530
    gnutls_global_deinit();
514
531
    return -1;
515
532
  }
516
533
  
517
534
  if(debug){
518
 
    fprintf(stderr, "Mandos plugin mandos-client: "
519
 
            "Attempting to use OpenPGP public key %s and"
520
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
521
 
            seckeyfilename);
 
535
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
536
                 " secret key %s as GnuTLS credentials\n",
 
537
                 pubkeyfilename,
 
538
                 seckeyfilename);
522
539
  }
523
540
  
524
541
  ret = gnutls_certificate_set_openpgp_key_file
525
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
542
    (mc->cred, pubkeyfilename, seckeyfilename,
526
543
     GNUTLS_OPENPGP_FMT_BASE64);
527
544
  if(ret != GNUTLS_E_SUCCESS){
528
 
    fprintf(stderr,
529
 
            "Mandos plugin mandos-client: "
530
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
531
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
532
 
    fprintf(stderr, "Mandos plugin mandos-client: "
533
 
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
 
545
    fprintf_plus(stderr,
 
546
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
547
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
548
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
549
                 safer_gnutls_strerror(ret));
534
550
    goto globalfail;
535
551
  }
536
552
  
537
553
  /* GnuTLS server initialization */
538
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
554
  ret = gnutls_dh_params_init(&mc->dh_params);
539
555
  if(ret != GNUTLS_E_SUCCESS){
540
 
    fprintf(stderr, "Mandos plugin mandos-client: "
541
 
            "Error in GnuTLS DH parameter initialization:"
542
 
            " %s\n", safer_gnutls_strerror(ret));
 
556
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
557
                 " initialization: %s\n",
 
558
                 safer_gnutls_strerror(ret));
543
559
    goto globalfail;
544
560
  }
545
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
561
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
546
562
  if(ret != GNUTLS_E_SUCCESS){
547
 
    fprintf(stderr, "Mandos plugin mandos-client: "
548
 
            "Error in GnuTLS prime generation: %s\n",
549
 
            safer_gnutls_strerror(ret));
 
563
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
564
                 safer_gnutls_strerror(ret));
550
565
    goto globalfail;
551
566
  }
552
567
  
553
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
568
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
554
569
  
555
570
  return 0;
556
571
  
557
572
 globalfail:
558
573
  
559
 
  gnutls_certificate_free_credentials(mc.cred);
 
574
  gnutls_certificate_free_credentials(mc->cred);
560
575
  gnutls_global_deinit();
561
 
  gnutls_dh_params_deinit(mc.dh_params);
 
576
  gnutls_dh_params_deinit(mc->dh_params);
562
577
  return -1;
563
578
}
564
579
 
565
 
static int init_gnutls_session(gnutls_session_t *session){
 
580
__attribute__((nonnull, warn_unused_result))
 
581
static int init_gnutls_session(gnutls_session_t *session,
 
582
                               mandos_context *mc){
566
583
  int ret;
567
584
  /* GnuTLS session creation */
568
585
  do {
572
589
    }
573
590
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
574
591
  if(ret != GNUTLS_E_SUCCESS){
575
 
    fprintf(stderr, "Mandos plugin mandos-client: "
576
 
            "Error in GnuTLS session initialization: %s\n",
577
 
            safer_gnutls_strerror(ret));
 
592
    fprintf_plus(stderr,
 
593
                 "Error in GnuTLS session initialization: %s\n",
 
594
                 safer_gnutls_strerror(ret));
578
595
  }
579
596
  
580
597
  {
581
598
    const char *err;
582
599
    do {
583
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
600
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
584
601
      if(quit_now){
585
602
        gnutls_deinit(*session);
586
603
        return -1;
587
604
      }
588
605
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
589
606
    if(ret != GNUTLS_E_SUCCESS){
590
 
      fprintf(stderr, "Mandos plugin mandos-client: "
591
 
              "Syntax error at: %s\n", err);
592
 
      fprintf(stderr, "Mandos plugin mandos-client: "
593
 
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
 
607
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
608
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
609
                   safer_gnutls_strerror(ret));
594
610
      gnutls_deinit(*session);
595
611
      return -1;
596
612
    }
598
614
  
599
615
  do {
600
616
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
601
 
                                 mc.cred);
 
617
                                 mc->cred);
602
618
    if(quit_now){
603
619
      gnutls_deinit(*session);
604
620
      return -1;
605
621
    }
606
622
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
607
623
  if(ret != GNUTLS_E_SUCCESS){
608
 
    fprintf(stderr, "Mandos plugin mandos-client: "
609
 
            "Error setting GnuTLS credentials: %s\n",
610
 
            safer_gnutls_strerror(ret));
 
624
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
625
                 safer_gnutls_strerror(ret));
611
626
    gnutls_deinit(*session);
612
627
    return -1;
613
628
  }
615
630
  /* ignore client certificate if any. */
616
631
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
617
632
  
618
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
633
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
619
634
  
620
635
  return 0;
621
636
}
625
640
                      __attribute__((unused)) const char *txt){}
626
641
 
627
642
/* Called when a Mandos server is found */
628
 
static int start_mandos_communication(const char *ip, uint16_t port,
 
643
__attribute__((nonnull, warn_unused_result))
 
644
static int start_mandos_communication(const char *ip, in_port_t port,
629
645
                                      AvahiIfIndex if_index,
630
 
                                      int af){
 
646
                                      int af, mandos_context *mc){
631
647
  int ret, tcp_sd = -1;
632
648
  ssize_t sret;
633
 
  union {
634
 
    struct sockaddr_in in;
635
 
    struct sockaddr_in6 in6;
636
 
  } to;
 
649
  struct sockaddr_storage to;
637
650
  char *buffer = NULL;
638
651
  char *decrypted_buffer = NULL;
639
652
  size_t buffer_length = 0;
658
671
    pf = PF_INET;
659
672
    break;
660
673
  default:
661
 
    fprintf(stderr, "Mandos plugin mandos-client: "
662
 
            "Bad address family: %d\n", af);
 
674
    fprintf_plus(stderr, "Bad address family: %d\n", af);
663
675
    errno = EINVAL;
664
676
    return -1;
665
677
  }
666
678
  
667
 
  ret = init_gnutls_session(&session);
 
679
  /* If the interface is specified and we have a list of interfaces */
 
680
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
 
681
    /* Check if the interface is one of the interfaces we are using */
 
682
    bool match = false;
 
683
    {
 
684
      char *interface = NULL;
 
685
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
686
                                 interface))){
 
687
        if(if_nametoindex(interface) == (unsigned int)if_index){
 
688
          match = true;
 
689
          break;
 
690
        }
 
691
      }
 
692
    }
 
693
    if(not match){
 
694
      /* This interface does not match any in the list, so we don't
 
695
         connect to the server */
 
696
      if(debug){
 
697
        char interface[IF_NAMESIZE];
 
698
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
699
          perror_plus("if_indextoname");
 
700
        } else {
 
701
          fprintf_plus(stderr, "Skipping server on non-used interface"
 
702
                       " \"%s\"\n",
 
703
                       if_indextoname((unsigned int)if_index,
 
704
                                      interface));
 
705
        }
 
706
      }
 
707
      return -1;
 
708
    }
 
709
  }
 
710
  
 
711
  ret = init_gnutls_session(&session, mc);
668
712
  if(ret != 0){
669
713
    return -1;
670
714
  }
671
715
  
672
716
  if(debug){
673
 
    fprintf(stderr, "Mandos plugin mandos-client: "
674
 
            "Setting up a TCP connection to %s, port %" PRIu16
675
 
            "\n", ip, port);
 
717
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
718
                 PRIuMAX "\n", ip, (uintmax_t)port);
676
719
  }
677
720
  
678
721
  tcp_sd = socket(pf, SOCK_STREAM, 0);
690
733
  
691
734
  memset(&to, 0, sizeof(to));
692
735
  if(af == AF_INET6){
693
 
    to.in6.sin6_family = (sa_family_t)af;
694
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
736
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
737
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
695
738
  } else {                      /* IPv4 */
696
 
    to.in.sin_family = (sa_family_t)af;
697
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
739
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
740
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
698
741
  }
699
742
  if(ret < 0 ){
700
743
    int e = errno;
704
747
  }
705
748
  if(ret == 0){
706
749
    int e = errno;
707
 
    fprintf(stderr, "Mandos plugin mandos-client: "
708
 
            "Bad address: %s\n", ip);
 
750
    fprintf_plus(stderr, "Bad address: %s\n", ip);
709
751
    errno = e;
710
752
    goto mandos_end;
711
753
  }
712
754
  if(af == AF_INET6){
713
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
714
 
                                       -Wconversion and
715
 
                                       -Wunreachable-code */
716
 
    
717
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
718
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
719
 
                                -Wunreachable-code*/
 
755
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
 
756
    if(IN6_IS_ADDR_LINKLOCAL
 
757
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
720
758
      if(if_index == AVAHI_IF_UNSPEC){
721
 
        fprintf(stderr, "Mandos plugin mandos-client: "
722
 
                "An IPv6 link-local address is incomplete"
723
 
                " without a network interface\n");
 
759
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
760
                     " incomplete without a network interface\n");
724
761
        errno = EINVAL;
725
762
        goto mandos_end;
726
763
      }
727
764
      /* Set the network interface number as scope */
728
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
765
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
729
766
    }
730
767
  } else {
731
 
    to.in.sin_port = htons(port); /* Spurious warnings from
732
 
                                     -Wconversion and
733
 
                                     -Wunreachable-code */
 
768
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
734
769
  }
735
770
  
736
771
  if(quit_now){
744
779
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
745
780
        perror_plus("if_indextoname");
746
781
      } else {
747
 
        fprintf(stderr, "Mandos plugin mandos-client: "
748
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
749
 
                ip, interface, port);
 
782
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
783
                     "\n", ip, interface, (uintmax_t)port);
750
784
      }
751
785
    } else {
752
 
      fprintf(stderr, "Mandos plugin mandos-client: "
753
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
786
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
787
                   ip, (uintmax_t)port);
754
788
    }
755
789
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
756
790
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
757
 
    const char *pcret;
758
791
    if(af == AF_INET6){
759
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
760
 
                        sizeof(addrstr));
 
792
      ret = getnameinfo((struct sockaddr *)&to,
 
793
                        sizeof(struct sockaddr_in6),
 
794
                        addrstr, sizeof(addrstr), NULL, 0,
 
795
                        NI_NUMERICHOST);
761
796
    } else {
762
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
763
 
                        sizeof(addrstr));
 
797
      ret = getnameinfo((struct sockaddr *)&to,
 
798
                        sizeof(struct sockaddr_in),
 
799
                        addrstr, sizeof(addrstr), NULL, 0,
 
800
                        NI_NUMERICHOST);
764
801
    }
765
 
    if(pcret == NULL){
766
 
      perror_plus("inet_ntop");
767
 
    } else {
768
 
      if(strcmp(addrstr, ip) != 0){
769
 
        fprintf(stderr, "Mandos plugin mandos-client: "
770
 
                "Canonical address form: %s\n", addrstr);
771
 
      }
 
802
    if(ret == EAI_SYSTEM){
 
803
      perror_plus("getnameinfo");
 
804
    } else if(ret != 0) {
 
805
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
 
806
    } else if(strcmp(addrstr, ip) != 0){
 
807
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
772
808
    }
773
809
  }
774
810
  
778
814
  }
779
815
  
780
816
  if(af == AF_INET6){
781
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
817
    ret = connect(tcp_sd, (struct sockaddr *)&to,
 
818
                  sizeof(struct sockaddr_in6));
782
819
  } else {
783
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
820
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
821
                  sizeof(struct sockaddr_in));
784
822
  }
785
823
  if(ret < 0){
786
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
824
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
787
825
      int e = errno;
788
826
      perror_plus("connect");
789
827
      errno = e;
827
865
  }
828
866
  
829
867
  if(debug){
830
 
    fprintf(stderr, "Mandos plugin mandos-client: "
831
 
            "Establishing TLS session with %s\n", ip);
 
868
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
832
869
  }
833
870
  
834
871
  if(quit_now){
836
873
    goto mandos_end;
837
874
  }
838
875
  
839
 
  /* Spurious warning from -Wint-to-pointer-cast */
840
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
876
  /* This casting via intptr_t is to eliminate warning about casting
 
877
     an int to a pointer type.  This is exactly how the GnuTLS Guile
 
878
     function "set-session-transport-fd!" does it. */
 
879
  gnutls_transport_set_ptr(session,
 
880
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
841
881
  
842
882
  if(quit_now){
843
883
    errno = EINTR;
854
894
  
855
895
  if(ret != GNUTLS_E_SUCCESS){
856
896
    if(debug){
857
 
      fprintf(stderr, "Mandos plugin mandos-client: "
858
 
              "*** GnuTLS Handshake failed ***\n");
 
897
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
859
898
      gnutls_perror(ret);
860
899
    }
861
900
    errno = EPROTO;
865
904
  /* Read OpenPGP packet that contains the wanted password */
866
905
  
867
906
  if(debug){
868
 
    fprintf(stderr, "Mandos plugin mandos-client: "
869
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
907
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
908
                 " %s\n", ip);
870
909
  }
871
910
  
872
911
  while(true){
910
949
          }
911
950
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
912
951
        if(ret < 0){
913
 
          fprintf(stderr, "Mandos plugin mandos-client: "
914
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
952
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
953
                       "***\n");
915
954
          gnutls_perror(ret);
916
955
          errno = EPROTO;
917
956
          goto mandos_end;
918
957
        }
919
958
        break;
920
959
      default:
921
 
        fprintf(stderr, "Mandos plugin mandos-client: "
922
 
                "Unknown error while reading data from"
923
 
                " encrypted session with Mandos server\n");
 
960
        fprintf_plus(stderr, "Unknown error while reading data from"
 
961
                     " encrypted session with Mandos server\n");
924
962
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
925
963
        errno = EIO;
926
964
        goto mandos_end;
931
969
  }
932
970
  
933
971
  if(debug){
934
 
    fprintf(stderr, "Mandos plugin mandos-client: "
935
 
            "Closing TLS session\n");
 
972
    fprintf_plus(stderr, "Closing TLS session\n");
936
973
  }
937
974
  
938
975
  if(quit_now){
951
988
  if(buffer_length > 0){
952
989
    ssize_t decrypted_buffer_size;
953
990
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
954
 
                                               &decrypted_buffer);
 
991
                                               &decrypted_buffer, mc);
955
992
    if(decrypted_buffer_size >= 0){
956
993
      
957
994
      written = 0;
967
1004
        if(ret == 0 and ferror(stdout)){
968
1005
          int e = errno;
969
1006
          if(debug){
970
 
            fprintf(stderr, "Mandos plugin mandos-client: "
971
 
                    "Error writing encrypted data: %s\n",
972
 
                    strerror(errno));
 
1007
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
1008
                         strerror(errno));
973
1009
          }
974
1010
          errno = e;
975
1011
          goto mandos_end;
1006
1042
  return retval;
1007
1043
}
1008
1044
 
 
1045
__attribute__((nonnull))
1009
1046
static void resolve_callback(AvahiSServiceResolver *r,
1010
1047
                             AvahiIfIndex interface,
1011
1048
                             AvahiProtocol proto,
1019
1056
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1020
1057
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1021
1058
                             flags,
1022
 
                             AVAHI_GCC_UNUSED void* userdata){
1023
 
  assert(r);
 
1059
                             void *mc){
 
1060
  if(r == NULL){
 
1061
    return;
 
1062
  }
1024
1063
  
1025
1064
  /* Called whenever a service has been resolved successfully or
1026
1065
     timed out */
1032
1071
  switch(event){
1033
1072
  default:
1034
1073
  case AVAHI_RESOLVER_FAILURE:
1035
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1036
 
            "(Avahi Resolver) Failed to resolve service '%s'"
1037
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1038
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1074
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1075
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1076
                 domain,
 
1077
                 avahi_strerror(avahi_server_errno
 
1078
                                (((mandos_context*)mc)->server)));
1039
1079
    break;
1040
1080
    
1041
1081
  case AVAHI_RESOLVER_FOUND:
1043
1083
      char ip[AVAHI_ADDRESS_STR_MAX];
1044
1084
      avahi_address_snprint(ip, sizeof(ip), address);
1045
1085
      if(debug){
1046
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1047
 
                "Mandos server \"%s\" found on %s (%s, %"
1048
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1049
 
                ip, (intmax_t)interface, port);
 
1086
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1087
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1088
                     host_name, ip, (intmax_t)interface, port);
1050
1089
      }
1051
 
      int ret = start_mandos_communication(ip, port, interface,
1052
 
                                           avahi_proto_to_af(proto));
 
1090
      int ret = start_mandos_communication(ip, (in_port_t)port,
 
1091
                                           interface,
 
1092
                                           avahi_proto_to_af(proto),
 
1093
                                           mc);
1053
1094
      if(ret == 0){
1054
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1095
        avahi_simple_poll_quit(simple_poll);
1055
1096
      } else {
1056
 
        ret = add_server(ip, port, interface,
1057
 
                         avahi_proto_to_af(proto));
 
1097
        if(not add_server(ip, (in_port_t)port, interface,
 
1098
                          avahi_proto_to_af(proto),
 
1099
                          &((mandos_context*)mc)->current_server)){
 
1100
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1101
                       " list\n", name);
 
1102
        }
1058
1103
      }
1059
1104
    }
1060
1105
  }
1070
1115
                            const char *domain,
1071
1116
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1072
1117
                            flags,
1073
 
                            AVAHI_GCC_UNUSED void* userdata){
1074
 
  assert(b);
 
1118
                            void *mc){
 
1119
  if(b == NULL){
 
1120
    return;
 
1121
  }
1075
1122
  
1076
1123
  /* Called whenever a new services becomes available on the LAN or
1077
1124
     is removed from the LAN */
1084
1131
  default:
1085
1132
  case AVAHI_BROWSER_FAILURE:
1086
1133
    
1087
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1088
 
            "(Avahi browser) %s\n",
1089
 
            avahi_strerror(avahi_server_errno(mc.server)));
1090
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1134
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1135
                 avahi_strerror(avahi_server_errno
 
1136
                                (((mandos_context*)mc)->server)));
 
1137
    avahi_simple_poll_quit(simple_poll);
1091
1138
    return;
1092
1139
    
1093
1140
  case AVAHI_BROWSER_NEW:
1096
1143
       the callback function is called the Avahi server will free the
1097
1144
       resolver for us. */
1098
1145
    
1099
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1100
 
                                    name, type, domain, protocol, 0,
1101
 
                                    resolve_callback, NULL) == NULL)
1102
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1103
 
              "Avahi: Failed to resolve service '%s': %s\n",
1104
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1146
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
 
1147
                                    interface, protocol, name, type,
 
1148
                                    domain, protocol, 0,
 
1149
                                    resolve_callback, mc) == NULL)
 
1150
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1151
                   " %s\n", name,
 
1152
                   avahi_strerror(avahi_server_errno
 
1153
                                  (((mandos_context*)mc)->server)));
1105
1154
    break;
1106
1155
    
1107
1156
  case AVAHI_BROWSER_REMOVE:
1110
1159
  case AVAHI_BROWSER_ALL_FOR_NOW:
1111
1160
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1112
1161
    if(debug){
1113
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1114
 
              "No Mandos server found, still searching...\n");
 
1162
      fprintf_plus(stderr, "No Mandos server found, still"
 
1163
                   " searching...\n");
1115
1164
    }
1116
1165
    break;
1117
1166
  }
1126
1175
  signal_received = sig;
1127
1176
  int old_errno = errno;
1128
1177
  /* set main loop to exit */
1129
 
  if(mc.simple_poll != NULL){
1130
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1178
  if(simple_poll != NULL){
 
1179
    avahi_simple_poll_quit(simple_poll);
1131
1180
  }
1132
1181
  errno = old_errno;
1133
1182
}
1134
1183
 
 
1184
__attribute__((nonnull, warn_unused_result))
1135
1185
bool get_flags(const char *ifname, struct ifreq *ifr){
1136
1186
  int ret;
 
1187
  error_t ret_errno;
1137
1188
  
1138
1189
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1139
1190
  if(s < 0){
 
1191
    ret_errno = errno;
1140
1192
    perror_plus("socket");
 
1193
    errno = ret_errno;
1141
1194
    return false;
1142
1195
  }
1143
1196
  strcpy(ifr->ifr_name, ifname);
1144
1197
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1145
1198
  if(ret == -1){
1146
1199
    if(debug){
 
1200
      ret_errno = errno;
1147
1201
      perror_plus("ioctl SIOCGIFFLAGS");
 
1202
      errno = ret_errno;
1148
1203
    }
1149
1204
    return false;
1150
1205
  }
1151
1206
  return true;
1152
1207
}
1153
1208
 
 
1209
__attribute__((nonnull, warn_unused_result))
1154
1210
bool good_flags(const char *ifname, const struct ifreq *ifr){
1155
1211
  
1156
1212
  /* Reject the loopback device */
1157
1213
  if(ifr->ifr_flags & IFF_LOOPBACK){
1158
1214
    if(debug){
1159
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1160
 
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1215
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1216
                   ifname);
1161
1217
    }
1162
1218
    return false;
1163
1219
  }
1164
1220
  /* Accept point-to-point devices only if connect_to is specified */
1165
1221
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1166
1222
    if(debug){
1167
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1168
 
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1223
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1224
                   " \"%s\"\n", ifname);
1169
1225
    }
1170
1226
    return true;
1171
1227
  }
1172
1228
  /* Otherwise, reject non-broadcast-capable devices */
1173
1229
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1174
1230
    if(debug){
1175
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1176
 
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1231
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1232
                   " \"%s\"\n", ifname);
1177
1233
    }
1178
1234
    return false;
1179
1235
  }
1180
1236
  /* Reject non-ARP interfaces (including dummy interfaces) */
1181
1237
  if(ifr->ifr_flags & IFF_NOARP){
1182
1238
    if(debug){
1183
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1184
 
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1239
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1240
                   ifname);
1185
1241
    }
1186
1242
    return false;
1187
1243
  }
1188
1244
  
1189
1245
  /* Accept this device */
1190
1246
  if(debug){
1191
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1192
 
            "Interface \"%s\" is good\n", ifname);
 
1247
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1193
1248
  }
1194
1249
  return true;
1195
1250
}
1199
1254
 * corresponds to an acceptable network device.
1200
1255
 * (This function is passed to scandir(3) as a filter function.)
1201
1256
 */
 
1257
__attribute__((nonnull, warn_unused_result))
1202
1258
int good_interface(const struct dirent *if_entry){
1203
1259
  if(if_entry->d_name[0] == '.'){
1204
1260
    return 0;
1207
1263
  struct ifreq ifr;
1208
1264
  if(not get_flags(if_entry->d_name, &ifr)){
1209
1265
    if(debug){
1210
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1211
 
              "Failed to get flags for interface \"%s\"\n",
1212
 
              if_entry->d_name);
1213
 
    }
1214
 
    return 0;
1215
 
  }
1216
 
  
1217
 
  if(not good_flags(if_entry->d_name, &ifr)){
1218
 
    return 0;
1219
 
  }
1220
 
  return 1;
1221
 
}
1222
 
 
1223
 
/* 
1224
 
 * This function determines if a directory entry in /sys/class/net
1225
 
 * corresponds to an acceptable network device which is up.
1226
 
 * (This function is passed to scandir(3) as a filter function.)
1227
 
 */
1228
 
int up_interface(const struct dirent *if_entry){
1229
 
  if(if_entry->d_name[0] == '.'){
1230
 
    return 0;
1231
 
  }
1232
 
  
1233
 
  struct ifreq ifr;
1234
 
  if(not get_flags(if_entry->d_name, &ifr)){
1235
 
    if(debug){
1236
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1237
 
              "Failed to get flags for interface \"%s\"\n",
1238
 
              if_entry->d_name);
1239
 
    }
1240
 
    return 0;
1241
 
  }
1242
 
  
1243
 
  /* Reject down interfaces */
1244
 
  if(not (ifr.ifr_flags & IFF_UP)){
1245
 
    if(debug){
1246
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1247
 
              "Rejecting down interface \"%s\"\n",
1248
 
              if_entry->d_name);
1249
 
    }
1250
 
    return 0;
1251
 
  }
1252
 
  
1253
 
  /* Reject non-running interfaces */
1254
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1255
 
    if(debug){
1256
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1257
 
              "Rejecting non-running interface \"%s\"\n",
1258
 
              if_entry->d_name);
1259
 
    }
1260
 
    return 0;
1261
 
  }
1262
 
  
1263
 
  if(not good_flags(if_entry->d_name, &ifr)){
1264
 
    return 0;
1265
 
  }
1266
 
  return 1;
1267
 
}
1268
 
 
 
1266
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1267
                   "\"%s\"\n", if_entry->d_name);
 
1268
    }
 
1269
    return 0;
 
1270
  }
 
1271
  
 
1272
  if(not good_flags(if_entry->d_name, &ifr)){
 
1273
    return 0;
 
1274
  }
 
1275
  return 1;
 
1276
}
 
1277
 
 
1278
/* 
 
1279
 * This function determines if a network interface is up.
 
1280
 */
 
1281
__attribute__((nonnull, warn_unused_result))
 
1282
bool interface_is_up(const char *interface){
 
1283
  struct ifreq ifr;
 
1284
  if(not get_flags(interface, &ifr)){
 
1285
    if(debug){
 
1286
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1287
                   "\"%s\"\n", interface);
 
1288
    }
 
1289
    return false;
 
1290
  }
 
1291
  
 
1292
  return (bool)(ifr.ifr_flags & IFF_UP);
 
1293
}
 
1294
 
 
1295
/* 
 
1296
 * This function determines if a network interface is running
 
1297
 */
 
1298
__attribute__((nonnull, warn_unused_result))
 
1299
bool interface_is_running(const char *interface){
 
1300
  struct ifreq ifr;
 
1301
  if(not get_flags(interface, &ifr)){
 
1302
    if(debug){
 
1303
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1304
                   "\"%s\"\n", interface);
 
1305
    }
 
1306
    return false;
 
1307
  }
 
1308
  
 
1309
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
 
1310
}
 
1311
 
 
1312
__attribute__((nonnull, pure, warn_unused_result))
1269
1313
int notdotentries(const struct dirent *direntry){
1270
1314
  /* Skip "." and ".." */
1271
1315
  if(direntry->d_name[0] == '.'
1278
1322
}
1279
1323
 
1280
1324
/* Is this directory entry a runnable program? */
 
1325
__attribute__((nonnull, warn_unused_result))
1281
1326
int runnable_hook(const struct dirent *direntry){
1282
1327
  int ret;
1283
1328
  size_t sret;
1291
1336
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1292
1337
                "abcdefghijklmnopqrstuvwxyz"
1293
1338
                "0123456789"
1294
 
                "_-");
 
1339
                "_.-");
1295
1340
  if((direntry->d_name)[sret] != '\0'){
1296
1341
    /* Contains non-allowed characters */
1297
1342
    if(debug){
1298
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1299
 
              "Ignoring hook \"%s\" with bad name\n",
1300
 
              direntry->d_name);
 
1343
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1344
                   direntry->d_name);
1301
1345
    }
1302
1346
    return 0;
1303
1347
  }
1304
1348
  
1305
 
  char *fullname = NULL;
1306
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1307
 
  if(ret < 0){
1308
 
    perror_plus("asprintf");
1309
 
    return 0;
1310
 
  }
1311
 
  
1312
 
  ret = stat(fullname, &st);
 
1349
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
1313
1350
  if(ret == -1){
1314
1351
    if(debug){
1315
1352
      perror_plus("Could not stat hook");
1319
1356
  if(not (S_ISREG(st.st_mode))){
1320
1357
    /* Not a regular file */
1321
1358
    if(debug){
1322
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1323
 
              "Ignoring hook \"%s\" - not a file\n",
1324
 
              direntry->d_name);
 
1359
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1360
                   direntry->d_name);
1325
1361
    }
1326
1362
    return 0;
1327
1363
  }
1328
1364
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1329
1365
    /* Not executable */
1330
1366
    if(debug){
1331
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1332
 
              "Ignoring hook \"%s\" - not executable\n",
1333
 
              direntry->d_name);
 
1367
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1368
                   direntry->d_name);
1334
1369
    }
1335
1370
    return 0;
1336
1371
  }
 
1372
  if(debug){
 
1373
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1374
                 direntry->d_name);
 
1375
  }
1337
1376
  return 1;
1338
1377
}
1339
1378
 
1340
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1379
__attribute__((nonnull, warn_unused_result))
 
1380
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
 
1381
                            mandos_context *mc){
1341
1382
  int ret;
1342
1383
  struct timespec now;
1343
1384
  struct timespec waited_time;
1344
1385
  intmax_t block_time;
1345
1386
  
1346
1387
  while(true){
1347
 
    if(mc.current_server == NULL){
1348
 
      if (debug){
1349
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1350
 
                "Wait until first server is found. No timeout!\n");
 
1388
    if(mc->current_server == NULL){
 
1389
      if(debug){
 
1390
        fprintf_plus(stderr, "Wait until first server is found."
 
1391
                     " No timeout!\n");
1351
1392
      }
1352
1393
      ret = avahi_simple_poll_iterate(s, -1);
1353
1394
    } else {
1354
 
      if (debug){
1355
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1356
 
                "Check current_server if we should run it,"
1357
 
                " or wait\n");
 
1395
      if(debug){
 
1396
        fprintf_plus(stderr, "Check current_server if we should run"
 
1397
                     " it, or wait\n");
1358
1398
      }
1359
1399
      /* the current time */
1360
1400
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1365
1405
      /* Calculating in ms how long time between now and server
1366
1406
         who we visted longest time ago. Now - last seen.  */
1367
1407
      waited_time.tv_sec = (now.tv_sec
1368
 
                            - mc.current_server->last_seen.tv_sec);
 
1408
                            - mc->current_server->last_seen.tv_sec);
1369
1409
      waited_time.tv_nsec = (now.tv_nsec
1370
 
                             - mc.current_server->last_seen.tv_nsec);
 
1410
                             - mc->current_server->last_seen.tv_nsec);
1371
1411
      /* total time is 10s/10,000ms.
1372
1412
         Converting to s from ms by dividing by 1,000,
1373
1413
         and ns to ms by dividing by 1,000,000. */
1375
1415
                     - ((intmax_t)waited_time.tv_sec * 1000))
1376
1416
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1377
1417
      
1378
 
      if (debug){
1379
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1380
 
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1418
      if(debug){
 
1419
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1420
                     block_time);
1381
1421
      }
1382
1422
      
1383
1423
      if(block_time <= 0){
1384
 
        ret = start_mandos_communication(mc.current_server->ip,
1385
 
                                         mc.current_server->port,
1386
 
                                         mc.current_server->if_index,
1387
 
                                         mc.current_server->af);
 
1424
        ret = start_mandos_communication(mc->current_server->ip,
 
1425
                                         mc->current_server->port,
 
1426
                                         mc->current_server->if_index,
 
1427
                                         mc->current_server->af, mc);
1388
1428
        if(ret == 0){
1389
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1429
          avahi_simple_poll_quit(s);
1390
1430
          return 0;
1391
1431
        }
1392
1432
        ret = clock_gettime(CLOCK_MONOTONIC,
1393
 
                            &mc.current_server->last_seen);
 
1433
                            &mc->current_server->last_seen);
1394
1434
        if(ret == -1){
1395
1435
          perror_plus("clock_gettime");
1396
1436
          return -1;
1397
1437
        }
1398
 
        mc.current_server = mc.current_server->next;
 
1438
        mc->current_server = mc->current_server->next;
1399
1439
        block_time = 0;         /* Call avahi to find new Mandos
1400
1440
                                   servers, but don't block */
1401
1441
      }
1403
1443
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1404
1444
    }
1405
1445
    if(ret != 0){
1406
 
      if (ret > 0 or errno != EINTR){
 
1446
      if(ret > 0 or errno != EINTR){
1407
1447
        return (ret != 1) ? ret : 0;
1408
1448
      }
1409
1449
    }
1410
1450
  }
1411
1451
}
1412
1452
 
 
1453
/* Set effective uid to 0, return errno */
 
1454
__attribute__((warn_unused_result))
 
1455
error_t raise_privileges(void){
 
1456
  error_t old_errno = errno;
 
1457
  error_t ret_errno = 0;
 
1458
  if(seteuid(0) == -1){
 
1459
    ret_errno = errno;
 
1460
    perror_plus("seteuid");
 
1461
  }
 
1462
  errno = old_errno;
 
1463
  return ret_errno;
 
1464
}
 
1465
 
 
1466
/* Set effective and real user ID to 0.  Return errno. */
 
1467
__attribute__((warn_unused_result))
 
1468
error_t raise_privileges_permanently(void){
 
1469
  error_t old_errno = errno;
 
1470
  error_t ret_errno = raise_privileges();
 
1471
  if(ret_errno != 0){
 
1472
    errno = old_errno;
 
1473
    return ret_errno;
 
1474
  }
 
1475
  if(setuid(0) == -1){
 
1476
    ret_errno = errno;
 
1477
    perror_plus("seteuid");
 
1478
  }
 
1479
  errno = old_errno;
 
1480
  return ret_errno;
 
1481
}
 
1482
 
 
1483
/* Set effective user ID to unprivileged saved user ID */
 
1484
__attribute__((warn_unused_result))
 
1485
error_t lower_privileges(void){
 
1486
  error_t old_errno = errno;
 
1487
  error_t ret_errno = 0;
 
1488
  if(seteuid(uid) == -1){
 
1489
    ret_errno = errno;
 
1490
    perror_plus("seteuid");
 
1491
  }
 
1492
  errno = old_errno;
 
1493
  return ret_errno;
 
1494
}
 
1495
 
 
1496
/* Lower privileges permanently */
 
1497
__attribute__((warn_unused_result))
 
1498
error_t lower_privileges_permanently(void){
 
1499
  error_t old_errno = errno;
 
1500
  error_t ret_errno = 0;
 
1501
  if(setuid(uid) == -1){
 
1502
    ret_errno = errno;
 
1503
    perror_plus("setuid");
 
1504
  }
 
1505
  errno = old_errno;
 
1506
  return ret_errno;
 
1507
}
 
1508
 
 
1509
#ifndef O_CLOEXEC
 
1510
/*
 
1511
 * Based on the example in the GNU LibC manual chapter 13.13 "File
 
1512
 * Descriptor Flags".
 
1513
 | [[info:libc:Descriptor%20Flags][File Descriptor Flags]] |
 
1514
 */
 
1515
__attribute__((warn_unused_result))
 
1516
static int set_cloexec_flag(int fd){
 
1517
  int ret = (int)TEMP_FAILURE_RETRY(fcntl(fd, F_GETFD, 0));
 
1518
  /* If reading the flags failed, return error indication now. */
 
1519
  if(ret < 0){
 
1520
    return ret;
 
1521
  }
 
1522
  /* Store modified flag word in the descriptor. */
 
1523
  return (int)TEMP_FAILURE_RETRY(fcntl(fd, F_SETFD,
 
1524
                                       ret | FD_CLOEXEC));
 
1525
}
 
1526
#endif  /* not O_CLOEXEC */
 
1527
 
 
1528
__attribute__((nonnull))
 
1529
void run_network_hooks(const char *mode, const char *interface,
 
1530
                       const float delay){
 
1531
  struct dirent **direntries;
 
1532
  if(hookdir_fd == -1){
 
1533
    hookdir_fd = open(hookdir, O_RDONLY |
 
1534
#ifdef O_CLOEXEC
 
1535
                      O_CLOEXEC
 
1536
#else  /* not O_CLOEXEC */
 
1537
                      0
 
1538
#endif  /* not O_CLOEXEC */
 
1539
                      );
 
1540
    if(hookdir_fd == -1){
 
1541
      if(errno == ENOENT){
 
1542
        if(debug){
 
1543
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1544
                       " found\n", hookdir);
 
1545
        }
 
1546
      } else {
 
1547
        perror_plus("open");
 
1548
      }
 
1549
      return;
 
1550
    }
 
1551
#ifndef O_CLOEXEC
 
1552
    if(set_cloexec_flag(hookdir_fd) < 0){
 
1553
      perror_plus("set_cloexec_flag");
 
1554
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1555
        perror_plus("close");
 
1556
      } else {
 
1557
        hookdir_fd = -1;
 
1558
      }
 
1559
      return;
 
1560
    }
 
1561
#endif  /* not O_CLOEXEC */
 
1562
  }
 
1563
#ifdef __GLIBC__
 
1564
#if __GLIBC_PREREQ(2, 15)
 
1565
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
 
1566
                           runnable_hook, alphasort);
 
1567
#else  /* not __GLIBC_PREREQ(2, 15) */
 
1568
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1569
                         alphasort);
 
1570
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
1571
#else   /* not __GLIBC__ */
 
1572
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1573
                         alphasort);
 
1574
#endif  /* not __GLIBC__ */
 
1575
  if(numhooks == -1){
 
1576
    perror_plus("scandir");
 
1577
    return;
 
1578
  }
 
1579
  struct dirent *direntry;
 
1580
  int ret;
 
1581
  int devnull = open("/dev/null", O_RDONLY);
 
1582
  for(int i = 0; i < numhooks; i++){
 
1583
    direntry = direntries[i];
 
1584
    if(debug){
 
1585
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1586
                   direntry->d_name);
 
1587
    }
 
1588
    pid_t hook_pid = fork();
 
1589
    if(hook_pid == 0){
 
1590
      /* Child */
 
1591
      /* Raise privileges */
 
1592
      if(raise_privileges_permanently() != 0){
 
1593
        perror_plus("Failed to raise privileges");
 
1594
        _exit(EX_NOPERM);
 
1595
      }
 
1596
      /* Set group */
 
1597
      errno = 0;
 
1598
      ret = setgid(0);
 
1599
      if(ret == -1){
 
1600
        perror_plus("setgid");
 
1601
        _exit(EX_NOPERM);
 
1602
      }
 
1603
      /* Reset supplementary groups */
 
1604
      errno = 0;
 
1605
      ret = setgroups(0, NULL);
 
1606
      if(ret == -1){
 
1607
        perror_plus("setgroups");
 
1608
        _exit(EX_NOPERM);
 
1609
      }
 
1610
      ret = dup2(devnull, STDIN_FILENO);
 
1611
      if(ret == -1){
 
1612
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
1613
        _exit(EX_OSERR);
 
1614
      }
 
1615
      ret = close(devnull);
 
1616
      if(ret == -1){
 
1617
        perror_plus("close");
 
1618
        _exit(EX_OSERR);
 
1619
      }
 
1620
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
1621
      if(ret == -1){
 
1622
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
1623
        _exit(EX_OSERR);
 
1624
      }
 
1625
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1626
      if(ret == -1){
 
1627
        perror_plus("setenv");
 
1628
        _exit(EX_OSERR);
 
1629
      }
 
1630
      ret = setenv("DEVICE", interface, 1);
 
1631
      if(ret == -1){
 
1632
        perror_plus("setenv");
 
1633
        _exit(EX_OSERR);
 
1634
      }
 
1635
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1636
      if(ret == -1){
 
1637
        perror_plus("setenv");
 
1638
        _exit(EX_OSERR);
 
1639
      }
 
1640
      ret = setenv("MODE", mode, 1);
 
1641
      if(ret == -1){
 
1642
        perror_plus("setenv");
 
1643
        _exit(EX_OSERR);
 
1644
      }
 
1645
      char *delaystring;
 
1646
      ret = asprintf(&delaystring, "%f", (double)delay);
 
1647
      if(ret == -1){
 
1648
        perror_plus("asprintf");
 
1649
        _exit(EX_OSERR);
 
1650
      }
 
1651
      ret = setenv("DELAY", delaystring, 1);
 
1652
      if(ret == -1){
 
1653
        free(delaystring);
 
1654
        perror_plus("setenv");
 
1655
        _exit(EX_OSERR);
 
1656
      }
 
1657
      free(delaystring);
 
1658
      if(connect_to != NULL){
 
1659
        ret = setenv("CONNECT", connect_to, 1);
 
1660
        if(ret == -1){
 
1661
          perror_plus("setenv");
 
1662
          _exit(EX_OSERR);
 
1663
        }
 
1664
      }
 
1665
      if(fexecve(hookdir_fd, (char *const [])
 
1666
                 { direntry->d_name, NULL }, environ) == -1){
 
1667
        perror_plus("fexecve");
 
1668
        _exit(EXIT_FAILURE);
 
1669
      }
 
1670
    } else {
 
1671
      int status;
 
1672
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1673
        perror_plus("waitpid");
 
1674
        continue;
 
1675
      }
 
1676
      if(WIFEXITED(status)){
 
1677
        if(WEXITSTATUS(status) != 0){
 
1678
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1679
                       " with status %d\n", direntry->d_name,
 
1680
                       WEXITSTATUS(status));
 
1681
          continue;
 
1682
        }
 
1683
      } else if(WIFSIGNALED(status)){
 
1684
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1685
                     " signal %d\n", direntry->d_name,
 
1686
                     WTERMSIG(status));
 
1687
        continue;
 
1688
      } else {
 
1689
        fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1690
                     " crashed\n", direntry->d_name);
 
1691
        continue;
 
1692
      }
 
1693
    }
 
1694
    if(debug){
 
1695
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1696
                   direntry->d_name);
 
1697
    }
 
1698
  }
 
1699
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1700
    perror_plus("close");
 
1701
  } else {
 
1702
    hookdir_fd = -1;
 
1703
  }
 
1704
  close(devnull);
 
1705
}
 
1706
 
 
1707
__attribute__((nonnull, warn_unused_result))
 
1708
error_t bring_up_interface(const char *const interface,
 
1709
                           const float delay){
 
1710
  error_t old_errno = errno;
 
1711
  int ret;
 
1712
  struct ifreq network;
 
1713
  unsigned int if_index = if_nametoindex(interface);
 
1714
  if(if_index == 0){
 
1715
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1716
    errno = old_errno;
 
1717
    return ENXIO;
 
1718
  }
 
1719
  
 
1720
  if(quit_now){
 
1721
    errno = old_errno;
 
1722
    return EINTR;
 
1723
  }
 
1724
  
 
1725
  if(not interface_is_up(interface)){
 
1726
    error_t ret_errno = 0, ioctl_errno = 0;
 
1727
    if(not get_flags(interface, &network)){
 
1728
      ret_errno = errno;
 
1729
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1730
                   "\"%s\"\n", interface);
 
1731
      errno = old_errno;
 
1732
      return ret_errno;
 
1733
    }
 
1734
    network.ifr_flags |= IFF_UP; /* set flag */
 
1735
    
 
1736
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1737
    if(sd == -1){
 
1738
      ret_errno = errno;
 
1739
      perror_plus("socket");
 
1740
      errno = old_errno;
 
1741
      return ret_errno;
 
1742
    }
 
1743
    
 
1744
    if(quit_now){
 
1745
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1746
      if(ret == -1){
 
1747
        perror_plus("close");
 
1748
      }
 
1749
      errno = old_errno;
 
1750
      return EINTR;
 
1751
    }
 
1752
    
 
1753
    if(debug){
 
1754
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
 
1755
                   interface);
 
1756
    }
 
1757
    
 
1758
    /* Raise privileges */
 
1759
    ret_errno = raise_privileges();
 
1760
    if(ret_errno != 0){
 
1761
      perror_plus("Failed to raise privileges");
 
1762
    }
 
1763
    
 
1764
#ifdef __linux__
 
1765
    int ret_linux;
 
1766
    bool restore_loglevel = false;
 
1767
    if(ret_errno == 0){
 
1768
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1769
         messages about the network interface to mess up the prompt */
 
1770
      ret_linux = klogctl(8, NULL, 5);
 
1771
      if(ret_linux == -1){
 
1772
        perror_plus("klogctl");
 
1773
      } else {
 
1774
        restore_loglevel = true;
 
1775
      }
 
1776
    }
 
1777
#endif  /* __linux__ */
 
1778
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1779
    ioctl_errno = errno;
 
1780
#ifdef __linux__
 
1781
    if(restore_loglevel){
 
1782
      ret_linux = klogctl(7, NULL, 0);
 
1783
      if(ret_linux == -1){
 
1784
        perror_plus("klogctl");
 
1785
      }
 
1786
    }
 
1787
#endif  /* __linux__ */
 
1788
    
 
1789
    /* If raise_privileges() succeeded above */
 
1790
    if(ret_errno == 0){
 
1791
      /* Lower privileges */
 
1792
      ret_errno = lower_privileges();
 
1793
      if(ret_errno != 0){
 
1794
        errno = ret_errno;
 
1795
        perror_plus("Failed to lower privileges");
 
1796
      }
 
1797
    }
 
1798
    
 
1799
    /* Close the socket */
 
1800
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1801
    if(ret == -1){
 
1802
      perror_plus("close");
 
1803
    }
 
1804
    
 
1805
    if(ret_setflags == -1){
 
1806
      errno = ioctl_errno;
 
1807
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1808
      errno = old_errno;
 
1809
      return ioctl_errno;
 
1810
    }
 
1811
  } else if(debug){
 
1812
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
 
1813
                 interface);
 
1814
  }
 
1815
  
 
1816
  /* Sleep checking until interface is running.
 
1817
     Check every 0.25s, up to total time of delay */
 
1818
  for(int i=0; i < delay * 4; i++){
 
1819
    if(interface_is_running(interface)){
 
1820
      break;
 
1821
    }
 
1822
    struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1823
    ret = nanosleep(&sleeptime, NULL);
 
1824
    if(ret == -1 and errno != EINTR){
 
1825
      perror_plus("nanosleep");
 
1826
    }
 
1827
  }
 
1828
  
 
1829
  errno = old_errno;
 
1830
  return 0;
 
1831
}
 
1832
 
 
1833
__attribute__((nonnull, warn_unused_result))
 
1834
error_t take_down_interface(const char *const interface){
 
1835
  error_t old_errno = errno;
 
1836
  struct ifreq network;
 
1837
  unsigned int if_index = if_nametoindex(interface);
 
1838
  if(if_index == 0){
 
1839
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1840
    errno = old_errno;
 
1841
    return ENXIO;
 
1842
  }
 
1843
  if(interface_is_up(interface)){
 
1844
    error_t ret_errno = 0, ioctl_errno = 0;
 
1845
    if(not get_flags(interface, &network) and debug){
 
1846
      ret_errno = errno;
 
1847
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1848
                   "\"%s\"\n", interface);
 
1849
      errno = old_errno;
 
1850
      return ret_errno;
 
1851
    }
 
1852
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1853
    
 
1854
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1855
    if(sd == -1){
 
1856
      ret_errno = errno;
 
1857
      perror_plus("socket");
 
1858
      errno = old_errno;
 
1859
      return ret_errno;
 
1860
    }
 
1861
    
 
1862
    if(debug){
 
1863
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
 
1864
                   interface);
 
1865
    }
 
1866
    
 
1867
    /* Raise privileges */
 
1868
    ret_errno = raise_privileges();
 
1869
    if(ret_errno != 0){
 
1870
      perror_plus("Failed to raise privileges");
 
1871
    }
 
1872
    
 
1873
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1874
    ioctl_errno = errno;
 
1875
    
 
1876
    /* If raise_privileges() succeeded above */
 
1877
    if(ret_errno == 0){
 
1878
      /* Lower privileges */
 
1879
      ret_errno = lower_privileges();
 
1880
      if(ret_errno != 0){
 
1881
        errno = ret_errno;
 
1882
        perror_plus("Failed to lower privileges");
 
1883
      }
 
1884
    }
 
1885
    
 
1886
    /* Close the socket */
 
1887
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1888
    if(ret == -1){
 
1889
      perror_plus("close");
 
1890
    }
 
1891
    
 
1892
    if(ret_setflags == -1){
 
1893
      errno = ioctl_errno;
 
1894
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1895
      errno = old_errno;
 
1896
      return ioctl_errno;
 
1897
    }
 
1898
  } else if(debug){
 
1899
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
 
1900
                 interface);
 
1901
  }
 
1902
  
 
1903
  errno = old_errno;
 
1904
  return 0;
 
1905
}
 
1906
 
1413
1907
int main(int argc, char *argv[]){
 
1908
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1909
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1910
                        "+CTYPE-OPENPGP", .current_server = NULL,
 
1911
                        .interfaces = NULL, .interfaces_size = 0 };
1414
1912
  AvahiSServiceBrowser *sb = NULL;
1415
 
  int error;
 
1913
  error_t ret_errno;
1416
1914
  int ret;
1417
1915
  intmax_t tmpmax;
1418
1916
  char *tmp;
1419
1917
  int exitcode = EXIT_SUCCESS;
1420
 
  const char *interface = "";
1421
 
  struct ifreq network;
1422
 
  int sd = -1;
1423
 
  bool take_down_interface = false;
1424
 
  uid_t uid;
1425
 
  gid_t gid;
1426
 
  char tempdir[] = "/tmp/mandosXXXXXX";
1427
 
  bool tempdir_created = false;
 
1918
  char *interfaces_to_take_down = NULL;
 
1919
  size_t interfaces_to_take_down_size = 0;
 
1920
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
 
1921
  char old_tempdir[] = "/tmp/mandosXXXXXX";
 
1922
  char *tempdir = NULL;
1428
1923
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1429
1924
  const char *seckey = PATHDIR "/" SECKEY;
1430
1925
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1926
  char *interfaces_hooks = NULL;
1431
1927
  
1432
1928
  bool gnutls_initialized = false;
1433
1929
  bool gpgme_initialized = false;
1495
1991
        .group = 2 },
1496
1992
      { .name = "retry", .key = 132,
1497
1993
        .arg = "SECONDS",
1498
 
        .doc = "Retry interval used when denied by the mandos server",
 
1994
        .doc = "Retry interval used when denied by the Mandos server",
1499
1995
        .group = 2 },
1500
1996
      { .name = "network-hook-dir", .key = 133,
1501
1997
        .arg = "DIR",
1524
2020
        connect_to = arg;
1525
2021
        break;
1526
2022
      case 'i':                 /* --interface */
1527
 
        interface = arg;
 
2023
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
 
2024
                                 arg, (int)',');
 
2025
        if(ret_errno != 0){
 
2026
          argp_error(state, "%s", strerror(ret_errno));
 
2027
        }
1528
2028
        break;
1529
2029
      case 's':                 /* --seckey */
1530
2030
        seckey = arg;
1573
2073
        argp_state_help(state, state->out_stream,
1574
2074
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1575
2075
      case 'V':                 /* --version */
1576
 
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1577
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
2076
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1578
2077
        exit(argp_err_exit_status);
1579
2078
        break;
1580
2079
      default:
1607
2106
  {
1608
2107
    /* Work around Debian bug #633582:
1609
2108
       <http://bugs.debian.org/633582> */
1610
 
    struct stat st;
1611
 
    
1612
 
    /* Re-raise priviliges */
1613
 
    errno = 0;
1614
 
    ret = seteuid(0);
1615
 
    if(ret == -1){
1616
 
      perror_plus("seteuid");
1617
 
    }
1618
 
    
1619
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1620
 
      int seckey_fd = open(seckey, O_RDONLY);
1621
 
      if(seckey_fd == -1){
1622
 
        perror_plus("open");
1623
 
      } else {
1624
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1625
 
        if(ret == -1){
1626
 
          perror_plus("fstat");
1627
 
        } else {
1628
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1629
 
            ret = fchown(seckey_fd, uid, gid);
1630
 
            if(ret == -1){
1631
 
              perror_plus("fchown");
1632
 
            }
1633
 
          }
1634
 
        }
1635
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1636
 
      }
1637
 
    }
1638
 
    
1639
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1640
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1641
 
      if(pubkey_fd == -1){
1642
 
        perror_plus("open");
1643
 
      } else {
1644
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1645
 
        if(ret == -1){
1646
 
          perror_plus("fstat");
1647
 
        } else {
1648
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1649
 
            ret = fchown(pubkey_fd, uid, gid);
1650
 
            if(ret == -1){
1651
 
              perror_plus("fchown");
1652
 
            }
1653
 
          }
1654
 
        }
1655
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1656
 
      }
1657
 
    }
1658
 
    
1659
 
    /* Lower privileges */
1660
 
    errno = 0;
1661
 
    ret = seteuid(uid);
1662
 
    if(ret == -1){
1663
 
      perror_plus("seteuid");
1664
 
    }
1665
 
  }
1666
 
  
1667
 
  /* Find network hooks and run them */
1668
 
  {
1669
 
    struct dirent **direntries;
1670
 
    struct dirent *direntry;
1671
 
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
1672
 
                           alphasort);
1673
 
    if(numhooks == -1){
1674
 
      perror_plus("scandir");
 
2109
    
 
2110
    /* Re-raise privileges */
 
2111
    ret_errno = raise_privileges();
 
2112
    if(ret_errno != 0){
 
2113
      errno = ret_errno;
 
2114
      perror_plus("Failed to raise privileges");
1675
2115
    } else {
1676
 
      int devnull = open("/dev/null", O_RDONLY);
1677
 
      for(int i = 0; i < numhooks; i++){
1678
 
        direntry = direntries[0];
1679
 
        char *fullname = NULL;
1680
 
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1681
 
        if(ret < 0){
1682
 
          perror_plus("asprintf");
1683
 
          continue;
1684
 
        }
1685
 
        pid_t hook_pid = fork();
1686
 
        if(hook_pid == 0){
1687
 
          /* Child */
1688
 
          dup2(devnull, STDIN_FILENO);
1689
 
          close(devnull);
1690
 
          dup2(STDERR_FILENO, STDOUT_FILENO);
1691
 
          ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1692
 
          if(ret == -1){
1693
 
            perror_plus("setenv");
1694
 
            exit(1);
1695
 
          }
1696
 
          ret = setenv("DEVICE", interface, 1);
1697
 
          if(ret == -1){
1698
 
            perror_plus("setenv");
1699
 
            exit(1);
1700
 
          }
1701
 
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1702
 
          if(ret == -1){
1703
 
            perror_plus("setenv");
1704
 
            exit(1);
1705
 
          }
1706
 
          ret = setenv("MODE", "start", 1);
1707
 
          if(ret == -1){
1708
 
            perror_plus("setenv");
1709
 
            exit(1);
1710
 
          }
1711
 
          char *delaystring;
1712
 
          ret = asprintf(&delaystring, "%f", delay);
1713
 
          if(ret == -1){
1714
 
            perror_plus("asprintf");
1715
 
            exit(1);
1716
 
          }
1717
 
          ret = setenv("DELAY", delaystring, 1);
1718
 
          if(ret == -1){
1719
 
            free(delaystring);
1720
 
            perror_plus("setenv");
1721
 
            exit(1);
1722
 
          }
1723
 
          free(delaystring);
1724
 
          ret = execl(fullname, direntry->d_name, "start", NULL);
1725
 
          perror_plus("execl");
1726
 
        } else {
1727
 
          int status;
1728
 
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1729
 
            perror_plus("waitpid");
1730
 
            free(fullname);
1731
 
            continue;
1732
 
          }
1733
 
          if(WIFEXITED(status)){
1734
 
            if(WEXITSTATUS(status) != 0){
1735
 
              fprintf(stderr, "Mandos plugin mandos-client: "
1736
 
                      "Warning: network hook \"%s\" exited"
1737
 
                      " with status %d\n", direntry->d_name,
1738
 
                      WEXITSTATUS(status));
1739
 
              free(fullname);
1740
 
              continue;
1741
 
            }
1742
 
          } else if(WIFSIGNALED(status)){
1743
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1744
 
                    "Warning: network hook \"%s\" died by"
1745
 
                    " signal %d\n", direntry->d_name,
1746
 
                    WTERMSIG(status));
1747
 
            free(fullname);
1748
 
            continue;
1749
 
          } else {
1750
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1751
 
                    "Warning: network hook \"%s\" crashed\n",
1752
 
                    direntry->d_name);
1753
 
            free(fullname);
1754
 
            continue;
1755
 
          }
1756
 
        }
1757
 
        free(fullname);
1758
 
        if(quit_now){
1759
 
          goto end;
1760
 
        }
1761
 
      }
1762
 
      close(devnull);
1763
 
    }
 
2116
      struct stat st;
 
2117
      
 
2118
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
2119
        int seckey_fd = open(seckey, O_RDONLY);
 
2120
        if(seckey_fd == -1){
 
2121
          perror_plus("open");
 
2122
        } else {
 
2123
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
2124
          if(ret == -1){
 
2125
            perror_plus("fstat");
 
2126
          } else {
 
2127
            if(S_ISREG(st.st_mode)
 
2128
               and st.st_uid == 0 and st.st_gid == 0){
 
2129
              ret = fchown(seckey_fd, uid, gid);
 
2130
              if(ret == -1){
 
2131
                perror_plus("fchown");
 
2132
              }
 
2133
            }
 
2134
          }
 
2135
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2136
        }
 
2137
      }
 
2138
    
 
2139
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
2140
        int pubkey_fd = open(pubkey, O_RDONLY);
 
2141
        if(pubkey_fd == -1){
 
2142
          perror_plus("open");
 
2143
        } else {
 
2144
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
2145
          if(ret == -1){
 
2146
            perror_plus("fstat");
 
2147
          } else {
 
2148
            if(S_ISREG(st.st_mode)
 
2149
               and st.st_uid == 0 and st.st_gid == 0){
 
2150
              ret = fchown(pubkey_fd, uid, gid);
 
2151
              if(ret == -1){
 
2152
                perror_plus("fchown");
 
2153
              }
 
2154
            }
 
2155
          }
 
2156
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2157
        }
 
2158
      }
 
2159
    
 
2160
      /* Lower privileges */
 
2161
      ret_errno = lower_privileges();
 
2162
      if(ret_errno != 0){
 
2163
        errno = ret_errno;
 
2164
        perror_plus("Failed to lower privileges");
 
2165
      }
 
2166
    }
 
2167
  }
 
2168
  
 
2169
  /* Remove invalid interface names (except "none") */
 
2170
  {
 
2171
    char *interface = NULL;
 
2172
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2173
                                 interface))){
 
2174
      if(strcmp(interface, "none") != 0
 
2175
         and if_nametoindex(interface) == 0){
 
2176
        if(interface[0] != '\0'){
 
2177
          fprintf_plus(stderr, "Not using nonexisting interface"
 
2178
                       " \"%s\"\n", interface);
 
2179
        }
 
2180
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2181
        interface = NULL;
 
2182
      }
 
2183
    }
 
2184
  }
 
2185
  
 
2186
  /* Run network hooks */
 
2187
  {
 
2188
    if(mc.interfaces != NULL){
 
2189
      interfaces_hooks = malloc(mc.interfaces_size);
 
2190
      if(interfaces_hooks == NULL){
 
2191
        perror_plus("malloc");
 
2192
        goto end;
 
2193
      }
 
2194
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
 
2195
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
 
2196
    }
 
2197
    run_network_hooks("start", interfaces_hooks != NULL ?
 
2198
                      interfaces_hooks : "", delay);
1764
2199
  }
1765
2200
  
1766
2201
  if(not debug){
1767
2202
    avahi_set_log_function(empty_log);
1768
2203
  }
1769
2204
  
1770
 
  if(interface[0] == '\0'){
1771
 
    struct dirent **direntries;
1772
 
    /* First look for interfaces that are up */
1773
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1774
 
                  alphasort);
1775
 
    if(ret == 0){
1776
 
      /* No up interfaces, look for any good interfaces */
1777
 
      free(direntries);
1778
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1779
 
                    alphasort);
1780
 
    }
1781
 
    if(ret >= 1){
1782
 
      /* Pick the first interface returned */
1783
 
      interface = strdup(direntries[0]->d_name);
1784
 
      if(debug){
1785
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1786
 
                "Using interface \"%s\"\n", interface);
1787
 
      }
1788
 
      if(interface == NULL){
1789
 
        perror_plus("malloc");
1790
 
        free(direntries);
1791
 
        exitcode = EXIT_FAILURE;
1792
 
        goto end;
1793
 
      }
1794
 
      free(direntries);
1795
 
    } else {
1796
 
      free(direntries);
1797
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1798
 
              "Could not find a network interface\n");
1799
 
      exitcode = EXIT_FAILURE;
1800
 
      goto end;
1801
 
    }
1802
 
  }
1803
 
  
1804
2205
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1805
2206
     from the signal handler */
1806
2207
  /* Initialize the pseudo-RNG for Avahi */
1807
2208
  srand((unsigned int) time(NULL));
1808
 
  mc.simple_poll = avahi_simple_poll_new();
1809
 
  if(mc.simple_poll == NULL){
1810
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1811
 
            "Avahi: Failed to create simple poll object.\n");
 
2209
  simple_poll = avahi_simple_poll_new();
 
2210
  if(simple_poll == NULL){
 
2211
    fprintf_plus(stderr,
 
2212
                 "Avahi: Failed to create simple poll object.\n");
1812
2213
    exitcode = EX_UNAVAILABLE;
1813
2214
    goto end;
1814
2215
  }
1876
2277
    }
1877
2278
  }
1878
2279
  
1879
 
  /* If the interface is down, bring it up */
1880
 
  if(strcmp(interface, "none") != 0){
1881
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1882
 
    if(if_index == 0){
1883
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1884
 
              "No such interface: \"%s\"\n", interface);
1885
 
      exitcode = EX_UNAVAILABLE;
1886
 
      goto end;
1887
 
    }
1888
 
    
1889
 
    if(quit_now){
1890
 
      goto end;
1891
 
    }
1892
 
    
1893
 
    /* Re-raise priviliges */
1894
 
    errno = 0;
1895
 
    ret = seteuid(0);
1896
 
    if(ret == -1){
1897
 
      perror_plus("seteuid");
1898
 
    }
1899
 
    
1900
 
#ifdef __linux__
1901
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1902
 
       messages about the network interface to mess up the prompt */
1903
 
    ret = klogctl(8, NULL, 5);
1904
 
    bool restore_loglevel = true;
1905
 
    if(ret == -1){
1906
 
      restore_loglevel = false;
1907
 
      perror_plus("klogctl");
1908
 
    }
1909
 
#endif  /* __linux__ */
1910
 
    
1911
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1912
 
    if(sd < 0){
1913
 
      perror_plus("socket");
1914
 
      exitcode = EX_OSERR;
1915
 
#ifdef __linux__
1916
 
      if(restore_loglevel){
1917
 
        ret = klogctl(7, NULL, 0);
1918
 
        if(ret == -1){
1919
 
          perror_plus("klogctl");
1920
 
        }
1921
 
      }
1922
 
#endif  /* __linux__ */
1923
 
      /* Lower privileges */
1924
 
      errno = 0;
1925
 
      ret = seteuid(uid);
1926
 
      if(ret == -1){
1927
 
        perror_plus("seteuid");
1928
 
      }
1929
 
      goto end;
1930
 
    }
1931
 
    strcpy(network.ifr_name, interface);
1932
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1933
 
    if(ret == -1){
1934
 
      perror_plus("ioctl SIOCGIFFLAGS");
1935
 
#ifdef __linux__
1936
 
      if(restore_loglevel){
1937
 
        ret = klogctl(7, NULL, 0);
1938
 
        if(ret == -1){
1939
 
          perror_plus("klogctl");
1940
 
        }
1941
 
      }
1942
 
#endif  /* __linux__ */
1943
 
      exitcode = EX_OSERR;
1944
 
      /* Lower privileges */
1945
 
      errno = 0;
1946
 
      ret = seteuid(uid);
1947
 
      if(ret == -1){
1948
 
        perror_plus("seteuid");
1949
 
      }
1950
 
      goto end;
1951
 
    }
1952
 
    if((network.ifr_flags & IFF_UP) == 0){
1953
 
      network.ifr_flags |= IFF_UP;
1954
 
      take_down_interface = true;
1955
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1956
 
      if(ret == -1){
1957
 
        take_down_interface = false;
1958
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1959
 
        exitcode = EX_OSERR;
1960
 
#ifdef __linux__
1961
 
        if(restore_loglevel){
1962
 
          ret = klogctl(7, NULL, 0);
1963
 
          if(ret == -1){
1964
 
            perror_plus("klogctl");
 
2280
  /* If no interfaces were specified, make a list */
 
2281
  if(mc.interfaces == NULL){
 
2282
    struct dirent **direntries;
 
2283
    /* Look for any good interfaces */
 
2284
    ret = scandir(sys_class_net, &direntries, good_interface,
 
2285
                  alphasort);
 
2286
    if(ret >= 1){
 
2287
      /* Add all found interfaces to interfaces list */
 
2288
      for(int i = 0; i < ret; ++i){
 
2289
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2290
                             direntries[i]->d_name);
 
2291
        if(ret_errno != 0){
 
2292
          errno = ret_errno;
 
2293
          perror_plus("argz_add");
 
2294
          continue;
 
2295
        }
 
2296
        if(debug){
 
2297
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
 
2298
                       direntries[i]->d_name);
 
2299
        }
 
2300
      }
 
2301
      free(direntries);
 
2302
    } else {
 
2303
      free(direntries);
 
2304
      fprintf_plus(stderr, "Could not find a network interface\n");
 
2305
      exitcode = EXIT_FAILURE;
 
2306
      goto end;
 
2307
    }
 
2308
  }
 
2309
  
 
2310
  /* Bring up interfaces which are down, and remove any "none"s */
 
2311
  {
 
2312
    char *interface = NULL;
 
2313
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2314
                                 interface))){
 
2315
      /* If interface name is "none", stop bringing up interfaces.
 
2316
         Also remove all instances of "none" from the list */
 
2317
      if(strcmp(interface, "none") == 0){
 
2318
        argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2319
                    interface);
 
2320
        interface = NULL;
 
2321
        while((interface = argz_next(mc.interfaces,
 
2322
                                     mc.interfaces_size, interface))){
 
2323
          if(strcmp(interface, "none") == 0){
 
2324
            argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2325
                        interface);
 
2326
            interface = NULL;
1965
2327
          }
1966
2328
        }
1967
 
#endif  /* __linux__ */
1968
 
        /* Lower privileges */
1969
 
        errno = 0;
1970
 
        ret = seteuid(uid);
1971
 
        if(ret == -1){
1972
 
          perror_plus("seteuid");
1973
 
        }
1974
 
        goto end;
1975
 
      }
1976
 
    }
1977
 
    /* Sleep checking until interface is running.
1978
 
       Check every 0.25s, up to total time of delay */
1979
 
    for(int i=0; i < delay * 4; i++){
1980
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1981
 
      if(ret == -1){
1982
 
        perror_plus("ioctl SIOCGIFFLAGS");
1983
 
      } else if(network.ifr_flags & IFF_RUNNING){
1984
2329
        break;
1985
2330
      }
1986
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1987
 
      ret = nanosleep(&sleeptime, NULL);
1988
 
      if(ret == -1 and errno != EINTR){
1989
 
        perror_plus("nanosleep");
1990
 
      }
1991
 
    }
1992
 
    if(not take_down_interface){
1993
 
      /* We won't need the socket anymore */
1994
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1995
 
      if(ret == -1){
1996
 
        perror_plus("close");
1997
 
      }
1998
 
    }
1999
 
#ifdef __linux__
2000
 
    if(restore_loglevel){
2001
 
      /* Restores kernel loglevel to default */
2002
 
      ret = klogctl(7, NULL, 0);
2003
 
      if(ret == -1){
2004
 
        perror_plus("klogctl");
2005
 
      }
2006
 
    }
2007
 
#endif  /* __linux__ */
2008
 
    /* Lower privileges */
2009
 
    errno = 0;
2010
 
    if(take_down_interface){
2011
 
      /* Lower privileges */
2012
 
      ret = seteuid(uid);
2013
 
      if(ret == -1){
2014
 
        perror_plus("seteuid");
2015
 
      }
2016
 
    } else {
2017
 
      /* Lower privileges permanently */
2018
 
      ret = setuid(uid);
2019
 
      if(ret == -1){
2020
 
        perror_plus("setuid");
2021
 
      }
2022
 
    }
 
2331
      bool interface_was_up = interface_is_up(interface);
 
2332
      errno = bring_up_interface(interface, delay);
 
2333
      if(not interface_was_up){
 
2334
        if(errno != 0){
 
2335
          perror_plus("Failed to bring up interface");
 
2336
        } else {
 
2337
          errno = argz_add(&interfaces_to_take_down,
 
2338
                           &interfaces_to_take_down_size,
 
2339
                           interface);
 
2340
          if(errno != 0){
 
2341
            perror_plus("argz_add");
 
2342
          }
 
2343
        }
 
2344
      }
 
2345
    }
 
2346
    if(debug and (interfaces_to_take_down == NULL)){
 
2347
      fprintf_plus(stderr, "No interfaces were brought up\n");
 
2348
    }
 
2349
  }
 
2350
  
 
2351
  /* If we only got one interface, explicitly use only that one */
 
2352
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
 
2353
    if(debug){
 
2354
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2355
                   mc.interfaces);
 
2356
    }
 
2357
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
2023
2358
  }
2024
2359
  
2025
2360
  if(quit_now){
2026
2361
    goto end;
2027
2362
  }
2028
2363
  
2029
 
  ret = init_gnutls_global(pubkey, seckey);
 
2364
  ret = init_gnutls_global(pubkey, seckey, &mc);
2030
2365
  if(ret == -1){
2031
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2032
 
            "init_gnutls_global failed\n");
 
2366
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2033
2367
    exitcode = EX_UNAVAILABLE;
2034
2368
    goto end;
2035
2369
  } else {
2040
2374
    goto end;
2041
2375
  }
2042
2376
  
2043
 
  if(mkdtemp(tempdir) == NULL){
 
2377
  /* Try /run/tmp before /tmp */
 
2378
  tempdir = mkdtemp(run_tempdir);
 
2379
  if(tempdir == NULL and errno == ENOENT){
 
2380
      if(debug){
 
2381
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
 
2382
                     run_tempdir, old_tempdir);
 
2383
      }
 
2384
      tempdir = mkdtemp(old_tempdir);
 
2385
  }
 
2386
  if(tempdir == NULL){
2044
2387
    perror_plus("mkdtemp");
2045
2388
    goto end;
2046
2389
  }
2047
 
  tempdir_created = true;
2048
2390
  
2049
2391
  if(quit_now){
2050
2392
    goto end;
2051
2393
  }
2052
2394
  
2053
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
2054
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2055
 
            "init_gpgme failed\n");
 
2395
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2396
    fprintf_plus(stderr, "init_gpgme failed\n");
2056
2397
    exitcode = EX_UNAVAILABLE;
2057
2398
    goto end;
2058
2399
  } else {
2067
2408
    /* Connect directly, do not use Zeroconf */
2068
2409
    /* (Mainly meant for debugging) */
2069
2410
    char *address = strrchr(connect_to, ':');
 
2411
    
2070
2412
    if(address == NULL){
2071
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2072
 
              "No colon in address\n");
 
2413
      fprintf_plus(stderr, "No colon in address\n");
2073
2414
      exitcode = EX_USAGE;
2074
2415
      goto end;
2075
2416
    }
2078
2419
      goto end;
2079
2420
    }
2080
2421
    
2081
 
    uint16_t port;
 
2422
    in_port_t port;
2082
2423
    errno = 0;
2083
2424
    tmpmax = strtoimax(address+1, &tmp, 10);
2084
2425
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2085
 
       or tmpmax != (uint16_t)tmpmax){
2086
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2087
 
              "Bad port number\n");
 
2426
       or tmpmax != (in_port_t)tmpmax){
 
2427
      fprintf_plus(stderr, "Bad port number\n");
2088
2428
      exitcode = EX_USAGE;
2089
2429
      goto end;
2090
2430
    }
2091
 
  
 
2431
    
2092
2432
    if(quit_now){
2093
2433
      goto end;
2094
2434
    }
2095
2435
    
2096
 
    port = (uint16_t)tmpmax;
 
2436
    port = (in_port_t)tmpmax;
2097
2437
    *address = '\0';
2098
2438
    /* Colon in address indicates IPv6 */
2099
2439
    int af;
2115
2455
    }
2116
2456
    
2117
2457
    while(not quit_now){
2118
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2458
      ret = start_mandos_communication(address, port, if_index, af,
 
2459
                                       &mc);
2119
2460
      if(quit_now or ret == 0){
2120
2461
        break;
2121
2462
      }
2122
2463
      if(debug){
2123
 
        fprintf(stderr, "Mandos plugin mandos-client: "
2124
 
                "Retrying in %d seconds\n", (int)retry_interval);
 
2464
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2465
                     (int)retry_interval);
2125
2466
      }
2126
 
      sleep((int)retry_interval);
 
2467
      sleep((unsigned int)retry_interval);
2127
2468
    }
2128
2469
    
2129
 
    if (not quit_now){
 
2470
    if(not quit_now){
2130
2471
      exitcode = EXIT_SUCCESS;
2131
2472
    }
2132
2473
    
2147
2488
    config.publish_domain = 0;
2148
2489
    
2149
2490
    /* Allocate a new server */
2150
 
    mc.server = avahi_server_new(avahi_simple_poll_get
2151
 
                                 (mc.simple_poll), &config, NULL,
2152
 
                                 NULL, &error);
 
2491
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2492
                                 &config, NULL, NULL, &ret_errno);
2153
2493
    
2154
2494
    /* Free the Avahi configuration data */
2155
2495
    avahi_server_config_free(&config);
2157
2497
  
2158
2498
  /* Check if creating the Avahi server object succeeded */
2159
2499
  if(mc.server == NULL){
2160
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2161
 
            "Failed to create Avahi server: %s\n",
2162
 
            avahi_strerror(error));
 
2500
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2501
                 avahi_strerror(ret_errno));
2163
2502
    exitcode = EX_UNAVAILABLE;
2164
2503
    goto end;
2165
2504
  }
2171
2510
  /* Create the Avahi service browser */
2172
2511
  sb = avahi_s_service_browser_new(mc.server, if_index,
2173
2512
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2174
 
                                   NULL, 0, browse_callback, NULL);
 
2513
                                   NULL, 0, browse_callback,
 
2514
                                   (void *)&mc);
2175
2515
  if(sb == NULL){
2176
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2177
 
            "Failed to create service browser: %s\n",
2178
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2516
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2517
                 avahi_strerror(avahi_server_errno(mc.server)));
2179
2518
    exitcode = EX_UNAVAILABLE;
2180
2519
    goto end;
2181
2520
  }
2187
2526
  /* Run the main loop */
2188
2527
  
2189
2528
  if(debug){
2190
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2191
 
            "Starting Avahi loop search\n");
 
2529
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2192
2530
  }
2193
 
 
2194
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2195
 
                                (int)(retry_interval * 1000));
 
2531
  
 
2532
  ret = avahi_loop_with_timeout(simple_poll,
 
2533
                                (int)(retry_interval * 1000), &mc);
2196
2534
  if(debug){
2197
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2198
 
            "avahi_loop_with_timeout exited %s\n",
2199
 
            (ret == 0) ? "successfully" : "with error");
 
2535
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2536
                 (ret == 0) ? "successfully" : "with error");
2200
2537
  }
2201
2538
  
2202
2539
 end:
2203
2540
  
2204
2541
  if(debug){
2205
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2206
 
            "%s exiting\n", argv[0]);
 
2542
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2207
2543
  }
2208
2544
  
2209
2545
  /* Cleanup things */
 
2546
  free(mc.interfaces);
 
2547
  
2210
2548
  if(sb != NULL)
2211
2549
    avahi_s_service_browser_free(sb);
2212
2550
  
2213
2551
  if(mc.server != NULL)
2214
2552
    avahi_server_free(mc.server);
2215
2553
  
2216
 
  if(mc.simple_poll != NULL)
2217
 
    avahi_simple_poll_free(mc.simple_poll);
 
2554
  if(simple_poll != NULL)
 
2555
    avahi_simple_poll_free(simple_poll);
2218
2556
  
2219
2557
  if(gnutls_initialized){
2220
2558
    gnutls_certificate_free_credentials(mc.cred);
2225
2563
  if(gpgme_initialized){
2226
2564
    gpgme_release(mc.ctx);
2227
2565
  }
2228
 
 
 
2566
  
2229
2567
  /* Cleans up the circular linked list of Mandos servers the client
2230
2568
     has seen */
2231
2569
  if(mc.current_server != NULL){
2237
2575
    }
2238
2576
  }
2239
2577
  
2240
 
  /* XXX run network hooks "stop" here  */
2241
 
  
2242
 
  /* Take down the network interface */
2243
 
  if(take_down_interface){
2244
 
    /* Re-raise priviliges */
2245
 
    errno = 0;
2246
 
    ret = seteuid(0);
2247
 
    if(ret == -1){
2248
 
      perror_plus("seteuid");
 
2578
  /* Re-raise privileges */
 
2579
  {
 
2580
    ret_errno = raise_privileges();
 
2581
    if(ret_errno != 0){
 
2582
      perror_plus("Failed to raise privileges");
 
2583
    } else {
 
2584
      
 
2585
      /* Run network hooks */
 
2586
      run_network_hooks("stop", interfaces_hooks != NULL ?
 
2587
                        interfaces_hooks : "", delay);
 
2588
      
 
2589
      /* Take down the network interfaces which were brought up */
 
2590
      {
 
2591
        char *interface = NULL;
 
2592
        while((interface=argz_next(interfaces_to_take_down,
 
2593
                                   interfaces_to_take_down_size,
 
2594
                                   interface))){
 
2595
          ret_errno = take_down_interface(interface);
 
2596
          if(ret_errno != 0){
 
2597
            errno = ret_errno;
 
2598
            perror_plus("Failed to take down interface");
 
2599
          }
 
2600
        }
 
2601
        if(debug and (interfaces_to_take_down == NULL)){
 
2602
          fprintf_plus(stderr, "No interfaces needed to be taken"
 
2603
                       " down\n");
 
2604
        }
 
2605
      }
2249
2606
    }
2250
 
    if(geteuid() == 0){
2251
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2252
 
      if(ret == -1){
2253
 
        perror_plus("ioctl SIOCGIFFLAGS");
2254
 
      } else if(network.ifr_flags & IFF_UP){
2255
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2256
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2257
 
        if(ret == -1){
2258
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2259
 
        }
2260
 
      }
2261
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2262
 
      if(ret == -1){
2263
 
        perror_plus("close");
2264
 
      }
2265
 
      /* Lower privileges permanently */
2266
 
      errno = 0;
2267
 
      ret = setuid(uid);
2268
 
      if(ret == -1){
2269
 
        perror_plus("setuid");
2270
 
      }
 
2607
    
 
2608
    ret_errno = lower_privileges_permanently();
 
2609
    if(ret_errno != 0){
 
2610
      perror_plus("Failed to lower privileges permanently");
2271
2611
    }
2272
2612
  }
2273
2613
  
 
2614
  free(interfaces_to_take_down);
 
2615
  free(interfaces_hooks);
 
2616
  
2274
2617
  /* Removes the GPGME temp directory and all files inside */
2275
 
  if(tempdir_created){
 
2618
  if(tempdir != NULL){
2276
2619
    struct dirent **direntries = NULL;
2277
2620
    struct dirent *direntry = NULL;
2278
2621
    int numentries = scandir(tempdir, &direntries, notdotentries,
2279
2622
                             alphasort);
2280
 
    if (numentries > 0){
 
2623
    if(numentries > 0){
2281
2624
      for(int i = 0; i < numentries; i++){
2282
2625
        direntry = direntries[i];
2283
2626
        char *fullname = NULL;
2289
2632
        }
2290
2633
        ret = remove(fullname);
2291
2634
        if(ret == -1){
2292
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2293
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
2635
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2636
                       strerror(errno));
2294
2637
        }
2295
2638
        free(fullname);
2296
2639
      }
2297
2640
    }
2298
 
 
 
2641
    
2299
2642
    /* need to clean even if 0 because man page doesn't specify */
2300
2643
    free(direntries);
2301
 
    if (numentries == -1){
 
2644
    if(numentries == -1){
2302
2645
      perror_plus("scandir");
2303
2646
    }
2304
2647
    ret = rmdir(tempdir);