/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2014-01-20 21:50:11 UTC
  • Revision ID: teddy@recompile.se-20140120215011-ka70v54d3rb2pyug
Bug fix from libdir change: make plugins get setuid bit again.

* debian/mandos-client.lintian-overrides: Libdir changes.
* debian/rules (override_dh_fixperms): - '' -

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008-2013 Teddy Hogeborn
 
13
 * Copyright © 2008-2013 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
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
61
61
                                 */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
 
#include <assert.h>             /* assert() */
65
64
#include <errno.h>              /* perror(), errno,
66
65
                                   program_invocation_short_name */
67
66
#include <time.h>               /* nanosleep(), time(), sleep() */
73
72
                                */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
 
75
                                   setgid(), pause(), _exit() */
77
76
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
85
84
                                   raise() */
86
85
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
86
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
87
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
88
                                   WEXITSTATUS(), WTERMSIG() */
 
89
#include <grp.h>                /* setgroups() */
 
90
#include <argz.h>               /* argz_add_sep(), argz_next(),
 
91
                                   argz_delete(), argz_append(),
 
92
                                   argz_stringify(), argz_add(),
 
93
                                   argz_count() */
88
94
 
89
95
#ifdef __linux__
90
96
#include <sys/klog.h>           /* klogctl() */
108
114
                                   init_gnutls_session(),
109
115
                                   GNUTLS_* */
110
116
#include <gnutls/openpgp.h>
111
 
                          /* gnutls_certificate_set_openpgp_key_file(),
112
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
117
                         /* gnutls_certificate_set_openpgp_key_file(),
 
118
                            GNUTLS_OPENPGP_FMT_BASE64 */
113
119
 
114
120
/* GPGME */
115
121
#include <gpgme.h>              /* All GPGME types, constants and
131
137
const char *argp_program_bug_address = "<mandos@recompile.se>";
132
138
static const char sys_class_net[] = "/sys/class/net";
133
139
char *connect_to = NULL;
 
140
const char *hookdir = HOOKDIR;
 
141
uid_t uid = 65534;
 
142
gid_t gid = 65534;
134
143
 
135
144
/* Doubly linked list that need to be circularly linked when used */
136
145
typedef struct server{
137
146
  const char *ip;
138
 
  uint16_t port;
 
147
  in_port_t port;
139
148
  AvahiIfIndex if_index;
140
149
  int af;
141
150
  struct timespec last_seen;
145
154
 
146
155
/* Used for passing in values through the Avahi callback functions */
147
156
typedef struct {
148
 
  AvahiSimplePoll *simple_poll;
149
157
  AvahiServer *server;
150
158
  gnutls_certificate_credentials_t cred;
151
159
  unsigned int dh_bits;
153
161
  const char *priority;
154
162
  gpgme_ctx_t ctx;
155
163
  server *current_server;
 
164
  char *interfaces;
 
165
  size_t interfaces_size;
156
166
} mandos_context;
157
167
 
158
 
/* global context so signal handler can reach it*/
159
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
160
 
                      .dh_bits = 1024, .priority = "SECURE256"
161
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
162
 
                      .current_server = NULL };
 
168
/* global so signal handler can reach it*/
 
169
AvahiSimplePoll *simple_poll;
163
170
 
164
171
sig_atomic_t quit_now = 0;
165
172
int signal_received = 0;
166
173
 
167
174
/* Function to use when printing errors */
168
175
void perror_plus(const char *print_text){
 
176
  int e = errno;
169
177
  fprintf(stderr, "Mandos plugin %s: ",
170
178
          program_invocation_short_name);
 
179
  errno = e;
171
180
  perror(print_text);
172
181
}
173
182
 
 
183
__attribute__((format (gnu_printf, 2, 3)))
 
184
int fprintf_plus(FILE *stream, const char *format, ...){
 
185
  va_list ap;
 
186
  va_start (ap, format);
 
187
  
 
188
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
189
                             program_invocation_short_name));
 
190
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
191
}
 
192
 
174
193
/*
175
194
 * Make additional room in "buffer" for at least BUFFER_SIZE more
176
195
 * bytes. "buffer_capacity" is how much is currently allocated,
177
196
 * "buffer_length" is how much is already used.
178
197
 */
179
198
size_t incbuffer(char **buffer, size_t buffer_length,
180
 
                  size_t buffer_capacity){
 
199
                 size_t buffer_capacity){
181
200
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
182
201
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
183
202
    if(buffer == NULL){
189
208
}
190
209
 
191
210
/* Add server to set of servers to retry periodically */
192
 
int add_server(const char *ip, uint16_t port,
193
 
                 AvahiIfIndex if_index,
194
 
                 int af){
 
211
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
 
212
                int af, server **current_server){
195
213
  int ret;
196
214
  server *new_server = malloc(sizeof(server));
197
215
  if(new_server == NULL){
198
216
    perror_plus("malloc");
199
 
    return -1;
 
217
    return false;
200
218
  }
201
219
  *new_server = (server){ .ip = strdup(ip),
202
 
                         .port = port,
203
 
                         .if_index = if_index,
204
 
                         .af = af };
 
220
                          .port = port,
 
221
                          .if_index = if_index,
 
222
                          .af = af };
205
223
  if(new_server->ip == NULL){
206
224
    perror_plus("strdup");
207
 
    return -1;
 
225
    return false;
208
226
  }
209
227
  /* Special case of first server */
210
 
  if (mc.current_server == NULL){
 
228
  if(*current_server == NULL){
211
229
    new_server->next = new_server;
212
230
    new_server->prev = new_server;
213
 
    mc.current_server = new_server;
 
231
    *current_server = new_server;
214
232
  /* Place the new server last in the list */
215
233
  } else {
216
 
    new_server->next = mc.current_server;
217
 
    new_server->prev = mc.current_server->prev;
 
234
    new_server->next = *current_server;
 
235
    new_server->prev = (*current_server)->prev;
218
236
    new_server->prev->next = new_server;
219
 
    mc.current_server->prev = new_server;
 
237
    (*current_server)->prev = new_server;
220
238
  }
221
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
239
  ret = clock_gettime(CLOCK_MONOTONIC, &(*current_server)->last_seen);
222
240
  if(ret == -1){
223
241
    perror_plus("clock_gettime");
224
 
    return -1;
 
242
    return false;
225
243
  }
226
 
  return 0;
 
244
  return true;
227
245
}
228
246
 
229
247
/* 
230
248
 * Initialize GPGME.
231
249
 */
232
 
static bool init_gpgme(const char *seckey,
233
 
                       const char *pubkey, const char *tempdir){
 
250
static bool init_gpgme(const char *seckey, const char *pubkey,
 
251
                       const char *tempdir, mandos_context *mc){
234
252
  gpgme_error_t rc;
235
253
  gpgme_engine_info_t engine_info;
236
254
  
237
 
  
238
255
  /*
239
256
   * Helper function to insert pub and seckey to the engine keyring.
240
257
   */
251
268
    
252
269
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
253
270
    if(rc != GPG_ERR_NO_ERROR){
254
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
255
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
271
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
272
                   gpgme_strsource(rc), gpgme_strerror(rc));
256
273
      return false;
257
274
    }
258
275
    
259
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
276
    rc = gpgme_op_import(mc->ctx, pgp_data);
260
277
    if(rc != GPG_ERR_NO_ERROR){
261
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
262
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
278
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
279
                   gpgme_strsource(rc), gpgme_strerror(rc));
263
280
      return false;
264
281
    }
265
282
    
272
289
  }
273
290
  
274
291
  if(debug){
275
 
    fprintf(stderr, "Initializing GPGME\n");
 
292
    fprintf_plus(stderr, "Initializing GPGME\n");
276
293
  }
277
294
  
278
295
  /* Init GPGME */
279
296
  gpgme_check_version(NULL);
280
297
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
281
298
  if(rc != GPG_ERR_NO_ERROR){
282
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
283
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
299
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
300
                 gpgme_strsource(rc), gpgme_strerror(rc));
284
301
    return false;
285
302
  }
286
303
  
287
304
  /* Set GPGME home directory for the OpenPGP engine only */
288
305
  rc = gpgme_get_engine_info(&engine_info);
289
306
  if(rc != GPG_ERR_NO_ERROR){
290
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
291
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
307
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
308
                 gpgme_strsource(rc), gpgme_strerror(rc));
292
309
    return false;
293
310
  }
294
311
  while(engine_info != NULL){
300
317
    engine_info = engine_info->next;
301
318
  }
302
319
  if(engine_info == NULL){
303
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
320
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
321
                 tempdir);
304
322
    return false;
305
323
  }
306
324
  
307
325
  /* Create new GPGME "context" */
308
 
  rc = gpgme_new(&(mc.ctx));
 
326
  rc = gpgme_new(&(mc->ctx));
309
327
  if(rc != GPG_ERR_NO_ERROR){
310
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
311
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
328
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
329
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
330
                 gpgme_strerror(rc));
312
331
    return false;
313
332
  }
314
333
  
325
344
 */
326
345
static ssize_t pgp_packet_decrypt(const char *cryptotext,
327
346
                                  size_t crypto_size,
328
 
                                  char **plaintext){
 
347
                                  char **plaintext,
 
348
                                  mandos_context *mc){
329
349
  gpgme_data_t dh_crypto, dh_plain;
330
350
  gpgme_error_t rc;
331
351
  ssize_t ret;
333
353
  ssize_t plaintext_length = 0;
334
354
  
335
355
  if(debug){
336
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
356
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
337
357
  }
338
358
  
339
359
  /* Create new GPGME data buffer from memory cryptotext */
340
360
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
341
361
                               0);
342
362
  if(rc != GPG_ERR_NO_ERROR){
343
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
344
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
363
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
364
                 gpgme_strsource(rc), gpgme_strerror(rc));
345
365
    return -1;
346
366
  }
347
367
  
348
368
  /* Create new empty GPGME data buffer for the plaintext */
349
369
  rc = gpgme_data_new(&dh_plain);
350
370
  if(rc != GPG_ERR_NO_ERROR){
351
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
352
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
371
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
372
                 "bad gpgme_data_new: %s: %s\n",
 
373
                 gpgme_strsource(rc), gpgme_strerror(rc));
353
374
    gpgme_data_release(dh_crypto);
354
375
    return -1;
355
376
  }
