/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

* initramfs-tools-hook: Install network hooks (and any required files)
                        in the initramfs image.
* plugins.d/mandos-client.c (main): Also set MANDOSNETHOOKDIR for
                                    network hooks.
* plugins.d/mandos-client.xml (OPTIONS): Use <filename
                                         class="directory">, not
                                         <directory>.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2014 Teddy Hogeborn
13
 
 * Copyright © 2008-2014 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 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  /* not _LARGEFILE_SOURCE */
 
35
#endif
36
36
#ifndef _FILE_OFFSET_BITS
37
37
#define _FILE_OFFSET_BITS 64
38
 
#endif  /* not _FILE_OFFSET_BITS */
 
38
#endif
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, intptr_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_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(),
59
 
                                   getnameinfo() */
 
58
                                   inet_pton(), connect() */
60
59
#include <fcntl.h>              /* open() */
61
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
61
                                 */
63
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
64
63
                                   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(), _exit() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons() */
 
76
                                   setgid(), pause() */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
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() */
97
90
 
98
91
#ifdef __linux__
99
92
#include <sys/klog.h>           /* klogctl() */
141
134
static const char sys_class_net[] = "/sys/class/net";
142
135
char *connect_to = NULL;
143
136
const char *hookdir = HOOKDIR;
144
 
int hookdir_fd = -1;
145
 
uid_t uid = 65534;
146
 
gid_t gid = 65534;
147
137
 
148
138
/* Doubly linked list that need to be circularly linked when used */
149
139
typedef struct server{
150
140
  const char *ip;
151
 
  in_port_t port;
 
141
  uint16_t port;
152
142
  AvahiIfIndex if_index;
153
143
  int af;
154
144
  struct timespec last_seen;
158
148
 
159
149
/* Used for passing in values through the Avahi callback functions */
160
150
typedef struct {
 
151
  AvahiSimplePoll *simple_poll;
161
152
  AvahiServer *server;
162
153
  gnutls_certificate_credentials_t cred;
163
154
  unsigned int dh_bits;
165
156
  const char *priority;
166
157
  gpgme_ctx_t ctx;
167
158
  server *current_server;
168
 
  char *interfaces;
169
 
  size_t interfaces_size;
170
159
} mandos_context;
171
160
 
172
 
/* global so signal handler can reach it*/
173
 
AvahiSimplePoll *simple_poll;
 
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 };
174
166
 
175
167
sig_atomic_t quit_now = 0;
176
168
int signal_received = 0;
177
169
 
178
170
/* Function to use when printing errors */
179
171
void perror_plus(const char *print_text){
180
 
  int e = errno;
181
172
  fprintf(stderr, "Mandos plugin %s: ",
182
173
          program_invocation_short_name);
183
 
  errno = e;
184
174
  perror(print_text);
185
175
}
186
176
 
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
 
 
197
177
/*
198
178
 * Make additional room in "buffer" for at least BUFFER_SIZE more
199
179
 * bytes. "buffer_capacity" is how much is currently allocated,
200
180
 * "buffer_length" is how much is already used.
201
181
 */
202
 
__attribute__((nonnull, warn_unused_result))
203
182
size_t incbuffer(char **buffer, size_t buffer_length,
204
183
                 size_t buffer_capacity){
205
184
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
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;
 
185
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
186
    if(buffer == NULL){
212
187
      return 0;
213
188
    }
214
 
    *buffer = new_buf;
215
189
    buffer_capacity += BUFFER_SIZE;
216
190
  }
217
191
  return buffer_capacity;
218
192
}
219
193
 
220
194
/* Add server to set of servers to retry periodically */
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){
 
195
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
196
               int af){
224
197
  int ret;
225
198
  server *new_server = malloc(sizeof(server));
226
199
  if(new_server == NULL){
227
200
    perror_plus("malloc");
228
 
    return false;
 
201
    return -1;
229
202
  }
230
203
  *new_server = (server){ .ip = strdup(ip),
231
204
                          .port = port,
233
206
                          .af = af };
234
207
  if(new_server->ip == NULL){
235
208
    perror_plus("strdup");
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;
 
209
    return -1;
242
210
  }
243
211
  /* Special case of first server */
244
 
  if(*current_server == NULL){
 
212
  if (mc.current_server == NULL){
245
213
    new_server->next = new_server;
246
214
    new_server->prev = new_server;
247
 
    *current_server = new_server;
 
215
    mc.current_server = new_server;
 
216
  /* Place the new server last in the list */
248
217
  } else {
249
 
    /* Place the new server last in the list */
250
 
    new_server->next = *current_server;
251
 
    new_server->prev = (*current_server)->prev;
 
218
    new_server->next = mc.current_server;
 
219
    new_server->prev = mc.current_server->prev;
252
220
    new_server->prev->next = new_server;
253
 
    (*current_server)->prev = new_server;
254
 
  }
255
 
  return true;
 
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;
256
229
}
257
230
 
258
231
/* 
259
232
 * Initialize GPGME.
260
233
 */
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){
 
234
static bool init_gpgme(const char *seckey, const char *pubkey,
 
235
                       const char *tempdir){
266
236
  gpgme_error_t rc;
267
237
  gpgme_engine_info_t engine_info;
268
238
  
 
239
  
269
240
  /*
270
241
   * Helper function to insert pub and seckey to the engine keyring.
271
242
   */
272
 
  bool import_key(const char * const filename){
 
243
  bool import_key(const char *filename){
273
244
    int ret;
274
245
    int fd;
275
246
    gpgme_data_t pgp_data;
282
253
    
283
254
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
284
255
    if(rc != GPG_ERR_NO_ERROR){
285
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
286
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
256
      fprintf(stderr, "Mandos plugin mandos-client: "
 
257
              "bad gpgme_data_new_from_fd: %s: %s\n",
 
258
              gpgme_strsource(rc), gpgme_strerror(rc));
287
259
      return false;
288
260
    }
289
261
    
290
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
262
    rc = gpgme_op_import(mc.ctx, pgp_data);
291
263
    if(rc != GPG_ERR_NO_ERROR){
292
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
293
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
264
      fprintf(stderr, "Mandos plugin mandos-client: "
 
265
              "bad gpgme_op_import: %s: %s\n",
 
266
              gpgme_strsource(rc), gpgme_strerror(rc));
294
267
      return false;
295
268
    }
296
269
    
303
276
  }
304
277
  
305
278
  if(debug){
306
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
279
    fprintf(stderr, "Mandos plugin mandos-client: "
 
280
            "Initializing GPGME\n");
307
281
  }
308
282
  
309
283
  /* Init GPGME */
310
284
  gpgme_check_version(NULL);
311
285
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
312
286
  if(rc != GPG_ERR_NO_ERROR){
313
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
314
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
287
    fprintf(stderr, "Mandos plugin mandos-client: "
 
288
            "bad gpgme_engine_check_version: %s: %s\n",
 
289
            gpgme_strsource(rc), gpgme_strerror(rc));
315
290
    return false;
316
291
  }
317
292
  
318
293
  /* Set GPGME home directory for the OpenPGP engine only */
319
294
  rc = gpgme_get_engine_info(&engine_info);
320
295
  if(rc != GPG_ERR_NO_ERROR){
321
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
322
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
296
    fprintf(stderr, "Mandos plugin mandos-client: "
 
297
            "bad gpgme_get_engine_info: %s: %s\n",
 
298
            gpgme_strsource(rc), gpgme_strerror(rc));
323
299
    return false;
324
300
  }
325
301
  while(engine_info != NULL){
331
307
    engine_info = engine_info->next;
332
308
  }
333
309
  if(engine_info == NULL){
334
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
335
 
                 tempdir);
 
310
    fprintf(stderr, "Mandos plugin mandos-client: "
 
311
            "Could not set GPGME home dir to %s\n", tempdir);
336
312
    return false;
337
313
  }
338
314
  
339
315
  /* Create new GPGME "context" */
340
 
  rc = gpgme_new(&(mc->ctx));
 
316
  rc = gpgme_new(&(mc.ctx));
341
317
  if(rc != GPG_ERR_NO_ERROR){
342
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
343
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
344
 
                 gpgme_strerror(rc));
 
318
    fprintf(stderr, "Mandos plugin mandos-client: "
 
319
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
320
            gpgme_strerror(rc));
345
321
    return false;
346
322
  }
347
323
  
356
332
 * Decrypt OpenPGP data.
357
333
 * Returns -1 on error
358
334
 */
359
 
__attribute__((nonnull, warn_unused_result))
360
335
static ssize_t pgp_packet_decrypt(const char *cryptotext,
361
336
                                  size_t crypto_size,
362
 
                                  char **plaintext,
363
 
                                  mandos_context *mc){
 
337
                                  char **plaintext){
364
338
  gpgme_data_t dh_crypto, dh_plain;
365
339
  gpgme_error_t rc;
366
340
  ssize_t ret;
368
342
  ssize_t plaintext_length = 0;
369
343
  
370
344
  if(debug){
371
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
345
    fprintf(stderr, "Mandos plugin mandos-client: "
 
346
            "Trying to decrypt OpenPGP data\n");
372
347
  }
373
348
  
374
349
  /* Create new GPGME data buffer from memory cryptotext */
375
350
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
376
351
                               0);
377
352
  if(rc != GPG_ERR_NO_ERROR){
378
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
379
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
353
    fprintf(stderr, "Mandos plugin mandos-client: "
 
354
            "bad gpgme_data_new_from_mem: %s: %s\n",
 
355
            gpgme_strsource(rc), gpgme_strerror(rc));
380
356
    return -1;
381
357
  }
382
358
  
383
359
  /* Create new empty GPGME data buffer for the plaintext */
384
360
  rc = gpgme_data_new(&dh_plain);
385
361
  if(rc != GPG_ERR_NO_ERROR){
386
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
387
 
                 "bad gpgme_data_new: %s: %s\n",
388
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
362
    fprintf(stderr, "Mandos plugin mandos-client: "
 
363
            "bad gpgme_data_new: %s: %s\n",
 
364
            gpgme_strsource(rc), gpgme_strerror(rc));
389
365
    gpgme_data_release(dh_crypto);
390
366
    return -1;
391
367
  }
392
368
  
393
369
  /* Decrypt data from the cryptotext data buffer to the plaintext
394
370
     data buffer */
395
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
371
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
396
372
  if(rc != GPG_ERR_NO_ERROR){
397
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
398
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
373
    fprintf(stderr, "Mandos plugin mandos-client: "
 
374
            "bad gpgme_op_decrypt: %s: %s\n",
 
375
            gpgme_strsource(rc), gpgme_strerror(rc));
399
376
    plaintext_length = -1;
400
377
    if(debug){
401
378
      gpgme_decrypt_result_t result;
402
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
379
      result = gpgme_op_decrypt_result(mc.ctx);
403
380
      if(result == NULL){
404
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
381
        fprintf(stderr, "Mandos plugin mandos-client: "
 
382
                "gpgme_op_decrypt_result failed\n");
405
383
      } else {
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);
 
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);
410
390
        if(result->file_name != NULL){
411
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
391
          fprintf(stderr, "Mandos plugin mandos-client: "
 
392
                  "File name: %s\n", result->file_name);
412
393
        }
413
394
        gpgme_recipient_t recipient;
414
395
        recipient = result->recipients;
415
396
        while(recipient != NULL){
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");
 
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");
423
406
          recipient = recipient->next;
424
407
        }
425
408
      }
428
411
  }
429
412
  
430
413
  if(debug){
431
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
414
    fprintf(stderr, "Mandos plugin mandos-client: "
 
415
            "Decryption of OpenPGP data succeeded\n");
432
416
  }
433
417
  
434
418
  /* Seek back to the beginning of the GPGME plaintext data buffer */
465
449
  }
466
450
  
467
451
  if(debug){
468
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
452
    fprintf(stderr, "Mandos plugin mandos-client: "
 
453
            "Decrypted password is: ");
469
454
    for(ssize_t i = 0; i < plaintext_length; i++){
470
455
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
471
456
    }
482
467
  return plaintext_length;
483
468
}
484
469
 
485
 
__attribute__((warn_unused_result))
486
 