356
377
  
357
378
  /* Decrypt data from the cryptotext data buffer to the plaintext
358
379
     data buffer */
359
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
380
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
360
381
  if(rc != GPG_ERR_NO_ERROR){
361
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
362
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
382
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
383
                 gpgme_strsource(rc), gpgme_strerror(rc));
363
384
    plaintext_length = -1;
364
385
    if(debug){
365
386
      gpgme_decrypt_result_t result;
366
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
387
      result = gpgme_op_decrypt_result(mc->ctx);
367
388
      if(result == NULL){
368
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
389
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
369
390
      } else {
370
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
371
 
                result->unsupported_algorithm);
372
 
        fprintf(stderr, "Wrong key usage: %u\n",
373
 
                result->wrong_key_usage);
 
391
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
392
                     result->unsupported_algorithm);
 
393
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
394
                     result->wrong_key_usage);
374
395
        if(result->file_name != NULL){
375
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
396
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
376
397
        }
377
398
        gpgme_recipient_t recipient;
378
399
        recipient = result->recipients;
379
400
        while(recipient != NULL){
380
 
          fprintf(stderr, "Public key algorithm: %s\n",
381
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
382
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
383
 
          fprintf(stderr, "Secret key available: %s\n",
384
 
                  recipient->status == GPG_ERR_NO_SECKEY
385
 
                  ? "No" : "Yes");
 
401
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
402
                       gpgme_pubkey_algo_name
 
403
                       (recipient->pubkey_algo));
 
404
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
405
          fprintf_plus(stderr, "Secret key available: %s\n",
 
406
                       recipient->status == GPG_ERR_NO_SECKEY
 
407
                       ? "No" : "Yes");
386
408
          recipient = recipient->next;
387
409
        }
388
410
      }
391
413
  }
392
414
  
393
415
  if(debug){
394
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
416
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
395
417
  }
396
418
  
397
419
  /* Seek back to the beginning of the GPGME plaintext data buffer */
404
426
  *plaintext = NULL;
405
427
  while(true){
406
428
    plaintext_capacity = incbuffer(plaintext,
407
 
                                      (size_t)plaintext_length,
408
 
                                      plaintext_capacity);
 
429
                                   (size_t)plaintext_length,
 
430
                                   plaintext_capacity);
409
431
    if(plaintext_capacity == 0){
410
 
        perror_plus("incbuffer");
411
 
        plaintext_length = -1;
412
 
        goto decrypt_end;
 
432
      perror_plus("incbuffer");
 
433
      plaintext_length = -1;
 
434
      goto decrypt_end;
413
435
    }
414
436
    
415
437
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
428
450
  }
429
451
  
430
452
  if(debug){
431
 
    fprintf(stderr, "Decrypted password is: ");
 
453
    fprintf_plus(stderr, "Decrypted password is: ");
432
454
    for(ssize_t i = 0; i < plaintext_length; i++){
433
455
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
434
456
    }
446
468
}
447
469
 
448
470
static const char * safer_gnutls_strerror(int value){
449
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
450
 
                                               -Wunreachable-code */
 
471
  const char *ret = gnutls_strerror(value);
451
472
  if(ret == NULL)
452
473
    ret = "(unknown)";
453
474
  return ret;
456
477
/* GnuTLS log function callback */
457
478
static void debuggnutls(__attribute__((unused)) int level,
458
479
                        const char* string){
459
 
  fprintf(stderr, "GnuTLS: %s", string);
 
480
  fprintf_plus(stderr, "GnuTLS: %s", string);
460
481
}
461
482
 
462
483
static int init_gnutls_global(const char *pubkeyfilename,
463
 
                              const char *seckeyfilename){
 
484
                              const char *seckeyfilename,
 
485
                              mandos_context *mc){
464
486
  int ret;
465
487
  
466
488
  if(debug){
467
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
489
    fprintf_plus(stderr, "Initializing GnuTLS\n");
468
490
  }
469
491
  
470
492
  ret = gnutls_global_init();
471
493
  if(ret != GNUTLS_E_SUCCESS){
472
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
473
 
            safer_gnutls_strerror(ret));
 
494
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
495
                 safer_gnutls_strerror(ret));
474
496
    return -1;
475
497
  }
476
498
  
483
505
  }
484
506
  
485
507
  /* OpenPGP credentials */
486
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
508
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
487
509
  if(ret != GNUTLS_E_SUCCESS){
488
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
489
 
            safer_gnutls_strerror(ret));
 
510
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
511
                 safer_gnutls_strerror(ret));
490
512
    gnutls_global_deinit();
491
513
    return -1;
492
514
  }
493
515
  
494
516
  if(debug){
495
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
496
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
497
 
            seckeyfilename);
 
517
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
518
                 " secret key %s as GnuTLS credentials\n",
 
519
                 pubkeyfilename,
 
520
                 seckeyfilename);
498
521
  }
499
522
  
500
523
  ret = gnutls_certificate_set_openpgp_key_file
501
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
524
    (mc->cred, pubkeyfilename, seckeyfilename,
502
525
     GNUTLS_OPENPGP_FMT_BASE64);
503
526
  if(ret != GNUTLS_E_SUCCESS){
504
 
    fprintf(stderr,
505
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
506
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
507
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
508
 
            safer_gnutls_strerror(ret));
 
527
    fprintf_plus(stderr,
 
528
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
529
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
530
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
531
                 safer_gnutls_strerror(ret));
509
532
    goto globalfail;
510
533
  }
511
534
  
512
535
  /* GnuTLS server initialization */
513
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
536
  ret = gnutls_dh_params_init(&mc->dh_params);
514
537
  if(ret != GNUTLS_E_SUCCESS){
515
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
516
 
            " %s\n", safer_gnutls_strerror(ret));
 
538
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
539
                 " initialization: %s\n",
 
540
                 safer_gnutls_strerror(ret));
517
541
    goto globalfail;
518
542
  }
519
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
543
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
520
544
  if(ret != GNUTLS_E_SUCCESS){
521
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
522
 
            safer_gnutls_strerror(ret));
 
545
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
546
                 safer_gnutls_strerror(ret));
523
547
    goto globalfail;
524
548
  }
525
549
  
526
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
550
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
527
551
  
528
552
  return 0;
529
553
  
530
554
 globalfail:
531
555
  
532
 
  gnutls_certificate_free_credentials(mc.cred);
 
556
  gnutls_certificate_free_credentials(mc->cred);
533
557
  gnutls_global_deinit();
534
 
  gnutls_dh_params_deinit(mc.dh_params);
 
558
  gnutls_dh_params_deinit(mc->dh_params);
535
559
  return -1;
536
560
}
537
561
 
538
 
static int init_gnutls_session(gnutls_session_t *session){
 
562
static int init_gnutls_session(gnutls_session_t *session,
 
563
                               mandos_context *mc){
539
564
  int ret;
540
565
  /* GnuTLS session creation */
541
566
  do {
545
570
    }
546
571
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
547
572
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
549
 
            safer_gnutls_strerror(ret));
 
573
    fprintf_plus(stderr,
 
574
                 "Error in GnuTLS session initialization: %s\n",
 
575
                 safer_gnutls_strerror(ret));
550
576
  }
551
577
  
552
578
  {
553
579
    const char *err;
554
580
    do {
555
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
581
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
556
582
      if(quit_now){
557
583
        gnutls_deinit(*session);
558
584
        return -1;
559
585
      }
560
586
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
561
587
    if(ret != GNUTLS_E_SUCCESS){
562
 
      fprintf(stderr, "Syntax error at: %s\n", err);
563
 
      fprintf(stderr, "GnuTLS error: %s\n",
564
 
              safer_gnutls_strerror(ret));
 
588
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
589
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
590
                   safer_gnutls_strerror(ret));
565
591
      gnutls_deinit(*session);
566
592
      return -1;
567
593
    }
569
595
  
570
596
  do {
571
597
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
572
 
                                 mc.cred);
 
598
                                 mc->cred);
573
599
    if(quit_now){
574
600
      gnutls_deinit(*session);
575
601
      return -1;
576
602
    }
577
603
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
578
604
  if(ret != GNUTLS_E_SUCCESS){
579
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
580
 
            safer_gnutls_strerror(ret));
 
605
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
606
                 safer_gnutls_strerror(ret));
581
607
    gnutls_deinit(*session);
582
608
    return -1;
583
609
  }
585
611
  /* ignore client certificate if any. */
586
612
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
587
613
  
588
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
614
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
589
615
  
590
616
  return 0;
591
617
}
595
621
                      __attribute__((unused)) const char *txt){}
596
622
 
597
623
/* Called when a Mandos server is found */
598
 
static int start_mandos_communication(const char *ip, uint16_t port,
 
624
static int start_mandos_communication(const char *ip, in_port_t port,
599
625
                                      AvahiIfIndex if_index,
600
 
                                      int af){
 
626
                                      int af, mandos_context *mc){
601
627
  int ret, tcp_sd = -1;
602
628
  ssize_t sret;
603
629
  union {
628
654
    pf = PF_INET;
629
655
    break;
630
656
  default:
631
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
657
    fprintf_plus(stderr, "Bad address family: %d\n", af);
632
658
    errno = EINVAL;
633
659
    return -1;
634
660
  }
635
661
  
636
 
  ret = init_gnutls_session(&session);
 
662
  /* If the interface is specified and we have a list of interfaces */
 
663
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
 
664
    /* Check if the interface is one of the interfaces we are using */
 
665
    bool match = false;
 
666
    {
 
667
      char *interface = NULL;
 
668
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
669
                                 interface))){
 
670
        if(if_nametoindex(interface) == (unsigned int)if_index){
 
671
          match = true;
 
672
          break;
 
673
        }
 
674
      }
 
675
    }
 
676
    if(not match){
 
677
      /* This interface does not match any in the list, so we don't
 
678
         connect to the server */
 
679
      if(debug){
 
680
        char interface[IF_NAMESIZE];
 
681
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
682
          perror_plus("if_indextoname");
 
683
        } else {
 
684
          fprintf_plus(stderr, "Skipping server on non-used interface"
 
685
                       " \"%s\"\n",
 
686
                       if_indextoname((unsigned int)if_index,
 
687
                                      interface));
 
688
        }
 
689
      }
 
690
      return -1;
 
691
    }
 
692
  }
 
693
  
 
694
  ret = init_gnutls_session(&session, mc);
637
695
  if(ret != 0){
638
696
    return -1;
639
697
  }
640
698
  
641
699
  if(debug){
642
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
643
 
            "\n", ip, port);
 
700
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
701
                 PRIuMAX "\n", ip, (uintmax_t)port);
644
702
  }
645
703
  
646
704
  tcp_sd = socket(pf, SOCK_STREAM, 0);
672
730
  }
673
731
  if(ret == 0){
674
732
    int e = errno;
675
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
733
    fprintf_plus(stderr, "Bad address: %s\n", ip);
676
734
    errno = e;
677
735
    goto mandos_end;
678
736
  }
679
737
  if(af == AF_INET6){
680
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
681
 
                                       -Wconversion and
682
 
                                       -Wunreachable-code */
683
 
    
 
738
    to.in6.sin6_port = htons(port);    
 
739
#ifdef __GNUC__
 
740
#pragma GCC diagnostic push
 
741
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
 
742
#endif
684
743
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
685
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
686
 
                              -Wunreachable-code*/
 
744
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower */
 
745
#ifdef __GNUC__
 
746
#pragma GCC diagnostic pop
 
747
#endif
687
748
      if(if_index == AVAHI_IF_UNSPEC){
688
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
689
 
                " without a network interface\n");
 
749
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
750
                     " incomplete without a network interface\n");
690
751
        errno = EINVAL;
691
752
        goto mandos_end;
692
753
      }
694
755
      to.in6.sin6_scope_id = (uint32_t)if_index;
695
756
    }
696
757
  } else {
697
 
    to.in.sin_port = htons(port); /* Spurious warnings from
698
 
                                     -Wconversion and
699
 
                                     -Wunreachable-code */
 
758
    to.in.sin_port = htons(port);
700
759
  }
701
760
  
702
761
  if(quit_now){
710
769
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
711
770
        perror_plus("if_indextoname");
712
771
      } else {
713
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
714
 
                ip, interface, port);
 
772
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
773
                     "\n", ip, interface, (uintmax_t)port);
715
774
      }
716
775
    } else {
717
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
718
 
              port);
 
776
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
777
                   ip, (uintmax_t)port);
719
778
    }
720
779
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
721
780
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
731
790
      perror_plus("inet_ntop");
732
791
    } else {
733
792
      if(strcmp(addrstr, ip) != 0){
734
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
793
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
735
794
      }
736
795
    }
737
796
  }
765
824
  while(true){
766
825
    size_t out_size = strlen(out);
767
826
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
768
 
                                   out_size - written));
 
827
                                        out_size - written));
769
828
    if(ret == -1){
770
829
      int e = errno;
771
830
      perror_plus("write");
791
850
  }
792
851
  
793
852
  if(debug){
794
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
853
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
795
854
  }
796
855
  
797
856
  if(quit_now){
799
858
    goto mandos_end;
800
859
  }
801
860
  
802
 
  /* Spurious warning from -Wint-to-pointer-cast */
803
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
861
  /* This casting via intptr_t is to eliminate warning about casting
 
862
     an int to a pointer type.  This is exactly how the GnuTLS Guile
 
863
     function "set-session-transport-fd!" does it. */
 
864
  gnutls_transport_set_ptr(session,
 
865
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
804
866
  
805
867
  if(quit_now){
806
868
    errno = EINTR;
817
879
  
818
880
  if(ret != GNUTLS_E_SUCCESS){
819
881
    if(debug){
820
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
882
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
821
883
      gnutls_perror(ret);
822
884
    }
823
885
    errno = EPROTO;
827
889
  /* Read OpenPGP packet that contains the wanted password */
828
890
  
829
891
  if(debug){
830
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
831
 
            ip);
 
892
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
893
                 " %s\n", ip);
832
894
  }
833
895
  
834
896
  while(true){
839
901
    }
840
902
    
841
903
    buffer_capacity = incbuffer(&buffer, buffer_length,
842
 
                                   buffer_capacity);
 
904
                                buffer_capacity);
843
905
    if(buffer_capacity == 0){
844
906
      int e = errno;
845
907
      perror_plus("incbuffer");
872
934
          }
873
935
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
874
936
        if(ret < 0){
875
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
937
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
938
                       "***\n");
876
939
          gnutls_perror(ret);
877
940
          errno = EPROTO;
878
941
          goto mandos_end;
879
942
        }
880
943
        break;
881
944
      default:
882
 
        fprintf(stderr, "Unknown error while reading data from"
883
 
                " encrypted session with Mandos server\n");
 
945
        fprintf_plus(stderr, "Unknown error while reading data from"
 
946
                     " encrypted session with Mandos server\n");
884
947
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
885
948
        errno = EIO;
886
949
        goto mandos_end;
891
954
  }
892
955
  
893
956
  if(debug){
894
 
    fprintf(stderr, "Closing TLS session\n");
 
957
    fprintf_plus(stderr, "Closing TLS session\n");
895
958
  }
896
959
  
897
960
  if(quit_now){
909
972
  
910
973
  if(buffer_length > 0){
911
974
    ssize_t decrypted_buffer_size;
912
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
913
 
                                               buffer_length,
914
 
                                               &decrypted_buffer);
 
975
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
976
                                               &decrypted_buffer, mc);
915
977
    if(decrypted_buffer_size >= 0){
916
978
      
917
979
      written = 0;
927
989
        if(ret == 0 and ferror(stdout)){
928
990
          int e = errno;
929
991
          if(debug){
930
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
931
 
                    strerror(errno));
 
992
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
993
                         strerror(errno));
932
994
          }
933
995
          errno = e;
934
996
          goto mandos_end;
978
1040
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
979
1041
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
980
1042
                             flags,
981
 
                             AVAHI_GCC_UNUSED void* userdata){
982
 
  assert(r);
 
1043
                             void* mc){
 
1044
  if(r == NULL){
 
1045
    return;
 
1046
  }
983
1047
  
984
1048
  /* Called whenever a service has been resolved successfully or
985
1049
     timed out */
991
1055
  switch(event){
992
1056
  default:
993
1057
  case AVAHI_RESOLVER_FAILURE:
994
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
995
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
996
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1058
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1059
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1060
                 domain,
 
1061
                 avahi_strerror(avahi_server_errno
 
1062
                                (((mandos_context*)mc)->server)));
997
1063
    break;
998
1064
    
999
1065
  case AVAHI_RESOLVER_FOUND:
1001
1067
      char ip[AVAHI_ADDRESS_STR_MAX];
1002
1068
      avahi_address_snprint(ip, sizeof(ip), address);
1003
1069
      if(debug){
1004
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1005
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1006
 
                ip, (intmax_t)interface, port);
 
1070
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1071
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1072
                     host_name, ip, (intmax_t)interface, port);
1007
1073
      }
1008
 
      int ret = start_mandos_communication(ip, port, interface,
1009
 
                                           avahi_proto_to_af(proto));
 
1074
      int ret = start_mandos_communication(ip, (in_port_t)port,
 
1075
                                           interface,
 
1076
                                           avahi_proto_to_af(proto),
 
1077
                                           mc);
1010
1078
      if(ret == 0){
1011
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1079
        avahi_simple_poll_quit(simple_poll);
1012
1080
      } else {
1013
 
        ret = add_server(ip, port, interface,
1014
 
                         avahi_proto_to_af(proto));
 
1081
        if(not add_server(ip, (in_port_t)port, interface,
 
1082
                          avahi_proto_to_af(proto),
 
1083
                          &((mandos_context*)mc)->current_server)){
 
1084
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1085
                       " list\n", name);
 
1086
        }
1015
1087
      }
1016
1088
    }
1017
1089
  }
1027
1099
                            const char *domain,
1028
1100
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1029
1101
                            flags,
1030
 
                            AVAHI_GCC_UNUSED void* userdata){
1031
 
  assert(b);
 
1102
                            void* mc){
 
1103
  if(b == NULL){
 
1104
    return;
 
1105
  }
1032
1106
  
1033
1107
  /* Called whenever a new services becomes available on the LAN or
1034
1108
     is removed from the LAN */
1041
1115
  default:
1042
1116
  case AVAHI_BROWSER_FAILURE:
1043
1117
    
1044
 
    fprintf(stderr, "(Avahi browser) %s\n",
1045
 
            avahi_strerror(avahi_server_errno(mc.server)));
1046
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1118
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1119
                 avahi_strerror(avahi_server_errno
 
1120
                                (((mandos_context*)mc)->server)));
 
1121
    avahi_simple_poll_quit(simple_poll);
1047
1122
    return;
1048
1123
    
1049
1124
  case AVAHI_BROWSER_NEW:
1052
1127
       the callback function is called the Avahi server will free the
1053
1128
       resolver for us. */
1054
1129
    
1055
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1056
 
                                    name, type, domain, protocol, 0,
1057
 
                                    resolve_callback, NULL) == NULL)
1058
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1059
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1130
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
 
1131
                                    interface, protocol, name, type,
 
1132
                                    domain, protocol, 0,
 
1133
                                    resolve_callback, mc) == NULL)
 
1134
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1135
                   " %s\n", name,
 
1136
                   avahi_strerror(avahi_server_errno
 
1137
                                  (((mandos_context*)mc)->server)));
1060
1138
    break;
1061
1139
    
1062
1140
  case AVAHI_BROWSER_REMOVE:
1065
1143
  case AVAHI_BROWSER_ALL_FOR_NOW:
1066
1144
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1067
1145
    if(debug){
1068
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1146
      fprintf_plus(stderr, "No Mandos server found, still"
 
1147
                   " searching...\n");
1069
1148
    }
1070
1149
    break;
1071
1150
  }
1080
1159
  signal_received = sig;
1081
1160
  int old_errno = errno;
1082
1161
  /* set main loop to exit */
1083
 
  if(mc.simple_poll != NULL){
1084
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1162
  if(simple_poll != NULL){
 
1163
    avahi_simple_poll_quit(simple_poll);
1085
1164
  }
1086
1165
  errno = old_errno;
1087
1166
}
1088
1167
 