static const char *safer_gnutls_strerror(int value){
487
 
  const char *ret = gnutls_strerror(value);
 
470
static const char * safer_gnutls_strerror(int value){
 
471
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
472
                                               -Wunreachable-code */
488
473
  if(ret == NULL)
489
474
    ret = "(unknown)";
490
475
  return ret;
491
476
}
492
477
 
493
478
/* GnuTLS log function callback */
494
 
__attribute__((nonnull))
495
479
static void debuggnutls(__attribute__((unused)) int level,
496
480
                        const char* string){
497
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
481
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
498
482
}
499
483
 
500
 
__attribute__((nonnull, warn_unused_result))
501
484
static int init_gnutls_global(const char *pubkeyfilename,
502
 
                              const char *seckeyfilename,
503
 
                              mandos_context *mc){
 
485
                              const char *seckeyfilename){
504
486
  int ret;
505
487
  
506
488
  if(debug){
507
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
489
    fprintf(stderr, "Mandos plugin mandos-client: "
 
490
            "Initializing GnuTLS\n");
508
491
  }
509
492
  
510
493
  ret = gnutls_global_init();
511
494
  if(ret != GNUTLS_E_SUCCESS){
512
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
513
 
                 safer_gnutls_strerror(ret));
 
495
    fprintf(stderr, "Mandos plugin mandos-client: "
 
496
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
514
497
    return -1;
515
498
  }
516
499
  
523
506
  }
524
507
  
525
508
  /* OpenPGP credentials */
526
 
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
 
509
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
527
510
  if(ret != GNUTLS_E_SUCCESS){
528
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
529
 
                 safer_gnutls_strerror(ret));
 
511
    fprintf(stderr, "Mandos plugin mandos-client: "
 
512
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
530
513
    gnutls_global_deinit();
531
514
    return -1;
532
515
  }
533
516
  
534
517
  if(debug){
535
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
536
 
                 " secret key %s as GnuTLS credentials\n",
537
 
                 pubkeyfilename,
538
 
                 seckeyfilename);
 
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);
539
522
  }
540
523
  
541
524
  ret = gnutls_certificate_set_openpgp_key_file
542
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
525
    (mc.cred, pubkeyfilename, seckeyfilename,
543
526
     GNUTLS_OPENPGP_FMT_BASE64);
544
527
  if(ret != GNUTLS_E_SUCCESS){
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));
 
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));
550
534
    goto globalfail;
551
535
  }
552
536
  
553
537
  /* GnuTLS server initialization */
554
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
538
  ret = gnutls_dh_params_init(&mc.dh_params);
555
539
  if(ret != GNUTLS_E_SUCCESS){
556
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
557
 
                 " initialization: %s\n",
558
 
                 safer_gnutls_strerror(ret));
 
540
    fprintf(stderr, "Mandos plugin mandos-client: "
 
541
            "Error in GnuTLS DH parameter initialization:"
 
542
            " %s\n", safer_gnutls_strerror(ret));
559
543
    goto globalfail;
560
544
  }
561
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
545
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
562
546
  if(ret != GNUTLS_E_SUCCESS){
563
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
564
 
                 safer_gnutls_strerror(ret));
 
547
    fprintf(stderr, "Mandos plugin mandos-client: "
 
548
            "Error in GnuTLS prime generation: %s\n",
 
549
            safer_gnutls_strerror(ret));
565
550
    goto globalfail;
566
551
  }
567
552
  
568
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
553
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
569
554
  
570
555
  return 0;
571
556
  
572
557
 globalfail:
573
558
  
574
 
  gnutls_certificate_free_credentials(mc->cred);
 
559
  gnutls_certificate_free_credentials(mc.cred);
575
560
  gnutls_global_deinit();
576
 
  gnutls_dh_params_deinit(mc->dh_params);
 
561
  gnutls_dh_params_deinit(mc.dh_params);
577
562
  return -1;
578
563
}
579
564
 
580
 
__attribute__((nonnull, warn_unused_result))
581
 
static int init_gnutls_session(gnutls_session_t *session,
582
 
                               mandos_context *mc){
 
565
static int init_gnutls_session(gnutls_session_t *session){
583
566
  int ret;
584
567
  /* GnuTLS session creation */
585
568
  do {
589
572
    }
590
573
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
591
574
  if(ret != GNUTLS_E_SUCCESS){
592
 
    fprintf_plus(stderr,
593
 
                 "Error in GnuTLS session initialization: %s\n",
594
 
                 safer_gnutls_strerror(ret));
 
575
    fprintf(stderr, "Mandos plugin mandos-client: "
 
576
            "Error in GnuTLS session initialization: %s\n",
 
577
            safer_gnutls_strerror(ret));
595
578
  }
596
579
  
597
580
  {
598
581
    const char *err;
599
582
    do {
600
 
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
583
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
601
584
      if(quit_now){
602
585
        gnutls_deinit(*session);
603
586
        return -1;
604
587
      }
605
588
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
606
589
    if(ret != GNUTLS_E_SUCCESS){
607
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
608
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
609
 
                   safer_gnutls_strerror(ret));
 
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));
610
594
      gnutls_deinit(*session);
611
595
      return -1;
612
596
    }
614
598
  
615
599
  do {
616
600
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
617
 
                                 mc->cred);
 
601
                                 mc.cred);
618
602
    if(quit_now){
619
603
      gnutls_deinit(*session);
620
604
      return -1;
621
605
    }
622
606
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
623
607
  if(ret != GNUTLS_E_SUCCESS){
624
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
625
 
                 safer_gnutls_strerror(ret));
 
608
    fprintf(stderr, "Mandos plugin mandos-client: "
 
609
            "Error setting GnuTLS credentials: %s\n",
 
610
            safer_gnutls_strerror(ret));
626
611
    gnutls_deinit(*session);
627
612
    return -1;
628
613
  }
630
615
  /* ignore client certificate if any. */
631
616
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
632
617
  
633
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
618
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
634
619
  
635
620
  return 0;
636
621
}
640
625
                      __attribute__((unused)) const char *txt){}
641
626
 
642
627
/* Called when a Mandos server is found */
643
 
__attribute__((nonnull, warn_unused_result))
644
 
static int start_mandos_communication(const char *ip, in_port_t port,
 
628
static int start_mandos_communication(const char *ip, uint16_t port,
645
629
                                      AvahiIfIndex if_index,
646
 
                                      int af, mandos_context *mc){
 
630
                                      int af){
647
631
  int ret, tcp_sd = -1;
648
632
  ssize_t sret;
649
 
  struct sockaddr_storage to;
 
633
  union {
 
634
    struct sockaddr_in in;
 
635
    struct sockaddr_in6 in6;
 
636
  } to;
650
637
  char *buffer = NULL;
651
638
  char *decrypted_buffer = NULL;
652
639
  size_t buffer_length = 0;
671
658
    pf = PF_INET;
672
659
    break;
673
660
  default:
674
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
661
    fprintf(stderr, "Mandos plugin mandos-client: "
 
662
            "Bad address family: %d\n", af);
675
663
    errno = EINVAL;
676
664
    return -1;
677
665
  }
678
666
  
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);
 