1089
1168
bool get_flags(const char *ifname, struct ifreq *ifr){
1090
1169
  int ret;
 
1170
  error_t ret_errno;
1091
1171
  
1092
1172
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1093
1173
  if(s < 0){
 
1174
    ret_errno = errno;
1094
1175
    perror_plus("socket");
 
1176
    errno = ret_errno;
1095
1177
    return false;
1096
1178
  }
1097
1179
  strcpy(ifr->ifr_name, ifname);
1098
1180
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1099
1181
  if(ret == -1){
1100
1182
    if(debug){
 
1183
      ret_errno = errno;
1101
1184
      perror_plus("ioctl SIOCGIFFLAGS");
 
1185
      errno = ret_errno;
1102
1186
    }
1103
1187
    return false;
1104
1188
  }
1110
1194
  /* Reject the loopback device */
1111
1195
  if(ifr->ifr_flags & IFF_LOOPBACK){
1112
1196
    if(debug){
1113
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1114
 
              ifname);
 
1197
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1198
                   ifname);
1115
1199
    }
1116
1200
    return false;
1117
1201
  }
1118
1202
  /* Accept point-to-point devices only if connect_to is specified */
1119
1203
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1120
1204
    if(debug){
1121
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1122
 
              ifname);
 
1205
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1206
                   " \"%s\"\n", ifname);
1123
1207
    }
1124
1208
    return true;
1125
1209
  }
1126
1210
  /* Otherwise, reject non-broadcast-capable devices */
1127
1211
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1128
1212
    if(debug){
1129
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1130
 
              ifname);
 
1213
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1214
                   " \"%s\"\n", ifname);
1131
1215
    }
1132
1216
    return false;
1133
1217
  }
1134
1218
  /* Reject non-ARP interfaces (including dummy interfaces) */
1135
1219
  if(ifr->ifr_flags & IFF_NOARP){
1136
1220
    if(debug){
1137
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1221
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1222
                   ifname);
1138
1223
    }
1139
1224
    return false;
1140
1225
  }
1141
1226
  
1142
1227
  /* Accept this device */
1143
1228
  if(debug){
1144
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
 
1229
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1145
1230
  }
1146
1231
  return true;
1147
1232
}
1159
1244
  struct ifreq ifr;
1160
1245
  if(not get_flags(if_entry->d_name, &ifr)){
1161
1246
    if(debug){
1162
 
      fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1163
 
              if_entry->d_name);
1164
 
    }
1165
 
    return 0;
1166
 
  }
1167
 
  
1168
 
  if(not good_flags(if_entry->d_name, &ifr)){
1169
 
    return 0;
1170
 
  }
1171
 
  return 1;
1172
 
}
1173
 
 
1174
 
/* 
1175
 
 * This function determines if a directory entry in /sys/class/net
1176
 
 * corresponds to an acceptable network device which is up.
1177
 
 * (This function is passed to scandir(3) as a filter function.)
1178
 
 */
1179
 
int up_interface(const struct dirent *if_entry){
1180
 
  if(if_entry->d_name[0] == '.'){
1181
 
    return 0;
1182
 
  }
1183
 
  
1184
 
  struct ifreq ifr;
1185
 
  if(not get_flags(if_entry->d_name, &ifr)){
1186
 
    if(debug){
1187
 
      fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1188
 
              if_entry->d_name);
1189
 
    }
1190
 
    return 0;
1191
 
  }
1192
 
  
1193
 
  /* Reject down interfaces */
1194
 
  if(not (ifr.ifr_flags & IFF_UP)){
1195
 
    if(debug){
1196
 
      fprintf(stderr, "Rejecting down interface \"%s\"\n",
1197
 
              if_entry->d_name);
1198
 
    }
1199
 
    return 0;
1200
 
  }
1201
 
  
1202
 
  /* Reject non-running interfaces */
1203
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1204
 
    if(debug){
1205
 
      fprintf(stderr, "Rejecting non-running interface \"%s\"\n",
1206
 
              if_entry->d_name);
1207
 
    }
1208
 
    return 0;
1209
 
  }
1210
 
  
1211
 
  if(not good_flags(if_entry->d_name, &ifr)){
1212
 
    return 0;
1213
 
  }
1214
 
  return 1;
 
1247
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1248
                   "\"%s\"\n", if_entry->d_name);
 
1249
    }
 
1250
    return 0;
 
1251
  }
 
1252
  
 
1253
  if(not good_flags(if_entry->d_name, &ifr)){
 
1254
    return 0;
 
1255
  }
 
1256
  return 1;
 
1257
}
 
1258
 
 
1259
/* 
 
1260
 * This function determines if a network interface is up.
 
1261
 */
 
1262
bool interface_is_up(const char *interface){
 
1263
  struct ifreq ifr;
 
1264
  if(not get_flags(interface, &ifr)){
 
1265
    if(debug){
 
1266
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1267
                   "\"%s\"\n", interface);
 
1268
    }
 
1269
    return false;
 
1270
  }
 
1271
  
 
1272
  return (bool)(ifr.ifr_flags & IFF_UP);
 
1273
}
 
1274
 
 
1275
/* 
 
1276
 * This function determines if a network interface is running
 
1277
 */
 
1278
bool interface_is_running(const char *interface){
 
1279
  struct ifreq ifr;
 
1280
  if(not get_flags(interface, &ifr)){
 
1281
    if(debug){
 
1282
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1283
                   "\"%s\"\n", interface);
 
1284
    }
 
1285
    return false;
 
1286
  }
 
1287
  
 
1288
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1215
1289
}
1216
1290
 
1217
1291
int notdotentries(const struct dirent *direntry){
1228
1302
/* Is this directory entry a runnable program? */
1229
1303
int runnable_hook(const struct dirent *direntry){
1230
1304
  int ret;
 
1305
  size_t sret;
1231
1306
  struct stat st;
1232
1307
  
1233
1308
  if((direntry->d_name)[0] == '\0'){
1235
1310
    return 0;
1236
1311
  }
1237
1312
  
1238
 
  /* Save pointer to last character */
1239
 
  char *end = strchr(direntry->d_name, '\0')-1;
1240
 
  
1241
 
  if(*end == '~'){
1242
 
    /* Backup name~ */
1243
 
    return 0;
1244
 
  }
1245
 
  
1246
 
  if(((direntry->d_name)[0] == '#')
1247
 
     and (*end == '#')){
1248
 
    /* Temporary #name# */
1249
 
    return 0;
1250
 
  }
1251
 
  
1252
 
  /* XXX more rules here */
1253
 
  
1254
 
  ret = stat(direntry->d_name, &st);
 
1313
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1314
                "abcdefghijklmnopqrstuvwxyz"
 
1315
                "0123456789"
 
1316
                "_-");
 
1317
  if((direntry->d_name)[sret] != '\0'){
 
1318
    /* Contains non-allowed characters */
 
1319
    if(debug){
 
1320
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1321
                   direntry->d_name);
 
1322
    }
 
1323
    return 0;
 
1324
  }
 
1325
  
 
1326
  char *fullname = NULL;
 
1327
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1328
  if(ret < 0){
 
1329
    perror_plus("asprintf");
 
1330
    return 0;
 
1331
  }
 
1332
  
 
1333
  ret = stat(fullname, &st);
1255
1334
  if(ret == -1){
1256
1335
    if(debug){
1257
 
      perror_plus("Could not stat plugin");
 
1336
      perror_plus("Could not stat hook");
1258
1337
    }
1259
1338
    return 0;
1260
1339
  }
1261
1340
  if(not (S_ISREG(st.st_mode))){
1262
1341
    /* Not a regular file */
 
1342
    if(debug){
 
1343
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1344
                   direntry->d_name);
 
1345
    }
1263
1346
    return 0;
1264
1347
  }
1265
1348
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1266
1349
    /* Not executable */
 
1350
    if(debug){
 
1351
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1352
                   direntry->d_name);
 
1353
    }
1267
1354
    return 0;
1268
1355
  }
 
1356
  if(debug){
 
1357
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1358
                 direntry->d_name);
 
1359
  }
1269
1360
  return 1;
1270
1361
}
1271
1362
 
1272
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1363
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
 
1364
                            mandos_context *mc){
1273
1365
  int ret;
1274
1366
  struct timespec now;
1275
1367
  struct timespec waited_time;
1276
1368
  intmax_t block_time;
1277
1369
  
1278
1370
  while(true){
1279
 
    if(mc.current_server == NULL){
 
1371
    if(mc->current_server == NULL){
1280
1372
      if (debug){
1281
 
        fprintf(stderr,
1282
 
                "Wait until first server is found. No timeout!\n");
 
1373
        fprintf_plus(stderr, "Wait until first server is found."
 
1374
                     " No timeout!\n");
1283
1375
      }
1284
1376
      ret = avahi_simple_poll_iterate(s, -1);
1285
1377
    } else {
1286
1378
      if (debug){
1287
 
        fprintf(stderr, "Check current_server if we should run it,"
1288
 
                " or wait\n");
 
1379
        fprintf_plus(stderr, "Check current_server if we should run"
 
1380
                     " it, or wait\n");
1289
1381
      }
1290
1382
      /* the current time */
1291
1383
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1296
1388
      /* Calculating in ms how long time between now and server
1297
1389
         who we visted longest time ago. Now - last seen.  */
1298
1390
      waited_time.tv_sec = (now.tv_sec
1299
 
                            - mc.current_server->last_seen.tv_sec);
 
1391
                            - mc->current_server->last_seen.tv_sec);
1300
1392
      waited_time.tv_nsec = (now.tv_nsec
1301
 
                             - mc.current_server->last_seen.tv_nsec);
 
1393
                             - mc->current_server->last_seen.tv_nsec);
1302
1394
      /* total time is 10s/10,000ms.
1303
1395
         Converting to s from ms by dividing by 1,000,
1304
1396
         and ns to ms by dividing by 1,000,000. */
1307
1399
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1308
1400
      
1309
1401
      if (debug){
1310
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1402
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1403
                     block_time);
1311
1404
      }
1312
1405
      
1313
1406
      if(block_time <= 0){
1314
 
        ret = start_mandos_communication(mc.current_server->ip,
1315
 
                                         mc.current_server->port,
1316
 
                                         mc.current_server->if_index,
1317
 
                                         mc.current_server->af);
 
1407
        ret = start_mandos_communication(mc->current_server->ip,
 
1408
                                         mc->current_server->port,
 
1409
                                         mc->current_server->if_index,
 
1410
                                         mc->current_server->af, mc);
1318
1411
        if(ret == 0){
1319
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1412
          avahi_simple_poll_quit(s);
1320
1413
          return 0;
1321
1414
        }
1322
1415
        ret = clock_gettime(CLOCK_MONOTONIC,
1323
 
                            &mc.current_server->last_seen);
 
1416
                            &mc->current_server->last_seen);
1324
1417
        if(ret == -1){
1325
1418
          perror_plus("clock_gettime");
1326
1419
          return -1;
1327
1420
        }
1328
 
        mc.current_server = mc.current_server->next;
 
1421
        mc->current_server = mc->current_server->next;
1329
1422
        block_time = 0;         /* Call avahi to find new Mandos
1330
1423
                                   servers, but don't block */
1331
1424
      }
1333
1426
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1334
1427
    }
1335
1428
    if(ret != 0){
1336
 
      if (ret > 0 or errno != EINTR) {
 
1429
      if (ret > 0 or errno != EINTR){
1337
1430
        return (ret != 1) ? ret : 0;
1338
1431
      }
1339
1432
    }
1340
1433
  }
1341
1434
}
1342
1435
 
 
1436
/* Set effective uid to 0, return errno */
 
1437
error_t raise_privileges(void){
 
1438
  error_t old_errno = errno;
 
1439
  error_t ret_errno = 0;
 
1440
  if(seteuid(0) == -1){
 
1441
    ret_errno = errno;
 
1442
    perror_plus("seteuid");
 
1443
  }
 
1444
  errno = old_errno;
 
1445
  return ret_errno;
 
1446
}
 
1447
 
 
1448
/* Set effective and real user ID to 0.  Return errno. */
 
1449
error_t raise_privileges_permanently(void){
 
1450
  error_t old_errno = errno;
 
1451
  error_t ret_errno = raise_privileges();
 
1452
  if(ret_errno != 0){
 
1453
    errno = old_errno;
 
1454
    return ret_errno;
 
1455
  }
 
1456
  if(setuid(0) == -1){
 
1457
    ret_errno = errno;
 
1458
    perror_plus("seteuid");
 
1459
  }
 
1460
  errno = old_errno;
 
1461
  return ret_errno;
 
1462
}
 
1463
 
 
1464
/* Set effective user ID to unprivileged saved user ID */
 
1465
error_t lower_privileges(void){
 
1466
  error_t old_errno = errno;
 
1467
  error_t ret_errno = 0;
 
1468
  if(seteuid(uid) == -1){
 
1469
    ret_errno = errno;
 
1470
    perror_plus("seteuid");
 
1471
  }
 
1472
  errno = old_errno;
 
1473
  return ret_errno;
 
1474
}
 
1475
 
 
1476
/* Lower privileges permanently */
 
1477
error_t lower_privileges_permanently(void){
 
1478
  error_t old_errno = errno;
 
1479
  error_t ret_errno = 0;
 
1480
  if(setuid(uid) == -1){
 
1481
    ret_errno = errno;
 
1482
    perror_plus("setuid");
 
1483
  }
 
1484
  errno = old_errno;
 
1485
  return ret_errno;
 
1486
}
 
1487
 
 
1488
bool run_network_hooks(const char *mode, const char *interface,
 
1489
                       const float delay){
 
1490
  struct dirent **direntries;
 
1491
  struct dirent *direntry;
 
1492
  int ret;
 
1493
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1494
                         alphasort);
 
1495
  if(numhooks == -1){
 
1496
    if(errno == ENOENT){
 
1497
      if(debug){
 
1498
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1499
                     " found\n", hookdir);
 
1500
      }
 
1501
    } else {
 
1502
      perror_plus("scandir");
 
1503
    }
 
1504
  } else {
 
1505
    int devnull = open("/dev/null", O_RDONLY);
 
1506
    for(int i = 0; i < numhooks; i++){
 
1507
      direntry = direntries[i];
 
1508
      char *fullname = NULL;
 
1509
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1510
      if(ret < 0){
 
1511
        perror_plus("asprintf");
 
1512
        continue;
 
1513
      }
 
1514
      if(debug){
 
1515
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1516
                     direntry->d_name);
 
1517
      }
 
1518
      pid_t hook_pid = fork();
 
1519
      if(hook_pid == 0){
 
1520
        /* Child */
 
1521
        /* Raise privileges */
 
1522
        raise_privileges_permanently();
 
1523
        /* Set group */
 
1524
        errno = 0;
 
1525
        ret = setgid(0);
 
1526
        if(ret == -1){
 
1527
          perror_plus("setgid");
 
1528
        }
 
1529
        /* Reset supplementary groups */
 
1530
        errno = 0;
 
1531
        ret = setgroups(0, NULL);
 
1532
        if(ret == -1){
 
1533
          perror_plus("setgroups");
 
1534
        }
 
1535
        dup2(devnull, STDIN_FILENO);
 
1536
        close(devnull);
 
1537
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1538
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1539
        if(ret == -1){
 
1540
          perror_plus("setenv");
 
1541
          _exit(EX_OSERR);
 
1542
        }
 
1543
        ret = setenv("DEVICE", interface, 1);
 
1544
        if(ret == -1){
 
1545
          perror_plus("setenv");
 
1546
          _exit(EX_OSERR);
 
1547
        }
 
1548
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1549
        if(ret == -1){
 
1550
          perror_plus("setenv");
 
1551
          _exit(EX_OSERR);
 
1552
        }
 
1553
        ret = setenv("MODE", mode, 1);
 
1554
        if(ret == -1){
 
1555
          perror_plus("setenv");
 
1556
          _exit(EX_OSERR);
 
1557
        }
 
1558
        char *delaystring;
 
1559
        ret = asprintf(&delaystring, "%f", delay);
 
1560
        if(ret == -1){
 
1561
          perror_plus("asprintf");
 
1562
          _exit(EX_OSERR);
 
1563
        }
 
1564
        ret = setenv("DELAY", delaystring, 1);
 
1565
        if(ret == -1){
 
1566
          free(delaystring);
 
1567
          perror_plus("setenv");
 
1568
          _exit(EX_OSERR);
 
1569
        }
 
1570
        free(delaystring);
 
1571
        if(connect_to != NULL){
 
1572
          ret = setenv("CONNECT", connect_to, 1);
 
1573
          if(ret == -1){
 
1574
            perror_plus("setenv");
 
1575
            _exit(EX_OSERR);
 
1576
          }
 
1577
        }
 
1578
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1579
          perror_plus("execl");
 
1580
          _exit(EXIT_FAILURE);
 
1581
        }
 
1582
      } else {
 
1583
        int status;
 
1584
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1585
          perror_plus("waitpid");
 
1586
          free(fullname);
 
1587
          continue;
 
1588
        }
 
1589
        if(WIFEXITED(status)){
 
1590
          if(WEXITSTATUS(status) != 0){
 
1591
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1592
                         " with status %d\n", direntry->d_name,
 
1593
                         WEXITSTATUS(status));
 
1594
            free(fullname);
 
1595
            continue;
 
1596
          }
 
1597
        } else if(WIFSIGNALED(status)){
 
1598
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1599
                       " signal %d\n", direntry->d_name,
 
1600
                       WTERMSIG(status));
 
1601
          free(fullname);
 
1602
          continue;
 
1603
        } else {
 
1604
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1605
                       " crashed\n", direntry->d_name);
 
1606
          free(fullname);
 
1607
          continue;
 
1608
        }
 
1609
      }
 
1610
      free(fullname);
 
1611
      if(debug){
 
1612
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1613
                     direntry->d_name);
 
1614
      }
 
1615
    }
 
1616
    close(devnull);
 
1617
  }
 
1618
  return true;
 
1619
}
 
1620
 
 
1621
error_t bring_up_interface(const char *const interface,
 
1622
                           const float delay){
 
1623
  int sd = -1;
 
1624
  error_t old_errno = errno;
 
1625
  error_t ret_errno = 0;
 
1626
  int ret, ret_setflags;
 
1627
  struct ifreq network;
 
1628
  unsigned int if_index = if_nametoindex(interface);
 
1629
  if(if_index == 0){
 
1630
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1631
    errno = old_errno;
 
1632
    return ENXIO;
 
1633
  }
 
1634
  
 
1635
  if(quit_now){
 
1636
    errno = old_errno;
 
1637
    return EINTR;
 
1638
  }
 
1639
  
 
1640
  if(not interface_is_up(interface)){
 
1641
    if(not get_flags(interface, &network) and debug){
 
1642
      ret_errno = errno;
 
1643
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1644
                   "\"%s\"\n", interface);
 
1645
      return ret_errno;
 
1646
    }
 
1647
    network.ifr_flags |= IFF_UP;
 
1648
    
 
1649
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1650
    if(sd < 0){
 
1651
      ret_errno = errno;
 
1652
      perror_plus("socket");
 
1653
      errno = old_errno;
 
1654
      return ret_errno;
 
1655
    }
 
1656
  
 
1657
    if(quit_now){
 
1658
      close(sd);
 
1659
      errno = old_errno;
 
1660
      return EINTR;
 
1661
    }
 
1662
    
 
1663
    if(debug){
 
1664
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
 
1665
                   interface);
 
1666
    }
 
1667
    
 
1668
    /* Raise priviliges */
 
1669
    raise_privileges();
 
1670
    
 
1671
#ifdef __linux__
 
1672
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1673
       messages about the network interface to mess up the prompt */
 
1674
    int ret_linux = klogctl(8, NULL, 5);
 
1675
    bool restore_loglevel = true;
 
1676
    if(ret_linux == -1){
 
1677
      restore_loglevel = false;
 
1678
      perror_plus("klogctl");
 
1679
    }
 
1680
#endif  /* __linux__ */
 
1681
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1682
    ret_errno = errno;
 
1683
#ifdef __linux__
 
1684
    if(restore_loglevel){
 
1685
      ret_linux = klogctl(7, NULL, 0);
 
1686
      if(ret_linux == -1){
 
1687
        perror_plus("klogctl");
 
1688
      }
 
1689
    }
 
1690
#endif  /* __linux__ */
 
1691
    
 
1692
    /* Lower privileges */
 
1693
    lower_privileges();
 
1694
    
 
1695
    /* Close the socket */
 
1696
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1697
    if(ret == -1){
 
1698
      perror_plus("close");
 
1699
    }
 