667
  ret = init_gnutls_session(&session);
712
668
  if(ret != 0){
713
669
    return -1;
714
670
  }
715
671
  
716
672
  if(debug){
717
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
718
 
                 PRIuMAX "\n", ip, (uintmax_t)port);
 
673
    fprintf(stderr, "Mandos plugin mandos-client: "
 
674
            "Setting up a TCP connection to %s, port %" PRIu16
 
675
            "\n", ip, port);
719
676
  }
720
677
  
721
678
  tcp_sd = socket(pf, SOCK_STREAM, 0);
733
690
  
734
691
  memset(&to, 0, sizeof(to));
735
692
  if(af == AF_INET6){
736
 
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
737
 
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
 
693
    to.in6.sin6_family = (sa_family_t)af;
 
694
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
738
695
  } else {                      /* IPv4 */
739
 
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
740
 
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
 
696
    to.in.sin_family = (sa_family_t)af;
 
697
    ret = inet_pton(af, ip, &to.in.sin_addr);
741
698
  }
742
699
  if(ret < 0 ){
743
700
    int e = errno;
747
704
  }
748
705
  if(ret == 0){
749
706
    int e = errno;
750
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
707
    fprintf(stderr, "Mandos plugin mandos-client: "
 
708
            "Bad address: %s\n", ip);
751
709
    errno = e;
752
710
    goto mandos_end;
753
711
  }
754
712
  if(af == AF_INET6){
755
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
756
 
    if(IN6_IS_ADDR_LINKLOCAL
757
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
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*/
758
720
      if(if_index == AVAHI_IF_UNSPEC){
759
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
760
 
                     " incomplete without a network interface\n");
 
721
        fprintf(stderr, "Mandos plugin mandos-client: "
 
722
                "An IPv6 link-local address is incomplete"
 
723
                " without a network interface\n");
761
724
        errno = EINVAL;
762
725
        goto mandos_end;
763
726
      }
764
727
      /* Set the network interface number as scope */
765
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
728
      to.in6.sin6_scope_id = (uint32_t)if_index;
766
729
    }
767
730
  } else {
768
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
731
    to.in.sin_port = htons(port); /* Spurious warnings from
 
732
                                     -Wconversion and
 
733
                                     -Wunreachable-code */
769
734
  }
770
735
  
771
736
  if(quit_now){
779
744
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
780
745
        perror_plus("if_indextoname");
781
746
      } else {
782
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
783
 
                     "\n", ip, interface, (uintmax_t)port);
 
747
        fprintf(stderr, "Mandos plugin mandos-client: "
 
748
                "Connection to: %s%%%s, port %" PRIu16 "\n",
 
749
                ip, interface, port);
784
750
      }
785
751
    } else {
786
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
787
 
                   ip, (uintmax_t)port);
 
752
      fprintf(stderr, "Mandos plugin mandos-client: "
 
753
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
788
754
    }
789
755
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
790
756
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
757
    const char *pcret;
791
758
    if(af == AF_INET6){
792
 
      ret = getnameinfo((struct sockaddr *)&to,
793
 
                        sizeof(struct sockaddr_in6),
794
 
                        addrstr, sizeof(addrstr), NULL, 0,
795
 
                        NI_NUMERICHOST);
 
759
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
760
                        sizeof(addrstr));
796
761
    } else {
797
 
      ret = getnameinfo((struct sockaddr *)&to,
798
 
                        sizeof(struct sockaddr_in),
799
 
                        addrstr, sizeof(addrstr), NULL, 0,
800
 
                        NI_NUMERICHOST);
 
762
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
763
                        sizeof(addrstr));
801
764
    }
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);
 
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
      }
808
772
    }
809
773
  }
810
774
  
814
778
  }
815
779
  
816
780
  if(af == AF_INET6){
817
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
818
 
                  sizeof(struct sockaddr_in6));
 
781
    ret = connect(tcp_sd, &to.in6, sizeof(to));
819
782
  } else {
820
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
821
 
                  sizeof(struct sockaddr_in));
 
783
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
822
784
  }
823
785
  if(ret < 0){
824
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
786
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
825
787
      int e = errno;
826
788
      perror_plus("connect");
827
789
      errno = e;
865
827
  }
866
828
  
867
829
  if(debug){
868
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
830
    fprintf(stderr, "Mandos plugin mandos-client: "
 
831
            "Establishing TLS session with %s\n", ip);
869
832
  }
870
833
  
871
834
  if(quit_now){
873
836
    goto mandos_end;
874
837
  }
875
838
  
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);
 
839
  /* Spurious warning from -Wint-to-pointer-cast */
 
840
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
881
841
  
882
842
  if(quit_now){
883
843
    errno = EINTR;
894
854
  
895
855
  if(ret != GNUTLS_E_SUCCESS){
896
856
    if(debug){
897
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
857
      fprintf(stderr, "Mandos plugin mandos-client: "
 
858
              "*** GnuTLS Handshake failed ***\n");
898
859
      gnutls_perror(ret);
899
860
    }
900
861
    errno = EPROTO;
904
865
  /* Read OpenPGP packet that contains the wanted password */
905
866
  
906
867
  if(debug){
907
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
908
 
                 " %s\n", ip);
 
868
    fprintf(stderr, "Mandos plugin mandos-client: "
 
869
            "Retrieving OpenPGP encrypted password from %s\n", ip);
909
870
  }
910
871
  
911
872
  while(true){
949
910
          }
950
911
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
951
912
        if(ret < 0){
952
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
953
 
                       "***\n");
 
913
          fprintf(stderr, "Mandos plugin mandos-client: "
 
914
                  "*** GnuTLS Re-handshake failed ***\n");
954
915
          gnutls_perror(ret);
955
916
          errno = EPROTO;
956
917
          goto mandos_end;
957
918
        }
958
919
        break;
959
920
      default:
960
 
        fprintf_plus(stderr, "Unknown error while reading data from"
961
 
                     " encrypted session with Mandos server\n");
 