1700
    
 
1701
    if(ret_setflags == -1){
 
1702
      errno = ret_errno;
 
1703
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1704
      errno = old_errno;
 
1705
      return ret_errno;
 
1706
    }
 
1707
  } else if(debug){
 
1708
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
 
1709
                 interface);
 
1710
  }
 
1711
  
 
1712
  /* Sleep checking until interface is running.
 
1713
     Check every 0.25s, up to total time of delay */
 
1714
  for(int i=0; i < delay * 4; i++){
 
1715
    if(interface_is_running(interface)){
 
1716
      break;
 
1717
    }
 
1718
    struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1719
    ret = nanosleep(&sleeptime, NULL);
 
1720
    if(ret == -1 and errno != EINTR){
 
1721
      perror_plus("nanosleep");
 
1722
    }
 
1723
  }
 
1724
  
 
1725
  errno = old_errno;
 
1726
  return 0;
 
1727
}
 
1728
 
 
1729
error_t take_down_interface(const char *const interface){
 
1730
  int sd = -1;
 
1731
  error_t old_errno = errno;
 
1732
  error_t ret_errno = 0;
 
1733
  int ret, ret_setflags;
 
1734
  struct ifreq network;
 
1735
  unsigned int if_index = if_nametoindex(interface);
 
1736
  if(if_index == 0){
 
1737
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1738
    errno = old_errno;
 
1739
    return ENXIO;
 
1740
  }
 
1741
  if(interface_is_up(interface)){
 
1742
    if(not get_flags(interface, &network) and debug){
 
1743
      ret_errno = errno;
 
1744
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1745
                   "\"%s\"\n", interface);
 
1746
      return ret_errno;
 
1747
    }
 
1748
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1749
    
 
1750
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1751
    if(sd < 0){
 
1752
      ret_errno = errno;
 
1753
      perror_plus("socket");
 
1754
      errno = old_errno;
 
1755
      return ret_errno;
 
1756
    }
 
1757
    
 
1758
    if(debug){
 
1759
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
 
1760
                   interface);
 
1761
    }
 
1762
    
 
1763
    /* Raise priviliges */
 
1764
    raise_privileges();
 
1765
    
 
1766
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1767
    ret_errno = errno;
 
1768
    
 
1769
    /* Lower privileges */
 
1770
    lower_privileges();
 
1771
    
 
1772
    /* Close the socket */
 
1773
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1774
    if(ret == -1){
 
1775
      perror_plus("close");
 
1776
    }
 
1777
    
 
1778
    if(ret_setflags == -1){
 
1779
      errno = ret_errno;
 
1780
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1781
      errno = old_errno;
 
1782
      return ret_errno;
 
1783
    }
 
1784
  } else if(debug){
 
1785
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
 
1786
                 interface);
 
1787
  }
 
1788
  
 
1789
  errno = old_errno;
 
1790
  return 0;
 
1791
}
 
1792
 
1343
1793
int main(int argc, char *argv[]){
 
1794
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1795
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1796
                        "+CTYPE-OPENPGP", .current_server = NULL, 
 
1797
                        .interfaces = NULL, .interfaces_size = 0 };
1344
1798
  AvahiSServiceBrowser *sb = NULL;
1345
 
  int error;
 
1799
  error_t ret_errno;
1346
1800
  int ret;
1347
1801
  intmax_t tmpmax;
1348
1802
  char *tmp;
1349
1803
  int exitcode = EXIT_SUCCESS;
1350
 
  const char *interface = "";
1351
 
  struct ifreq network;
1352
 
  int sd = -1;
1353
 
  bool take_down_interface = false;
1354
 
  uid_t uid;
1355
 
  gid_t gid;
 
1804
  char *interfaces_to_take_down = NULL;
 
1805
  size_t interfaces_to_take_down_size = 0;
1356
1806
  char tempdir[] = "/tmp/mandosXXXXXX";
1357
1807
  bool tempdir_created = false;
1358
1808
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1359
1809
  const char *seckey = PATHDIR "/" SECKEY;
1360
1810
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1811
  char *interfaces_hooks = NULL;
 
1812
  size_t interfaces_hooks_size = 0;
1361
1813
  
1362
1814
  bool gnutls_initialized = false;
1363
1815
  bool gpgme_initialized = false;
1425
1877
        .group = 2 },
1426
1878
      { .name = "retry", .key = 132,
1427
1879
        .arg = "SECONDS",
1428
 
        .doc = "Retry interval used when denied by the mandos server",
 
1880
        .doc = "Retry interval used when denied by the Mandos server",
 
1881
        .group = 2 },
 
1882
      { .name = "network-hook-dir", .key = 133,
 
1883
        .arg = "DIR",
 
1884
        .doc = "Directory where network hooks are located",
1429
1885
        .group = 2 },
1430
1886
      /*
1431
1887
       * These reproduce what we would get without ARGP_NO_HELP
1450
1906
        connect_to = arg;
1451
1907
        break;
1452
1908
      case 'i':                 /* --interface */
1453
 
        interface = arg;
 
1909
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
 
1910
                                 arg, (int)',');
 
1911
        if(ret_errno != 0){
 
1912
          argp_error(state, "%s", strerror(ret_errno));
 
1913
        }
1454
1914
        break;
1455
1915
      case 's':                 /* --seckey */
1456
1916
        seckey = arg;
1485
1945
          argp_error(state, "Bad retry interval");
1486
1946
        }
1487
1947
        break;
 
1948
      case 133:                 /* --network-hook-dir */
 
1949
        hookdir = arg;
 
1950
        break;
1488
1951
        /*
1489
1952
         * These reproduce what we would get without ARGP_NO_HELP
1490
1953
         */
1496
1959
        argp_state_help(state, state->out_stream,
1497
1960
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1498
1961
      case 'V':                 /* --version */
1499
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1962
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1500
1963
        exit(argp_err_exit_status);
1501
1964
        break;
1502
1965
      default:
1529
1992
  {
1530
1993
    /* Work around Debian bug #633582:
1531
1994
       <http://bugs.debian.org/633582> */
1532
 
    struct stat st;
1533
1995
    
1534
1996
    /* Re-raise priviliges */
1535
 
    errno = 0;
1536
 
    ret = seteuid(0);
1537
 
    if(ret == -1){
1538
 
      perror_plus("seteuid");
1539
 
    }
1540
 
    
1541
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1542
 
      int seckey_fd = open(seckey, O_RDONLY);
1543
 
      if(seckey_fd == -1){
1544
 
        perror_plus("open");
1545
 
      } else {
1546
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1547
 
        if(ret == -1){
1548
 
          perror_plus("fstat");
1549
 
        } else {
1550
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1551
 
            ret = fchown(seckey_fd, uid, gid);
1552
 
            if(ret == -1){
1553
 
              perror_plus("fchown");
1554
 
            }
1555
 
          }
1556
 
        }
1557
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1558
 
      }
1559
 
    }
1560
 
    
1561
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1562
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1563
 
      if(pubkey_fd == -1){
1564
 
        perror_plus("open");
1565
 
      } else {
1566
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1567
 
        if(ret == -1){
1568
 
          perror_plus("fstat");
1569
 
        } else {
1570
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1571
 
            ret = fchown(pubkey_fd, uid, gid);
1572
 
            if(ret == -1){
1573
 
              perror_plus("fchown");
1574
 
            }
1575
 
          }
1576
 
        }
1577
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1578
 
      }
1579
 
    }
1580
 
    
1581
 
    /* Lower privileges */
1582
 
    errno = 0;
1583
 
    ret = seteuid(uid);
1584
 
    if(ret == -1){
1585
 
      perror_plus("seteuid");
1586
 
    }
1587
 
  }
1588
 
  
1589
 
  /* Find network hooks and run them */
1590
 
  {
1591
 
    struct dirent **direntries;
1592
 
    struct dirent *direntry;
1593
 
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
1594
 
                           alphasort);
1595
 
    int devnull = open("/dev/null", O_RDONLY);
1596
 
    for(int i = 0; i < numhooks; i++){
1597
 
      direntry = direntries[0];
1598
 
      char *fullname = NULL;
1599
 
      ret = asprintf(&fullname, "%s/%s", tempdir,
1600
 
                     direntry->d_name);
1601
 
      if(ret < 0){
1602
 
        perror_plus("asprintf");
1603
 
        continue;
1604
 
      }
1605
 
      pid_t hook_pid = fork();
1606
 
      if(hook_pid == 0){
1607
 
        /* Child */
1608
 
        dup2(devnull, STDIN_FILENO);
1609
 
        close(devnull);
1610
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1611
 
        setenv("DEVICE", interface, 1);
1612
 
        setenv("VERBOSE", debug ? "1" : "0", 1);
1613
 
        setenv("MODE", "start", 1);
1614
 
        /* setenv( XXX more here */
1615
 
        ret = execl(fullname, direntry->d_name, "start", NULL);
1616
 
        perror_plus("execl");
1617
 
      }
1618
 
      free(fullname);
1619
 
      if(quit_now){
 
1997
    if(raise_privileges() == 0){
 
1998
      struct stat st;
 
1999
      
 
2000
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
2001
        int seckey_fd = open(seckey, O_RDONLY);
 
2002
        if(seckey_fd == -1){
 
2003
          perror_plus("open");
 
2004
        } else {
 
2005
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
2006
          if(ret == -1){
 
2007
            perror_plus("fstat");
 
2008
          } else {
 
2009
            if(S_ISREG(st.st_mode)
 
2010
               and st.st_uid == 0 and st.st_gid == 0){
 
2011
              ret = fchown(seckey_fd, uid, gid);
 
2012
              if(ret == -1){
 
2013
                perror_plus("fchown");
 
2014
              }
 
2015
            }
 
2016
          }
 
2017
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2018
        }
 
2019
      }
 
2020
    
 
2021
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
2022
        int pubkey_fd = open(pubkey, O_RDONLY);
 
2023
        if(pubkey_fd == -1){
 
2024
          perror_plus("open");
 
2025
        } else {
 
2026
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
2027
          if(ret == -1){
 
2028
            perror_plus("fstat");
 
2029
          } else {
 
2030
            if(S_ISREG(st.st_mode)
 
2031
               and st.st_uid == 0 and st.st_gid == 0){
 
2032
              ret = fchown(pubkey_fd, uid, gid);
 
2033
              if(ret == -1){
 
2034
                perror_plus("fchown");
 
2035
              }
 
2036
            }
 
2037
          }
 
2038
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2039
        }
 
2040
      }
 
2041
    
 
2042
      /* Lower privileges */
 
2043
      lower_privileges();
 
2044
    }
 