921
        fprintf(stderr, "Mandos plugin mandos-client: "
 
922
                "Unknown error while reading data from"
 
923
                " encrypted session with Mandos server\n");
962
924
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
963
925
        errno = EIO;
964
926
        goto mandos_end;
969
931
  }
970
932
  
971
933
  if(debug){
972
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
934
    fprintf(stderr, "Mandos plugin mandos-client: "
 
935
            "Closing TLS session\n");
973
936
  }
974
937
  
975
938
  if(quit_now){
988
951
  if(buffer_length > 0){
989
952
    ssize_t decrypted_buffer_size;
990
953
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
991
 
                                               &decrypted_buffer, mc);
 
954
                                               &decrypted_buffer);
992
955
    if(decrypted_buffer_size >= 0){
993
956
      
994
957
      written = 0;
1004
967
        if(ret == 0 and ferror(stdout)){
1005
968
          int e = errno;
1006
969
          if(debug){
1007
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
1008
 
                         strerror(errno));
 
970
            fprintf(stderr, "Mandos plugin mandos-client: "
 
971
                    "Error writing encrypted data: %s\n",
 
972
                    strerror(errno));
1009
973
          }
1010
974
          errno = e;
1011
975
          goto mandos_end;
1042
1006
  return retval;
1043
1007
}
1044
1008
 
1045
 
__attribute__((nonnull))
1046
1009
static void resolve_callback(AvahiSServiceResolver *r,
1047
1010
                             AvahiIfIndex interface,
1048
1011
                             AvahiProtocol proto,
1056
1019
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1057
1020
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1058
1021
                             flags,
1059
 
                             void *mc){
1060
 
  if(r == NULL){
1061
 
    return;
1062
 
  }
 
1022
                             AVAHI_GCC_UNUSED void* userdata){
 
1023
  assert(r);
1063
1024
  
1064
1025
  /* Called whenever a service has been resolved successfully or
1065
1026
     timed out */
1071
1032
  switch(event){
1072
1033
  default:
1073
1034
  case AVAHI_RESOLVER_FAILURE:
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)));
 
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)));
1079
1039
    break;
1080
1040
    
1081
1041
  case AVAHI_RESOLVER_FOUND:
1083
1043
      char ip[AVAHI_ADDRESS_STR_MAX];
1084
1044
      avahi_address_snprint(ip, sizeof(ip), address);
1085
1045
      if(debug){
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);
 
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);
1089
1050
      }
1090
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1091
 
                                           interface,
1092
 
                                           avahi_proto_to_af(proto),
1093
 
                                           mc);
 
1051
      int ret = start_mandos_communication(ip, port, interface,
 
1052
                                           avahi_proto_to_af(proto));
1094
1053
      if(ret == 0){
1095
 
        avahi_simple_poll_quit(simple_poll);
 
1054
        avahi_simple_poll_quit(mc.simple_poll);
1096
1055
      } else {
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
 
        }
 
1056
        ret = add_server(ip, port, interface,
 
1057
                         avahi_proto_to_af(proto));
1103
1058
      }
1104
1059
    }
1105
1060
  }
1115
1070
                            const char *domain,
1116
1071
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1117
1072
                            flags,
1118
 
                            void *mc){
1119
 
  if(b == NULL){
1120
 
    return;
1121
 
  }
 
1073
                            AVAHI_GCC_UNUSED void* userdata){
 
1074
  assert(b);
1122
1075
  
1123
1076
  /* Called whenever a new services becomes available on the LAN or
1124
1077
     is removed from the LAN */
1131
1084
  default:
1132
1085
  case AVAHI_BROWSER_FAILURE:
1133
1086
    
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);
 
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);
1138
1091
    return;
1139
1092
    
1140
1093
  case AVAHI_BROWSER_NEW:
1143
1096
       the callback function is called the Avahi server will free the
1144
1097
       resolver for us. */
1145
1098
    
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)));
 
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)));
1154
1105
    break;
1155
1106
    
1156
1107
  case AVAHI_BROWSER_REMOVE:
1159
1110
  case AVAHI_BROWSER_ALL_FOR_NOW:
1160
1111
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1161
1112
    if(debug){
1162
 
      fprintf_plus(stderr, "No Mandos server found, still"
1163
 
                   " searching...\n");
 
1113
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1114
              "No Mandos server found, still searching...\n");
1164
1115
    }
1165
1116
    break;
1166
1117
  }
1175
1126
  signal_received = sig;
1176
1127
  int old_errno = errno;
1177
1128
  /* set main loop to exit */
1178
 
  if(simple_poll != NULL){
1179
 
    avahi_simple_poll_quit(simple_poll);
 
1129
  if(mc.simple_poll != NULL){
 
1130
    avahi_simple_poll_quit(mc.simple_poll);
1180
1131
  }
1181
1132
  errno = old_errno;
1182
1133
}
1183
1134
 
1184
 
__attribute__((nonnull, warn_unused_result))
1185
1135
bool get_flags(const char *ifname, struct ifreq *ifr){
1186
1136
  int ret;
1187
 
  error_t ret_errno;
1188
1137
  
1189
1138
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1190
1139
  if(s < 0){
1191
 
    ret_errno = errno;
1192
1140
    perror_plus("socket");
1193
 
    errno = ret_errno;
1194
1141
    return false;
1195
1142
  }
1196
1143
  strcpy(ifr->ifr_name, ifname);
1197
1144
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1198
1145
  if(ret == -1){
1199
1146
    if(debug){
1200
 
      ret_errno = errno;
1201
1147
      perror_plus("ioctl SIOCGIFFLAGS");
1202
 
      errno = ret_errno;
1203
1148
    }
1204
1149
    return false;
1205
1150
  }
1206
1151
  return true;
1207
1152
}
1208
1153
 
1209
 
__attribute__((nonnull, warn_unused_result))
1210
1154
bool good_flags(const char *ifname, const struct ifreq *ifr){
1211
1155
  
1212
1156
  /* Reject the loopback device */
1213
1157
  if(ifr->ifr_flags & IFF_LOOPBACK){
1214
1158
    if(debug){
1215
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1216
 
                   ifname);
 
1159
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1160
              "Rejecting loopback interface \"%s\"\n", ifname);
1217
1161
    }
1218
1162
    return false;
1219
1163
  }
1220
1164
  /* Accept point-to-point devices only if connect_to is specified */