2045
  }
 
2046
  
 
2047
  /* Remove invalid interface names (except "none") */
 
2048
  {
 
2049
    char *interface = NULL;
 
2050
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2051
                                 interface))){
 
2052
      if(strcmp(interface, "none") != 0
 
2053
         and if_nametoindex(interface) == 0){
 
2054
        if(interface[0] != '\0'){
 
2055
          fprintf_plus(stderr, "Not using nonexisting interface"
 
2056
                       " \"%s\"\n", interface);
 
2057
        }
 
2058
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2059
        interface = NULL;
 
2060
      }
 
2061
    }
 
2062
  }
 
2063
  
 
2064
  /* Run network hooks */
 
2065
  {
 
2066
    if(mc.interfaces != NULL){
 
2067
      interfaces_hooks = malloc(mc.interfaces_size);
 
2068
      if(interfaces_hooks == NULL){
 
2069
        perror_plus("malloc");
1620
2070
        goto end;
1621
2071
      }
1622
 
    }
1623
 
    close(devnull);
 
2072
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
 
2073
      interfaces_hooks_size = mc.interfaces_size;
 
2074
      argz_stringify(interfaces_hooks, interfaces_hooks_size,
 
2075
                     (int)',');
 
2076
    }
 
2077
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
 
2078
                             interfaces_hooks : "", delay)){
 
2079
      goto end;
 
2080
    }
1624
2081
  }
1625
2082
  
1626
2083
  if(not debug){
1627
2084
    avahi_set_log_function(empty_log);
1628
2085
  }
1629
2086
  
1630
 
  if(interface[0] == '\0'){
1631
 
    struct dirent **direntries;
1632
 
    /* First look for interfaces that are up */
1633
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1634
 
                  alphasort);
1635
 
    if(ret == 0){
1636
 
      /* No up interfaces, look for any good interfaces */
1637
 
      free(direntries);
1638
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1639
 
                    alphasort);
1640
 
    }
1641
 
    if(ret >= 1){
1642
 
      /* Pick the first interface returned */
1643
 
      interface = strdup(direntries[0]->d_name);
1644
 
      if(debug){
1645
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1646
 
      }
1647
 
      if(interface == NULL){
1648
 
        perror_plus("malloc");
1649
 
        free(direntries);
1650
 
        exitcode = EXIT_FAILURE;
1651
 
        goto end;
1652
 
      }
1653
 
      free(direntries);
1654
 
    } else {
1655
 
      free(direntries);
1656
 
      fprintf(stderr, "Could not find a network interface\n");
1657
 
      exitcode = EXIT_FAILURE;
1658
 
      goto end;
1659
 
    }
1660
 
  }
1661
 
  
1662
2087
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1663
2088
     from the signal handler */
1664
2089
  /* Initialize the pseudo-RNG for Avahi */
1665
2090
  srand((unsigned int) time(NULL));
1666
 
  mc.simple_poll = avahi_simple_poll_new();
1667
 
  if(mc.simple_poll == NULL){
1668
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
2091
  simple_poll = avahi_simple_poll_new();
 
2092
  if(simple_poll == NULL){
 
2093
    fprintf_plus(stderr,
 
2094
                 "Avahi: Failed to create simple poll object.\n");
1669
2095
    exitcode = EX_UNAVAILABLE;
1670
2096
    goto end;
1671
2097
  }
1733
2159
    }
1734
2160
  }
1735
2161
  
1736
 
  /* If the interface is down, bring it up */
1737
 
  if(strcmp(interface, "none") != 0){
1738
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1739
 
    if(if_index == 0){
1740
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1741
 
      exitcode = EX_UNAVAILABLE;
1742
 
      goto end;
1743
 
    }
1744
 
    
1745
 
    if(quit_now){
1746
 
      goto end;
1747
 
    }
1748
 
    
1749
 
    /* Re-raise priviliges */
1750
 
    errno = 0;
1751
 
    ret = seteuid(0);
1752
 
    if(ret == -1){
1753
 
      perror_plus("seteuid");
1754
 
    }
1755
 
    
1756
 
#ifdef __linux__
1757
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1758
 
       messages about the network interface to mess up the prompt */
1759
 
    ret = klogctl(8, NULL, 5);
1760
 
    bool restore_loglevel = true;
1761
 
    if(ret == -1){
1762
 
      restore_loglevel = false;
1763
 
      perror_plus("klogctl");
1764
 
    }
1765
 
#endif  /* __linux__ */
1766
 
    
1767
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1768
 
    if(sd < 0){
1769
 
      perror_plus("socket");
1770
 
      exitcode = EX_OSERR;
1771
 
#ifdef __linux__
1772
 
      if(restore_loglevel){
1773
 
        ret = klogctl(7, NULL, 0);
1774
 
        if(ret == -1){
1775
 
          perror_plus("klogctl");
1776
 
        }
1777
 
      }
1778
 
#endif  /* __linux__ */
1779
 
      /* Lower privileges */
1780
 
      errno = 0;
1781
 
      ret = seteuid(uid);
1782
 
      if(ret == -1){
1783
 
        perror_plus("seteuid");
1784
 
      }
1785
 
      goto end;
1786
 
    }
1787
 
    strcpy(network.ifr_name, interface);
1788
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1789
 
    if(ret == -1){
1790
 
      perror_plus("ioctl SIOCGIFFLAGS");
1791
 
#ifdef __linux__
1792
 
      if(restore_loglevel){
1793
 
        ret = klogctl(7, NULL, 0);
1794
 
        if(ret == -1){
1795
 
          perror_plus("klogctl");
1796
 
        }
1797
 
      }
1798
 
#endif  /* __linux__ */
1799
 
      exitcode = EX_OSERR;
1800
 
      /* Lower privileges */
1801
 
      errno = 0;
1802
 
      ret = seteuid(uid);
1803
 
      if(ret == -1){
1804
 
        perror_plus("seteuid");
1805
 
      }
1806
 
      goto end;
1807
 
    }
1808
 
    if((network.ifr_flags & IFF_UP) == 0){
1809
 
      network.ifr_flags |= IFF_UP;
1810
 
      take_down_interface = true;
1811
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1812
 
      if(ret == -1){
1813
 
        take_down_interface = false;
1814
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1815
 
        exitcode = EX_OSERR;
1816
 
#ifdef __linux__
1817
 
        if(restore_loglevel){
1818
 
          ret = klogctl(7, NULL, 0);
1819
 
          if(ret == -1){
1820
 
            perror_plus("klogctl");
 
2162
  /* If no interfaces were specified, make a list */
 
2163
  if(mc.interfaces == NULL){
 
2164
    struct dirent **direntries;
 
2165
    /* Look for any good interfaces */
 
2166
    ret = scandir(sys_class_net, &direntries, good_interface,
 
2167
                  alphasort);
 
2168
    if(ret >= 1){
 
2169
      /* Add all found interfaces to interfaces list */
 
2170
      for(int i = 0; i < ret; ++i){
 
2171
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2172
                             direntries[i]->d_name);
 
2173
        if(ret_errno != 0){
 
2174
          perror_plus("argz_add");
 
2175
          continue;
 
2176
        }
 
2177
        if(debug){
 
2178
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
 
2179
                       direntries[i]->d_name);
 
2180
        }
 
2181
      }
 
2182
      free(direntries);
 
2183
    } else {
 
2184
      free(direntries);
 
2185
      fprintf_plus(stderr, "Could not find a network interface\n");
 
2186
      exitcode = EXIT_FAILURE;
 
2187
      goto end;
 
2188
    }
 
2189
  }
 
2190
  
 
2191
  /* Bring up interfaces which are down, and remove any "none"s */
 
2192
  {
 
2193
    char *interface = NULL;
 
2194
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2195
                                 interface))){
 
2196
      /* If interface name is "none", stop bringing up interfaces.
 
2197
         Also remove all instances of "none" from the list */
 
2198
      if(strcmp(interface, "none") == 0){
 
2199
        argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2200
                    interface);
 
2201
        interface = NULL;
 
2202
        while((interface = argz_next(mc.interfaces,
 
2203
                                     mc.interfaces_size, interface))){
 
2204
          if(strcmp(interface, "none") == 0){
 
2205
            argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2206
                        interface);
 
2207
            interface = NULL;
1821
2208
          }
1822
2209
        }
1823
 
#endif  /* __linux__ */
1824
 
        /* Lower privileges */
1825
 
        errno = 0;
1826
 
        ret = seteuid(uid);
1827
 
        if(ret == -1){
1828
 
          perror_plus("seteuid");
1829
 
        }
1830
 
        goto end;
1831
 
      }
1832
 
    }
1833
 
    /* Sleep checking until interface is running.
1834
 
       Check every 0.25s, up to total time of delay */
1835
 
    for(int i=0; i < delay * 4; i++){
1836
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1837
 
      if(ret == -1){
1838
 
        perror_plus("ioctl SIOCGIFFLAGS");
1839
 
      } else if(network.ifr_flags & IFF_RUNNING){
1840
2210
        break;
1841
2211
      }
1842
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1843
 
      ret = nanosleep(&sleeptime, NULL);
1844
 
      if(ret == -1 and errno != EINTR){
1845
 
        perror_plus("nanosleep");
1846
 
      }
1847
 
    }
1848
 
    if(not take_down_interface){
1849
 
      /* We won't need the socket anymore */
1850
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1851
 
      if(ret == -1){
1852
 
        perror_plus("close");
1853
 
      }
1854
 
    }
1855
 
#ifdef __linux__
1856
 
    if(restore_loglevel){
1857
 
      /* Restores kernel loglevel to default */
1858
 
      ret = klogctl(7, NULL, 0);
1859
 
      if(ret == -1){
1860
 
        perror_plus("klogctl");
1861
 
      }
1862
 
    }
1863
 
#endif  /* __linux__ */
1864
 
    /* Lower privileges */
1865
 
    errno = 0;