1221
1165
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1222
1166
    if(debug){
1223
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1224
 
                   " \"%s\"\n", ifname);
 
1167
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1168
              "Accepting point-to-point interface \"%s\"\n", ifname);
1225
1169
    }
1226
1170
    return true;
1227
1171
  }
1228
1172
  /* Otherwise, reject non-broadcast-capable devices */
1229
1173
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1230
1174
    if(debug){
1231
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1232
 
                   " \"%s\"\n", ifname);
 
1175
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1176
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
1233
1177
    }
1234
1178
    return false;
1235
1179
  }
1236
1180
  /* Reject non-ARP interfaces (including dummy interfaces) */
1237
1181
  if(ifr->ifr_flags & IFF_NOARP){
1238
1182
    if(debug){
1239
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1240
 
                   ifname);
 
1183
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1184
              "Rejecting non-ARP interface \"%s\"\n", ifname);
1241
1185
    }
1242
1186
    return false;
1243
1187
  }
1244
1188
  
1245
1189
  /* Accept this device */
1246
1190
  if(debug){
1247
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1191
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1192
            "Interface \"%s\" is good\n", ifname);
1248
1193
  }
1249
1194
  return true;
1250
1195
}
1254
1199
 * corresponds to an acceptable network device.
1255
1200
 * (This function is passed to scandir(3) as a filter function.)
1256
1201
 */
1257
 
__attribute__((nonnull, warn_unused_result))
1258
1202
int good_interface(const struct dirent *if_entry){
1259
1203
  if(if_entry->d_name[0] == '.'){
1260
1204
    return 0;
1263
1207
  struct ifreq ifr;
1264
1208
  if(not get_flags(if_entry->d_name, &ifr)){
1265
1209
    if(debug){
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))
 
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
 
1313
1269
int notdotentries(const struct dirent *direntry){
1314
1270
  /* Skip "." and ".." */
1315
1271
  if(direntry->d_name[0] == '.'
1322
1278
}
1323
1279
 
1324
1280
/* Is this directory entry a runnable program? */
1325
 
__attribute__((nonnull, warn_unused_result))
1326
1281
int runnable_hook(const struct dirent *direntry){
1327
1282
  int ret;
1328
1283
  size_t sret;
1336
1291
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1337
1292
                "abcdefghijklmnopqrstuvwxyz"
1338
1293
                "0123456789"
1339
 
                "_.-");
 
1294
                "_-");
1340
1295
  if((direntry->d_name)[sret] != '\0'){
1341
1296
    /* Contains non-allowed characters */
1342
1297
    if(debug){
1343
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1344
 
                   direntry->d_name);
 
1298
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1299
              "Ignoring hook \"%s\" with bad name\n",
 
1300
              direntry->d_name);
1345
1301
    }
1346
1302
    return 0;
1347
1303
  }
1348
1304
  
1349
 
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
 
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);
1350
1313
  if(ret == -1){
1351
1314
    if(debug){
1352
1315
      perror_plus("Could not stat hook");
1356
1319
  if(not (S_ISREG(st.st_mode))){
1357
1320
    /* Not a regular file */
1358
1321
    if(debug){
1359
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1360
 
                   direntry->d_name);
 
1322
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1323
              "Ignoring hook \"%s\" - not a file\n",
 
1324
              direntry->d_name);
1361
1325
    }
1362
1326
    return 0;
1363
1327
  }
1364
1328
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1365
1329
    /* Not executable */
1366
1330
    if(debug){
1367
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1368
 
                   direntry->d_name);
 
1331
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1332
              "Ignoring hook \"%s\" - not executable\n",
 
1333
              direntry->d_name);
1369
1334
    }
1370
1335
    return 0;
1371
1336
  }
1372
 
  if(debug){
1373
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1374
 
                 direntry->d_name);
1375
 
  }
1376
1337
  return 1;
1377
1338
}
1378
1339
 
1379
 
__attribute__((nonnull, warn_unused_result))
1380
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1381
 
                            mandos_context *mc){
 
1340
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1382
1341
  int ret;
1383
1342
  struct timespec now;
1384
1343
  struct timespec waited_time;
1385
1344
  intmax_t block_time;
1386
1345
  
1387
1346
  while(true){
1388
 
    if(mc->current_server == NULL){
1389
 
      if(debug){
1390
 
        fprintf_plus(stderr, "Wait until first server is found."
1391
 
                     " No timeout!\n");
 
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");
1392
1351
      }
1393
1352
      ret = avahi_simple_poll_iterate(s, -1);
1394
1353
    } else {
1395
 
      if(debug){
1396
 
        fprintf_plus(stderr, "Check current_server if we should run"
1397
 
                     " it, or wait\n");
 
1354
      if (debug){
 
1355
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1356
                "Check current_server if we should run it,"
 
1357
                " or wait\n");
1398
1358
      }
1399
1359
      /* the current time */
1400
1360
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1405
1365
      /* Calculating in ms how long time between now and server
1406
1366
         who we visted longest time ago. Now - last seen.  */
1407
1367
      waited_time.tv_sec = (now.tv_sec
1408
 
                            - mc->current_server->last_seen.tv_sec);
 
1368
                            - mc.current_server->last_seen.tv_sec);
1409
1369
      waited_time.tv_nsec = (now.tv_nsec
1410
 
                             - mc->current_server->last_seen.tv_nsec);
 
1370
                             - mc.current_server->last_seen.tv_nsec);
1411
1371
      /* total time is 10s/10,000ms.
1412
1372
         Converting to s from ms by dividing by 1,000,
1413
1373
         and ns to ms by dividing by 1,000,000. */
1415
1375
                     - ((intmax_t)waited_time.tv_sec * 1000))
1416
1376
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1417
1377
      
1418
 
      if(debug){
1419
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1420
 
                     block_time);
 
1378
      if (debug){
 
1379
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1380
                "Blocking for %" PRIdMAX " ms\n", block_time);
1421
1381
      }
1422
1382
      
1423
1383
      if(block_time <= 0){
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);
 
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);
1428
1388
        if(ret == 0){
1429
 
          avahi_simple_poll_quit(s);
 
1389
          avahi_simple_poll_quit(mc.simple_poll);
1430
1390
          return 0;
1431
1391
        }
1432
1392
        ret = clock_gettime(CLOCK_MONOTONIC,
1433
 
                            &mc->current_server->last_seen);
 