1866
 
    if(take_down_interface){
1867
 
      /* Lower privileges */
1868
 
      ret = seteuid(uid);
1869
 
      if(ret == -1){
1870
 
        perror_plus("seteuid");
1871
 
      }
1872
 
    } else {
1873
 
      /* Lower privileges permanently */
1874
 
      ret = setuid(uid);
1875
 
      if(ret == -1){
1876
 
        perror_plus("setuid");
1877
 
      }
1878
 
    }
 
2212
      bool interface_was_up = interface_is_up(interface);
 
2213
      ret = bring_up_interface(interface, delay);
 
2214
      if(not interface_was_up){
 
2215
        if(ret != 0){
 
2216
          errno = ret;
 
2217
          perror_plus("Failed to bring up interface");
 
2218
        } else {
 
2219
          ret_errno = argz_add(&interfaces_to_take_down,
 
2220
                               &interfaces_to_take_down_size,
 
2221
                               interface);
 
2222
        }
 
2223
      }
 
2224
    }
 
2225
    if(debug and (interfaces_to_take_down == NULL)){
 
2226
      fprintf_plus(stderr, "No interfaces were brought up\n");
 
2227
    }
 
2228
  }
 
2229
  
 
2230
  /* If we only got one interface, explicitly use only that one */
 
2231
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
 
2232
    if(debug){
 
2233
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2234
                   mc.interfaces);
 
2235
    }
 
2236
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
1879
2237
  }
1880
2238
  
1881
2239
  if(quit_now){
1882
2240
    goto end;
1883
2241
  }
1884
2242
  
1885
 
  ret = init_gnutls_global(pubkey, seckey);
 
2243
  ret = init_gnutls_global(pubkey, seckey, &mc);
1886
2244
  if(ret == -1){
1887
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2245
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1888
2246
    exitcode = EX_UNAVAILABLE;
1889
2247
    goto end;
1890
2248
  } else {
1905
2263
    goto end;
1906
2264
  }
1907
2265
  
1908
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
1909
 
    fprintf(stderr, "init_gpgme failed\n");
 
2266
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2267
    fprintf_plus(stderr, "init_gpgme failed\n");
1910
2268
    exitcode = EX_UNAVAILABLE;
1911
2269
    goto end;
1912
2270
  } else {
1921
2279
    /* Connect directly, do not use Zeroconf */
1922
2280
    /* (Mainly meant for debugging) */
1923
2281
    char *address = strrchr(connect_to, ':');
 
2282
    
1924
2283
    if(address == NULL){
1925
 
      fprintf(stderr, "No colon in address\n");
 
2284
      fprintf_plus(stderr, "No colon in address\n");
1926
2285
      exitcode = EX_USAGE;
1927
2286
      goto end;
1928
2287
    }
1931
2290
      goto end;
1932
2291
    }
1933
2292
    
1934
 
    uint16_t port;
 
2293
    in_port_t port;
1935
2294
    errno = 0;
1936
2295
    tmpmax = strtoimax(address+1, &tmp, 10);
1937
2296
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1938
 
       or tmpmax != (uint16_t)tmpmax){
1939
 
      fprintf(stderr, "Bad port number\n");
 
2297
       or tmpmax != (in_port_t)tmpmax){
 
2298
      fprintf_plus(stderr, "Bad port number\n");
1940
2299
      exitcode = EX_USAGE;
1941
2300
      goto end;
1942
2301
    }
1943
 
  
 
2302
    
1944
2303
    if(quit_now){
1945
2304
      goto end;
1946
2305
    }
1947
2306
    
1948
 
    port = (uint16_t)tmpmax;
 
2307
    port = (in_port_t)tmpmax;
1949
2308
    *address = '\0';
1950
2309
    /* Colon in address indicates IPv6 */
1951
2310
    int af;
1967
2326
    }
1968
2327
    
1969
2328
    while(not quit_now){
1970
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2329
      ret = start_mandos_communication(address, port, if_index, af,
 
2330
                                       &mc);
1971
2331
      if(quit_now or ret == 0){
1972
2332
        break;
1973
2333
      }
1974
2334
      if(debug){
1975
 
        fprintf(stderr, "Retrying in %d seconds\n",
1976
 
                (int)retry_interval);
 
2335
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2336
                     (int)retry_interval);
1977
2337
      }
1978
 
      sleep((int)retry_interval);
 
2338
      sleep((unsigned int)retry_interval);
1979
2339
    }
1980
2340
    
1981
2341
    if (not quit_now){
1999
2359
    config.publish_domain = 0;
2000
2360
    
2001
2361
    /* Allocate a new server */
2002
 
    mc.server = avahi_server_new(avahi_simple_poll_get
2003
 
                                 (mc.simple_poll), &config, NULL,
2004
 
                                 NULL, &error);
 
2362
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2363
                                 &config, NULL, NULL, &ret_errno);
2005
2364
    
2006
2365
    /* Free the Avahi configuration data */
2007
2366
    avahi_server_config_free(&config);
2009
2368
  
2010
2369
  /* Check if creating the Avahi server object succeeded */
2011
2370
  if(mc.server == NULL){
2012
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2013
 
            avahi_strerror(error));
 
2371
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2372
                 avahi_strerror(ret_errno));
2014
2373
    exitcode = EX_UNAVAILABLE;
2015
2374
    goto end;
2016
2375
  }
2022
2381
  /* Create the Avahi service browser */
2023
2382
  sb = avahi_s_service_browser_new(mc.server, if_index,
2024
2383
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2025
 
                                   NULL, 0, browse_callback, NULL);
 
2384
                                   NULL, 0, browse_callback,
 
2385
                                   (void *)&mc);
2026
2386
  if(sb == NULL){
2027
 
    fprintf(stderr, "Failed to create service browser: %s\n",
2028
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2387
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2388
                 avahi_strerror(avahi_server_errno(mc.server)));
2029
2389
    exitcode = EX_UNAVAILABLE;
2030
2390
    goto end;
2031
2391
  }
2037
2397
  /* Run the main loop */
2038
2398
  
2039
2399
  if(debug){
2040
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2400
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2041
2401
  }
2042
2402
 
2043
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2044
 
                                (int)(retry_interval * 1000));
 
2403
  ret = avahi_loop_with_timeout(simple_poll,
 
2404
                                (int)(retry_interval * 1000), &mc);
2045
2405
  if(debug){
2046
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2047
 
            (ret == 0) ? "successfully" : "with error");
 
2406
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2407
                 (ret == 0) ? "successfully" : "with error");
2048
2408
  }
2049
2409
  
2050
2410
 end:
2051
2411
  
2052
2412
  if(debug){
2053
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2413
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2054
2414
  }
2055
2415
  
2056
2416
  /* Cleanup things */
 
2417
  free(mc.interfaces);
 
2418
  
2057
2419
  if(sb != NULL)
2058
2420
    avahi_s_service_browser_free(sb);
2059
2421
  
2060
2422
  if(mc.server != NULL)
2061
2423
    avahi_server_free(mc.server);
2062
2424
  
2063
 
  if(mc.simple_poll != NULL)
2064
 
    avahi_simple_poll_free(mc.simple_poll);
 
2425
  if(simple_poll != NULL)
 
2426
    avahi_simple_poll_free(simple_poll);
2065
2427
  
2066
2428
  if(gnutls_initialized){
2067
2429
    gnutls_certificate_free_credentials(mc.cred);
2072
2434
  if(gpgme_initialized){
2073
2435
    gpgme_release(mc.ctx);
2074
2436
  }
2075
 
 
 
2437
  
2076
2438
  /* Cleans up the circular linked list of Mandos servers the client
2077
2439
     has seen */
2078
2440
  if(mc.current_server != NULL){
2084
2446
    }
2085
2447
  }
2086
2448
  
2087
 
  /* XXX run network hooks "stop" here  */
2088
 
  
2089
 
  /* Take down the network interface */
2090
 
  if(take_down_interface){
2091
 
    /* Re-raise priviliges */
2092
 
    errno = 0;
2093
 
    ret = seteuid(0);
2094
 
    if(ret == -1){
2095
 
      perror_plus("seteuid");
2096
 
    }
2097
 
    if(geteuid() == 0){
2098
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2099
 
      if(ret == -1){
2100
 
        perror_plus("ioctl SIOCGIFFLAGS");
2101
 
      } else if(network.ifr_flags & IFF_UP) {
2102
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2103
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2104
 
        if(ret == -1){
2105
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2449
  /* Re-raise priviliges */
 
2450
  {
 
2451
    raise_privileges();
 
2452
    
 
2453
    /* Run network hooks */
 
2454
    run_network_hooks("stop", interfaces_hooks != NULL ?
 
2455
                      interfaces_hooks : "", delay);
 
2456
    
 
2457
    /* Take down the network interfaces which were brought up */
 
2458
    {
 
2459
      char *interface = NULL;
 
2460
      while((interface=argz_next(interfaces_to_take_down,
 
2461
                                 interfaces_to_take_down_size,
 
2462
                                 interface))){
 
2463
        ret_errno = take_down_interface(interface);
 
2464
        if(ret_errno != 0){
 
2465
          errno = ret_errno;
 
2466
          perror_plus("Failed to take down interface");
2106
2467
        }
2107
2468
      }
2108
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2109
 
      if(ret == -1){
2110
 
        perror_plus("close");
2111
 
      }
2112
 
      /* Lower privileges permanently */
2113
 
      errno = 0;
2114
 
      ret = setuid(uid);
2115
 
      if(ret == -1){
2116
 
        perror_plus("setuid");
 
2469
      if(debug and (interfaces_to_take_down == NULL)){
 
2470
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2471
                     " down\n");
2117
2472
      }
2118
2473
    }
 
2474
    
 
2475
    lower_privileges_permanently();
2119
2476
  }
2120
2477
  
 
2478
  free(interfaces_to_take_down);
 
2479
  free(interfaces_hooks);
 
2480
  
2121
2481
  /* Removes the GPGME temp directory and all files inside */
2122
2482
  if(tempdir_created){
2123
2483
    struct dirent **direntries = NULL;
2136
2496
        }
2137
2497
        ret = remove(fullname);
2138
2498
        if(ret == -1){
2139
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2140
 
                  strerror(errno));
 
2499
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2500
                       strerror(errno));
2141
2501
        }
2142
2502
        free(fullname);
2143
2503
      }