1393
                            &mc.current_server->last_seen);
1434
1394
        if(ret == -1){
1435
1395
          perror_plus("clock_gettime");
1436
1396
          return -1;
1437
1397
        }
1438
 
        mc->current_server = mc->current_server->next;
 
1398
        mc.current_server = mc.current_server->next;
1439
1399
        block_time = 0;         /* Call avahi to find new Mandos
1440
1400
                                   servers, but don't block */
1441
1401
      }
1443
1403
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1444
1404
    }
1445
1405
    if(ret != 0){
1446
 
      if(ret > 0 or errno != EINTR){
 
1406
      if (ret > 0 or errno != EINTR){
1447
1407
        return (ret != 1) ? ret : 0;
1448
1408
      }
1449
1409
    }
1450
1410
  }
1451
1411
}
1452
1412
 
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
 
 
1907
1413
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 };
1912
1414
  AvahiSServiceBrowser *sb = NULL;
1913
 
  error_t ret_errno;
 
1415
  int error;
1914
1416
  int ret;
1915
1417
  intmax_t tmpmax;
1916
1418
  char *tmp;
1917
1419
  int exitcode = EXIT_SUCCESS;
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;
 
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;
1923
1428
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1924
1429
  const char *seckey = PATHDIR "/" SECKEY;
1925
1430
  const char *pubkey = PATHDIR "/" PUBKEY;
1926
 
  char *interfaces_hooks = NULL;
1927
1431
  
1928
1432
  bool gnutls_initialized = false;
1929
1433
  bool gpgme_initialized = false;
1991
1495
        .group = 2 },
1992
1496
      { .name = "retry", .key = 132,
1993
1497
        .arg = "SECONDS",
1994
 
        .doc = "Retry interval used when denied by the Mandos server",
 
1498
        .doc = "Retry interval used when denied by the mandos server",
1995
1499
        .group = 2 },
1996
1500
      { .name = "network-hook-dir", .key = 133,
1997
1501
        .arg = "DIR",
2020
1524
        connect_to = arg;
2021
1525
        break;
2022
1526
      case 'i':                 /* --interface */
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
 
        }
 
1527
        interface = arg;
2028
1528
        break;
2029
1529
      case 's':                 /* --seckey */
2030
1530
        seckey = arg;
2073
1573
        argp_state_help(state, state->out_stream,
2074
1574
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
2075
1575
      case 'V':                 /* --version */
2076
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1576
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
 
1577
        fprintf(state->out_stream, "%s\n", argp_program_version);
2077
1578
        exit(argp_err_exit_status);
2078
1579
        break;
2079
1580
      default:
2106
1607
  {
2107
1608
    /* Work around Debian bug #633582:
2108
1609
       <http://bugs.debian.org/633582> */
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");
 
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");
2115
1675
    } else {
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);
 
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
    }
2199
1764
  }
2200
1765
  
2201
1766
  if(not debug){
2202
1767
    avahi_set_log_function(empty_log);
2203
1768
  }
2204
1769
  
 
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
  
2205
1804
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2206
1805
     from the signal handler */
2207
1806
  /* Initialize the pseudo-RNG for Avahi */
2208
1807
  srand((unsigned int) time(NULL));
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");
 
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");
2213
1812
    exitcode = EX_UNAVAILABLE;
2214
1813
    goto end;
2215
1814
  }
2277
1876
    }
2278
1877
  }
2279
1878
  
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);
 
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");
 
1965
          }
 
1966
        }
 
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
        break;
 
1985
      }
 
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
      }
2302
2016
    } 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;
2327
 
          }
2328
 
        }
2329
 
        break;
2330
 
      }
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);
 
2017
      /* Lower privileges permanently */
 
2018
      ret = setuid(uid);
 
2019
      if(ret == -1){
 
2020
        perror_plus("setuid");
 
2021
      }
 
2022
    }
2358
2023
  }
2359
2024
  
2360
2025
  if(quit_now){
2361
2026
    goto end;
2362
2027
  }
2363
2028
  
2364
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2029
  ret = init_gnutls_global(pubkey, seckey);
2365
2030
  if(ret == -1){
2366
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
2031
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2032
            "init_gnutls_global failed\n");
2367
2033
    exitcode = EX_UNAVAILABLE;
2368
2034
    goto end;
2369
2035
  } else {
2374
2040
    goto end;
2375
2041
  }
2376
2042
  
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){
 
2043
  if(mkdtemp(tempdir) == NULL){
2387
2044
    perror_plus("mkdtemp");
2388
2045
    goto end;
2389
2046
  }
 
2047
  tempdir_created = true;
2390
2048
  
2391
2049
  if(quit_now){
2392
2050
    goto end;
2393
2051
  }
2394
2052
  
2395
 
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
2396
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
2053
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
2054
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2055
            "init_gpgme failed\n");
2397
2056
    exitcode = EX_UNAVAILABLE;
2398
2057
    goto end;
2399
2058
  } else {
2408
2067
    /* Connect directly, do not use Zeroconf */
2409
2068
    /* (Mainly meant for debugging) */
2410
2069
    char *address = strrchr(connect_to, ':');
2411
 
    
2412
2070
    if(address == NULL){
2413
 
      fprintf_plus(stderr, "No colon in address\n");
 
2071
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2072
              "No colon in address\n");
2414
2073
      exitcode = EX_USAGE;
2415
2074
      goto end;
2416
2075
    }
2419
2078
      goto end;
2420
2079
    }
2421
2080
    
2422
 
    in_port_t port;
 
2081
    uint16_t port;
2423
2082
    errno = 0;
2424
2083
    tmpmax = strtoimax(address+1, &tmp, 10);
2425
2084
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2426
 
       or tmpmax != (in_port_t)tmpmax){
2427
 
      fprintf_plus(stderr, "Bad port number\n");
 
2085
       or tmpmax != (uint16_t)tmpmax){
 
2086
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2087
              "Bad port number\n");
2428
2088
      exitcode = EX_USAGE;
2429
2089
      goto end;
2430
2090
    }
2431
 
    
 
2091
  
2432
2092
    if(quit_now){
2433
2093
      goto end;
2434
2094
    }
2435
2095
    
2436
 
    port = (in_port_t)tmpmax;
 
2096
    port = (uint16_t)tmpmax;
2437
2097
    *address = '\0';
2438
2098
    /* Colon in address indicates IPv6 */
2439
2099
    int af;
2455
2115
    }
2456
2116
    
2457
2117
    while(not quit_now){
2458
 
      ret = start_mandos_communication(address, port, if_index, af,
2459
 
                                       &mc);
 
2118
      ret = start_mandos_communication(address, port, if_index, af);
2460
2119
      if(quit_now or ret == 0){
2461
2120
        break;
2462
2121
      }
2463
2122
      if(debug){
2464
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2465
 
                     (int)retry_interval);
 
2123
        fprintf(stderr, "Mandos plugin mandos-client: "
 
2124
                "Retrying in %d seconds\n", (int)retry_interval);
2466
2125
      }
2467
 
      sleep((unsigned int)retry_interval);
 
2126
      sleep((int)retry_interval);
2468
2127
    }
2469
2128
    
2470
 
    if(not quit_now){
 
2129
    if (not quit_now){
2471
2130
      exitcode = EXIT_SUCCESS;
2472
2131
    }
2473
2132
    
2488
2147
    config.publish_domain = 0;
2489
2148
    
2490
2149
    /* Allocate a new server */
2491
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2492
 
                                 &config, NULL, NULL, &ret_errno);
 
2150
    mc.server = avahi_server_new(avahi_simple_poll_get
 
2151
                                 (mc.simple_poll), &config, NULL,
 
2152
                                 NULL, &error);
2493
2153
    
2494
2154
    /* Free the Avahi configuration data */
2495
2155
    avahi_server_config_free(&config);
2497
2157
  
2498
2158
  /* Check if creating the Avahi server object succeeded */
2499
2159
  if(mc.server == NULL){
2500
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2501
 
                 avahi_strerror(ret_errno));
 
2160
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2161
            "Failed to create Avahi server: %s\n",
 
2162
            avahi_strerror(error));
2502
2163
    exitcode = EX_UNAVAILABLE;
2503
2164
    goto end;
2504
2165
  }
2510
2171
  /* Create the Avahi service browser */
2511
2172
  sb = avahi_s_service_browser_new(mc.server, if_index,
2512
2173
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2513
 
                                   NULL, 0, browse_callback,
2514
 
                                   (void *)&mc);
 
2174
                                   NULL, 0, browse_callback, NULL);
2515
2175
  if(sb == NULL){
2516
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2517
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
2176
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2177
            "Failed to create service browser: %s\n",
 
2178
            avahi_strerror(avahi_server_errno(mc.server)));
2518
2179
    exitcode = EX_UNAVAILABLE;
2519
2180
    goto end;
2520
2181
  }
2526
2187
  /* Run the main loop */
2527
2188
  
2528
2189
  if(debug){
2529
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
2190
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2191
            "Starting Avahi loop search\n");
2530
2192
  }
2531
 
  
2532
 
  ret = avahi_loop_with_timeout(simple_poll,
2533
 
                                (int)(retry_interval * 1000), &mc);
 
2193
 
 
2194
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2195
                                (int)(retry_interval * 1000));
2534
2196
  if(debug){
2535
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2536
 
                 (ret == 0) ? "successfully" : "with error");
 
2197
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2198
            "avahi_loop_with_timeout exited %s\n",
 
2199
            (ret == 0) ? "successfully" : "with error");
2537
2200
  }
2538
2201
  
2539
2202
 end:
2540
2203
  
2541
2204
  if(debug){
2542
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2205
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2206
            "%s exiting\n", argv[0]);
2543
2207
  }
2544
2208
  
2545
2209
  /* Cleanup things */
2546
 
  free(mc.interfaces);
2547
 
  
2548
2210
  if(sb != NULL)
2549
2211
    avahi_s_service_browser_free(sb);
2550
2212
  
2551
2213
  if(mc.server != NULL)
2552
2214
    avahi_server_free(mc.server);
2553
2215
  
2554
 
  if(simple_poll != NULL)
2555
 
    avahi_simple_poll_free(simple_poll);
 
2216
  if(mc.simple_poll != NULL)
 
2217
    avahi_simple_poll_free(mc.simple_poll);
2556
2218
  
2557
2219
  if(gnutls_initialized){
2558
2220
    gnutls_certificate_free_credentials(mc.cred);
2563
2225
  if(gpgme_initialized){
2564
2226
    gpgme_release(mc.ctx);
2565
2227
  }
2566
 
  
 
2228
 
2567
2229
  /* Cleans up the circular linked list of Mandos servers the client
2568
2230
     has seen */
2569
2231
  if(mc.current_server != NULL){
2575
2237
    }
2576
2238
  }
2577
2239
  
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
 
      }
 
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");
2606
2249
    }
2607
 
    
2608
 
    ret_errno = lower_privileges_permanently();
2609
 
    if(ret_errno != 0){
2610
 
      perror_plus("Failed to lower privileges permanently");
 
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
      }
2611
2271
    }
2612
2272
  }
2613
2273
  
2614
 
  free(interfaces_to_take_down);
2615
 
  free(interfaces_hooks);
2616
 
  
2617
2274
  /* Removes the GPGME temp directory and all files inside */
2618
 
  if(tempdir != NULL){
 
2275
  if(tempdir_created){
2619
2276
    struct dirent **direntries = NULL;
2620
2277
    struct dirent *direntry = NULL;
2621
2278
    int numentries = scandir(tempdir, &direntries, notdotentries,
2622
2279
                             alphasort);
2623
 
    if(numentries > 0){
 
2280
    if (numentries > 0){
2624
2281
      for(int i = 0; i < numentries; i++){
2625
2282
        direntry = direntries[i];
2626
2283
        char *fullname = NULL;
2632
2289
        }
2633
2290
        ret = remove(fullname);
2634
2291
        if(ret == -1){
2635
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2636
 
                       strerror(errno));
 
2292
          fprintf(stderr, "Mandos plugin mandos-client: "
 
2293
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
2637
2294
        }
2638
2295
        free(fullname);
2639
2296
      }
2640
2297
    }
2641
 
    
 
2298
 
2642
2299
    /* need to clean even if 0 because man page doesn't specify */
2643
2300
    free(direntries);
2644
 
    if(numentries == -1){
 
2301
    if (numentries == -1){
2645
2302
      perror_plus("scandir");
2646
2303
    }
2647
2304
    ret = rmdir(tempdir);