/mandos/release

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2014-03-01 09:51:07 UTC
  • mto: (237.7.272 trunk)
  • mto: This revision was merged to the branch mainline in revision 311.
  • Revision ID: teddy@recompile.se-20140301095107-wfcwbmol2a71d3xz
* mandos-keygen (keygen): Add workaround for Debian bug #737128.

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
87
86
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
87
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
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() */
90
94
 
91
95
#ifdef __linux__
92
96
#include <sys/klog.h>           /* klogctl() */
110
114
                                   init_gnutls_session(),
111
115
                                   GNUTLS_* */
112
116
#include <gnutls/openpgp.h>
113
 
                          /* gnutls_certificate_set_openpgp_key_file(),
114
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
117
                         /* gnutls_certificate_set_openpgp_key_file(),
 
118
                            GNUTLS_OPENPGP_FMT_BASE64 */
115
119
 
116
120
/* GPGME */
117
121
#include <gpgme.h>              /* All GPGME types, constants and
133
137
const char *argp_program_bug_address = "<mandos@recompile.se>";
134
138
static const char sys_class_net[] = "/sys/class/net";
135
139
char *connect_to = NULL;
 
140
const char *hookdir = HOOKDIR;
 
141
uid_t uid = 65534;
 
142
gid_t gid = 65534;
136
143
 
137
144
/* Doubly linked list that need to be circularly linked when used */
138
145
typedef struct server{
139
146
  const char *ip;
140
 
  uint16_t port;
 
147
  in_port_t port;
141
148
  AvahiIfIndex if_index;
142
149
  int af;
143
150
  struct timespec last_seen;
147
154
 
148
155
/* Used for passing in values through the Avahi callback functions */
149
156
typedef struct {
150
 
  AvahiSimplePoll *simple_poll;
151
157
  AvahiServer *server;
152
158
  gnutls_certificate_credentials_t cred;
153
159
  unsigned int dh_bits;
155
161
  const char *priority;
156
162
  gpgme_ctx_t ctx;
157
163
  server *current_server;
 
164
  char *interfaces;
 
165
  size_t interfaces_size;
158
166
} mandos_context;
159
167
 
160
 
/* global context so signal handler can reach it*/
161
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
162
 
                      .dh_bits = 1024, .priority = "SECURE256"
163
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
164
 
                      .current_server = NULL };
 
168
/* global so signal handler can reach it*/
 
169
AvahiSimplePoll *simple_poll;
165
170
 
166
171
sig_atomic_t quit_now = 0;
167
172
int signal_received = 0;
168
173
 
169
174
/* Function to use when printing errors */
170
175
void perror_plus(const char *print_text){
 
176
  int e = errno;
171
177
  fprintf(stderr, "Mandos plugin %s: ",
172
178
          program_invocation_short_name);
 
179
  errno = e;
173
180
  perror(print_text);
174
181
}
175
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
 
176
193
/*
177
194
 * Make additional room in "buffer" for at least BUFFER_SIZE more
178
195
 * bytes. "buffer_capacity" is how much is currently allocated,
179
196
 * "buffer_length" is how much is already used.
180
197
 */
181
198
size_t incbuffer(char **buffer, size_t buffer_length,
182
 
                  size_t buffer_capacity){
 
199
                 size_t buffer_capacity){
183
200
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
184
201
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
185
202
    if(buffer == NULL){
191
208
}
192
209
 
193
210
/* Add server to set of servers to retry periodically */
194
 
int add_server(const char *ip, uint16_t port,
195
 
                 AvahiIfIndex if_index,
196
 
                 int af){
 
211
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
 
212
                int af, server **current_server){
197
213
  int ret;
198
214
  server *new_server = malloc(sizeof(server));
199
215
  if(new_server == NULL){
200
216
    perror_plus("malloc");
201
 
    return -1;
 
217
    return false;
202
218
  }
203
219
  *new_server = (server){ .ip = strdup(ip),
204
 
                         .port = port,
205
 
                         .if_index = if_index,
206
 
                         .af = af };
 
220
                          .port = port,
 
221
                          .if_index = if_index,
 
222
                          .af = af };
207
223
  if(new_server->ip == NULL){
208
224
    perror_plus("strdup");
209
 
    return -1;
 
225
    return false;
210
226
  }
211
227
  /* Special case of first server */
212
 
  if (mc.current_server == NULL){
 
228
  if(*current_server == NULL){
213
229
    new_server->next = new_server;
214
230
    new_server->prev = new_server;
215
 
    mc.current_server = new_server;
 
231
    *current_server = new_server;
216
232
  /* Place the new server last in the list */
217
233
  } else {
218
 
    new_server->next = mc.current_server;
219
 
    new_server->prev = mc.current_server->prev;
 
234
    new_server->next = *current_server;
 
235
    new_server->prev = (*current_server)->prev;
220
236
    new_server->prev->next = new_server;
221
 
    mc.current_server->prev = new_server;
 
237
    (*current_server)->prev = new_server;
222
238
  }
223
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
239
  ret = clock_gettime(CLOCK_MONOTONIC, &(*current_server)->last_seen);
224
240
  if(ret == -1){
225
241
    perror_plus("clock_gettime");
226
 
    return -1;
 
242
    return false;
227
243
  }
228
 
  return 0;
 
244
  return true;
229
245
}
230
246
 
231
247
/* 
232
248
 * Initialize GPGME.
233
249
 */
234
 
static bool init_gpgme(const char *seckey,
235
 
                       const char *pubkey, const char *tempdir){
 
250
static bool init_gpgme(const char *seckey, const char *pubkey,
 
251
                       const char *tempdir, mandos_context *mc){
236
252
  gpgme_error_t rc;
237
253
  gpgme_engine_info_t engine_info;
238
254
  
239
 
  
240
255
  /*
241
256
   * Helper function to insert pub and seckey to the engine keyring.
242
257
   */
253
268
    
254
269
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
255
270
    if(rc != GPG_ERR_NO_ERROR){
256
 
      fprintf(stderr, "Mandos plugin mandos-client: "
257
 
              "bad gpgme_data_new_from_fd: %s: %s\n",
258
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
271
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
272
                   gpgme_strsource(rc), gpgme_strerror(rc));
259
273
      return false;
260
274
    }
261
275
    
262
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
276
    rc = gpgme_op_import(mc->ctx, pgp_data);
263
277
    if(rc != GPG_ERR_NO_ERROR){
264
 
      fprintf(stderr, "Mandos plugin mandos-client: "
265
 
              "bad gpgme_op_import: %s: %s\n",
266
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
278
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
279
                   gpgme_strsource(rc), gpgme_strerror(rc));
267
280
      return false;
268
281
    }
269
282
    
276
289
  }
277
290
  
278
291
  if(debug){
279
 
    fprintf(stderr, "Mandos plugin mandos-client: "
280
 
            "Initializing GPGME\n");
 
292
    fprintf_plus(stderr, "Initializing GPGME\n");
281
293
  }
282
294
  
283
295
  /* Init GPGME */
284
296
  gpgme_check_version(NULL);
285
297
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
286
298
  if(rc != GPG_ERR_NO_ERROR){
287
 
    fprintf(stderr, "Mandos plugin mandos-client: "
288
 
            "bad gpgme_engine_check_version: %s: %s\n",
289
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
299
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
300
                 gpgme_strsource(rc), gpgme_strerror(rc));
290
301
    return false;
291
302
  }
292
303
  
293
304
  /* Set GPGME home directory for the OpenPGP engine only */
294
305
  rc = gpgme_get_engine_info(&engine_info);
295
306
  if(rc != GPG_ERR_NO_ERROR){
296
 
    fprintf(stderr, "Mandos plugin mandos-client: "
297
 
            "bad gpgme_get_engine_info: %s: %s\n",
298
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
307
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
308
                 gpgme_strsource(rc), gpgme_strerror(rc));
299
309
    return false;
300
310
  }
301
311
  while(engine_info != NULL){
307
317
    engine_info = engine_info->next;
308
318
  }
309
319
  if(engine_info == NULL){
310
 
    fprintf(stderr, "Mandos plugin mandos-client: "
311
 
            "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);
312
322
    return false;
313
323
  }
314
324
  
315
325
  /* Create new GPGME "context" */
316
 
  rc = gpgme_new(&(mc.ctx));
 
326
  rc = gpgme_new(&(mc->ctx));
317
327
  if(rc != GPG_ERR_NO_ERROR){
318
 
    fprintf(stderr, "Mandos plugin mandos-client: "
319
 
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
320
 
            gpgme_strerror(rc));
 
328
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
329
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
330
                 gpgme_strerror(rc));
321
331
    return false;
322
332
  }
323
333
  
334
344
 */
335
345
static ssize_t pgp_packet_decrypt(const char *cryptotext,
336
346
                                  size_t crypto_size,
337
 
                                  char **plaintext){
 
347
                                  char **plaintext,
 
348
                                  mandos_context *mc){
338
349
  gpgme_data_t dh_crypto, dh_plain;
339
350
  gpgme_error_t rc;
340
351
  ssize_t ret;
342
353
  ssize_t plaintext_length = 0;
343
354
  
344
355
  if(debug){
345
 
    fprintf(stderr, "Mandos plugin mandos-client: "
346
 
            "Trying to decrypt OpenPGP data\n");
 
356
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
347
357
  }
348
358
  
349
359
  /* Create new GPGME data buffer from memory cryptotext */
350
360
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
351
361
                               0);
352
362
  if(rc != GPG_ERR_NO_ERROR){
353
 
    fprintf(stderr, "Mandos plugin mandos-client: "
354
 
            "bad gpgme_data_new_from_mem: %s: %s\n",
355
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
363
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
364
                 gpgme_strsource(rc), gpgme_strerror(rc));
356
365
    return -1;
357
366
  }
358
367
  
359
368
  /* Create new empty GPGME data buffer for the plaintext */
360
369
  rc = gpgme_data_new(&dh_plain);
361
370
  if(rc != GPG_ERR_NO_ERROR){
362
 
    fprintf(stderr, "Mandos plugin mandos-client: "
363
 
            "bad gpgme_data_new: %s: %s\n",
364
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
371
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
372
                 "bad gpgme_data_new: %s: %s\n",
 
373
                 gpgme_strsource(rc), gpgme_strerror(rc));
365
374
    gpgme_data_release(dh_crypto);
366
375
    return -1;
367
376
  }
368
377
  
369
378
  /* Decrypt data from the cryptotext data buffer to the plaintext
370
379
     data buffer */
371
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
380
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
372
381
  if(rc != GPG_ERR_NO_ERROR){
373
 
    fprintf(stderr, "Mandos plugin mandos-client: "
374
 
            "bad gpgme_op_decrypt: %s: %s\n",
375
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
382
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
383
                 gpgme_strsource(rc), gpgme_strerror(rc));
376
384
    plaintext_length = -1;
377
385
    if(debug){
378
386
      gpgme_decrypt_result_t result;
379
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
387
      result = gpgme_op_decrypt_result(mc->ctx);
380
388
      if(result == NULL){
381
 
        fprintf(stderr, "Mandos plugin mandos-client: "
382
 
                "gpgme_op_decrypt_result failed\n");
 
389
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
383
390
      } else {
384
 
        fprintf(stderr, "Mandos plugin mandos-client: "
385
 
                "Unsupported algorithm: %s\n",
386
 
                result->unsupported_algorithm);
387
 
        fprintf(stderr, "Mandos plugin mandos-client: "
388
 
                "Wrong key usage: %u\n",
389
 
                result->wrong_key_usage);
 
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);
390
395
        if(result->file_name != NULL){
391
 
          fprintf(stderr, "Mandos plugin mandos-client: "
392
 
                  "File name: %s\n", result->file_name);
 
396
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
393
397
        }
394
398
        gpgme_recipient_t recipient;
395
399
        recipient = result->recipients;
396
400
        while(recipient != NULL){
397
 
          fprintf(stderr, "Mandos plugin mandos-client: "
398
 
                  "Public key algorithm: %s\n",
399
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
400
 
          fprintf(stderr, "Mandos plugin mandos-client: "
401
 
                  "Key ID: %s\n", recipient->keyid);
402
 
          fprintf(stderr, "Mandos plugin mandos-client: "
403
 
                  "Secret key available: %s\n",
404
 
                  recipient->status == GPG_ERR_NO_SECKEY
405
 
                  ? "No" : "Yes");
 
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");
406
408
          recipient = recipient->next;
407
409
        }
408
410
      }
411
413
  }
412
414
  
413
415
  if(debug){
414
 
    fprintf(stderr, "Mandos plugin mandos-client: "
415
 
            "Decryption of OpenPGP data succeeded\n");
 
416
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
416
417
  }
417
418
  
418
419
  /* Seek back to the beginning of the GPGME plaintext data buffer */
425
426
  *plaintext = NULL;
426
427
  while(true){
427
428
    plaintext_capacity = incbuffer(plaintext,
428
 
                                      (size_t)plaintext_length,
429
 
                                      plaintext_capacity);
 
429
                                   (size_t)plaintext_length,
 
430
                                   plaintext_capacity);
430
431
    if(plaintext_capacity == 0){
431
 
        perror_plus("incbuffer");
432
 
        plaintext_length = -1;
433
 
        goto decrypt_end;
 
432
      perror_plus("incbuffer");
 
433
      plaintext_length = -1;
 
434
      goto decrypt_end;
434
435
    }
435
436
    
436
437
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
449
450
  }
450
451
  
451
452
  if(debug){
452
 
    fprintf(stderr, "Mandos plugin mandos-client: "
453
 
            "Decrypted password is: ");
 
453
    fprintf_plus(stderr, "Decrypted password is: ");
454
454
    for(ssize_t i = 0; i < plaintext_length; i++){
455
455
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
456
456
    }
468
468
}
469
469
 
470
470
static const char * safer_gnutls_strerror(int value){
471
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
472
 
                                               -Wunreachable-code */
 
471
  const char *ret = gnutls_strerror(value);
473
472
  if(ret == NULL)
474
473
    ret = "(unknown)";
475
474
  return ret;
478
477
/* GnuTLS log function callback */
479
478
static void debuggnutls(__attribute__((unused)) int level,
480
479
                        const char* string){
481
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
480
  fprintf_plus(stderr, "GnuTLS: %s", string);
482
481
}
483
482
 
484
483
static int init_gnutls_global(const char *pubkeyfilename,
485
 
                              const char *seckeyfilename){
 
484
                              const char *seckeyfilename,
 
485
                              mandos_context *mc){
486
486
  int ret;
487
487
  
488
488
  if(debug){
489
 
    fprintf(stderr, "Mandos plugin mandos-client: "
490
 
            "Initializing GnuTLS\n");
 
489
    fprintf_plus(stderr, "Initializing GnuTLS\n");
491
490
  }
492
491
  
493
492
  ret = gnutls_global_init();
494
493
  if(ret != GNUTLS_E_SUCCESS){
495
 
    fprintf(stderr, "Mandos plugin mandos-client: "
496
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
494
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
495
                 safer_gnutls_strerror(ret));
497
496
    return -1;
498
497
  }
499
498
  
506
505
  }
507
506
  
508
507
  /* OpenPGP credentials */
509
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
508
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
510
509
  if(ret != GNUTLS_E_SUCCESS){
511
 
    fprintf(stderr, "Mandos plugin mandos-client: "
512
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
510
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
511
                 safer_gnutls_strerror(ret));
513
512
    gnutls_global_deinit();
514
513
    return -1;
515
514
  }
516
515
  
517
516
  if(debug){
518
 
    fprintf(stderr, "Mandos plugin mandos-client: "
519
 
            "Attempting to use OpenPGP public key %s and"
520
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
521
 
            seckeyfilename);
 
517
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
518
                 " secret key %s as GnuTLS credentials\n",
 
519
                 pubkeyfilename,
 
520
                 seckeyfilename);
522
521
  }
523
522
  
524
523
  ret = gnutls_certificate_set_openpgp_key_file
525
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
524
    (mc->cred, pubkeyfilename, seckeyfilename,
526
525
     GNUTLS_OPENPGP_FMT_BASE64);
527
526
  if(ret != GNUTLS_E_SUCCESS){
528
 
    fprintf(stderr,
529
 
            "Mandos plugin mandos-client: "
530
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
531
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
532
 
    fprintf(stderr, "Mandos plugin mandos-client: "
533
 
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
 
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));
534
532
    goto globalfail;
535
533
  }
536
534
  
537
535
  /* GnuTLS server initialization */
538
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
536
  ret = gnutls_dh_params_init(&mc->dh_params);
539
537
  if(ret != GNUTLS_E_SUCCESS){
540
 
    fprintf(stderr, "Mandos plugin mandos-client: "
541
 
            "Error in GnuTLS DH parameter initialization:"
542
 
            " %s\n", safer_gnutls_strerror(ret));
 
538
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
539
                 " initialization: %s\n",
 
540
                 safer_gnutls_strerror(ret));
543
541
    goto globalfail;
544
542
  }
545
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
543
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
546
544
  if(ret != GNUTLS_E_SUCCESS){
547
 
    fprintf(stderr, "Mandos plugin mandos-client: "
548
 
            "Error in GnuTLS prime generation: %s\n",
549
 
            safer_gnutls_strerror(ret));
 
545
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
546
                 safer_gnutls_strerror(ret));
550
547
    goto globalfail;
551
548
  }
552
549
  
553
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
550
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
554
551
  
555
552
  return 0;
556
553
  
557
554
 globalfail:
558
555
  
559
 
  gnutls_certificate_free_credentials(mc.cred);
 
556
  gnutls_certificate_free_credentials(mc->cred);
560
557
  gnutls_global_deinit();
561
 
  gnutls_dh_params_deinit(mc.dh_params);
 
558
  gnutls_dh_params_deinit(mc->dh_params);
562
559
  return -1;
563
560
}
564
561
 
565
 
static int init_gnutls_session(gnutls_session_t *session){
 
562
static int init_gnutls_session(gnutls_session_t *session,
 
563
                               mandos_context *mc){
566
564
  int ret;
567
565
  /* GnuTLS session creation */
568
566
  do {
572
570
    }
573
571
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
574
572
  if(ret != GNUTLS_E_SUCCESS){
575
 
    fprintf(stderr, "Mandos plugin mandos-client: "
576
 
            "Error in GnuTLS session initialization: %s\n",
577
 
            safer_gnutls_strerror(ret));
 
573
    fprintf_plus(stderr,
 
574
                 "Error in GnuTLS session initialization: %s\n",
 
575
                 safer_gnutls_strerror(ret));
578
576
  }
579
577
  
580
578
  {
581
579
    const char *err;
582
580
    do {
583
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
581
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
584
582
      if(quit_now){
585
583
        gnutls_deinit(*session);
586
584
        return -1;
587
585
      }
588
586
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
589
587
    if(ret != GNUTLS_E_SUCCESS){
590
 
      fprintf(stderr, "Mandos plugin mandos-client: "
591
 
              "Syntax error at: %s\n", err);
592
 
      fprintf(stderr, "Mandos plugin mandos-client: "
593
 
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
 
588
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
589
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
590
                   safer_gnutls_strerror(ret));
594
591
      gnutls_deinit(*session);
595
592
      return -1;
596
593
    }
598
595
  
599
596
  do {
600
597
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
601
 
                                 mc.cred);
 
598
                                 mc->cred);
602
599
    if(quit_now){
603
600
      gnutls_deinit(*session);
604
601
      return -1;
605
602
    }
606
603
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
607
604
  if(ret != GNUTLS_E_SUCCESS){
608
 
    fprintf(stderr, "Mandos plugin mandos-client: "
609
 
            "Error setting GnuTLS credentials: %s\n",
610
 
            safer_gnutls_strerror(ret));
 
605
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
606
                 safer_gnutls_strerror(ret));
611
607
    gnutls_deinit(*session);
612
608
    return -1;
613
609
  }
615
611
  /* ignore client certificate if any. */
616
612
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
617
613
  
618
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
614
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
619
615
  
620
616
  return 0;
621
617
}
625
621
                      __attribute__((unused)) const char *txt){}
626
622
 
627
623
/* Called when a Mandos server is found */
628
 
static int start_mandos_communication(const char *ip, uint16_t port,
 
624
static int start_mandos_communication(const char *ip, in_port_t port,
629
625
                                      AvahiIfIndex if_index,
630
 
                                      int af){
 
626
                                      int af, mandos_context *mc){
631
627
  int ret, tcp_sd = -1;
632
628
  ssize_t sret;
633
629
  union {
658
654
    pf = PF_INET;
659
655
    break;
660
656
  default:
661
 
    fprintf(stderr, "Mandos plugin mandos-client: "
662
 
            "Bad address family: %d\n", af);
 
657
    fprintf_plus(stderr, "Bad address family: %d\n", af);
663
658
    errno = EINVAL;
664
659
    return -1;
665
660
  }
666
661
  
667
 
  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);
668
695
  if(ret != 0){
669
696
    return -1;
670
697
  }
671
698
  
672
699
  if(debug){
673
 
    fprintf(stderr, "Mandos plugin mandos-client: "
674
 
            "Setting up a TCP connection to %s, port %" PRIu16
675
 
            "\n", ip, port);
 
700
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
701
                 PRIuMAX "\n", ip, (uintmax_t)port);
676
702
  }
677
703
  
678
704
  tcp_sd = socket(pf, SOCK_STREAM, 0);
704
730
  }
705
731
  if(ret == 0){
706
732
    int e = errno;
707
 
    fprintf(stderr, "Mandos plugin mandos-client: "
708
 
            "Bad address: %s\n", ip);
 
733
    fprintf_plus(stderr, "Bad address: %s\n", ip);
709
734
    errno = e;
710
735
    goto mandos_end;
711
736
  }
712
737
  if(af == AF_INET6){
713
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
714
 
                                       -Wconversion and
715
 
                                       -Wunreachable-code */
716
 
    
 
738
    to.in6.sin6_port = htons(port);    
 
739
#ifdef __GNUC__
 
740
#pragma GCC diagnostic push
 
741
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
 
742
#endif
717
743
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
718
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
719
 
                              -Wunreachable-code*/
 
744
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower */
 
745
#ifdef __GNUC__
 
746
#pragma GCC diagnostic pop
 
747
#endif
720
748
      if(if_index == AVAHI_IF_UNSPEC){
721
 
        fprintf(stderr, "Mandos plugin mandos-client: "
722
 
                "An IPv6 link-local address is incomplete"
723
 
                " without a network interface\n");
 
749
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
750
                     " incomplete without a network interface\n");
724
751
        errno = EINVAL;
725
752
        goto mandos_end;
726
753
      }
728
755
      to.in6.sin6_scope_id = (uint32_t)if_index;
729
756
    }
730
757
  } else {
731
 
    to.in.sin_port = htons(port); /* Spurious warnings from
732
 
                                     -Wconversion and
733
 
                                     -Wunreachable-code */
 
758
    to.in.sin_port = htons(port);
734
759
  }
735
760
  
736
761
  if(quit_now){
744
769
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
745
770
        perror_plus("if_indextoname");
746
771
      } else {
747
 
        fprintf(stderr, "Mandos plugin mandos-client: "
748
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
749
 
                ip, interface, port);
 
772
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
773
                     "\n", ip, interface, (uintmax_t)port);
750
774
      }
751
775
    } else {
752
 
      fprintf(stderr, "Mandos plugin mandos-client: "
753
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
776
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
777
                   ip, (uintmax_t)port);
754
778
    }
755
779
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
756
780
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
766
790
      perror_plus("inet_ntop");
767
791
    } else {
768
792
      if(strcmp(addrstr, ip) != 0){
769
 
        fprintf(stderr, "Mandos plugin mandos-client: "
770
 
                "Canonical address form: %s\n", addrstr);
 
793
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
771
794
      }
772
795
    }
773
796
  }
801
824
  while(true){
802
825
    size_t out_size = strlen(out);
803
826
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
804
 
                                   out_size - written));
 
827
                                        out_size - written));
805
828
    if(ret == -1){
806
829
      int e = errno;
807
830
      perror_plus("write");
827
850
  }
828
851
  
829
852
  if(debug){
830
 
    fprintf(stderr, "Mandos plugin mandos-client: "
831
 
            "Establishing TLS session with %s\n", ip);
 
853
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
832
854
  }
833
855
  
834
856
  if(quit_now){
836
858
    goto mandos_end;
837
859
  }
838
860
  
839
 
  /* Spurious warning from -Wint-to-pointer-cast */
840
 
  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);
841
866
  
842
867
  if(quit_now){
843
868
    errno = EINTR;
854
879
  
855
880
  if(ret != GNUTLS_E_SUCCESS){
856
881
    if(debug){
857
 
      fprintf(stderr, "Mandos plugin mandos-client: "
858
 
              "*** GnuTLS Handshake failed ***\n");
 
882
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
859
883
      gnutls_perror(ret);
860
884
    }
861
885
    errno = EPROTO;
865
889
  /* Read OpenPGP packet that contains the wanted password */
866
890
  
867
891
  if(debug){
868
 
    fprintf(stderr, "Mandos plugin mandos-client: "
869
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
892
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
893
                 " %s\n", ip);
870
894
  }
871
895
  
872
896
  while(true){
877
901
    }
878
902
    
879
903
    buffer_capacity = incbuffer(&buffer, buffer_length,
880
 
                                   buffer_capacity);
 
904
                                buffer_capacity);
881
905
    if(buffer_capacity == 0){
882
906
      int e = errno;
883
907
      perror_plus("incbuffer");
910
934
          }
911
935
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
912
936
        if(ret < 0){
913
 
          fprintf(stderr, "Mandos plugin mandos-client: "
914
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
937
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
938
                       "***\n");
915
939
          gnutls_perror(ret);
916
940
          errno = EPROTO;
917
941
          goto mandos_end;
918
942
        }
919
943
        break;
920
944
      default:
921
 
        fprintf(stderr, "Mandos plugin mandos-client: "
922
 
                "Unknown error while reading data from"
923
 
                " encrypted session with Mandos server\n");
 
945
        fprintf_plus(stderr, "Unknown error while reading data from"
 
946
                     " encrypted session with Mandos server\n");
924
947
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
925
948
        errno = EIO;
926
949
        goto mandos_end;
931
954
  }
932
955
  
933
956
  if(debug){
934
 
    fprintf(stderr, "Mandos plugin mandos-client: "
935
 
            "Closing TLS session\n");
 
957
    fprintf_plus(stderr, "Closing TLS session\n");
936
958
  }
937
959
  
938
960
  if(quit_now){
950
972
  
951
973
  if(buffer_length > 0){
952
974
    ssize_t decrypted_buffer_size;
953
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
954
 
                                               buffer_length,
955
 
                                               &decrypted_buffer);
 
975
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
976
                                               &decrypted_buffer, mc);
956
977
    if(decrypted_buffer_size >= 0){
957
978
      
958
979
      written = 0;
968
989
        if(ret == 0 and ferror(stdout)){
969
990
          int e = errno;
970
991
          if(debug){
971
 
            fprintf(stderr, "Mandos plugin mandos-client: "
972
 
                    "Error writing encrypted data: %s\n",
973
 
                    strerror(errno));
 
992
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
993
                         strerror(errno));
974
994
          }
975
995
          errno = e;
976
996
          goto mandos_end;
1020
1040
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1021
1041
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1022
1042
                             flags,
1023
 
                             AVAHI_GCC_UNUSED void* userdata){
1024
 
  assert(r);
 
1043
                             void* mc){
 
1044
  if(r == NULL){
 
1045
    return;
 
1046
  }
1025
1047
  
1026
1048
  /* Called whenever a service has been resolved successfully or
1027
1049
     timed out */
1033
1055
  switch(event){
1034
1056
  default:
1035
1057
  case AVAHI_RESOLVER_FAILURE:
1036
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1037
 
            "(Avahi Resolver) Failed to resolve service '%s'"
1038
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1039
 
            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)));
1040
1063
    break;
1041
1064
    
1042
1065
  case AVAHI_RESOLVER_FOUND:
1044
1067
      char ip[AVAHI_ADDRESS_STR_MAX];
1045
1068
      avahi_address_snprint(ip, sizeof(ip), address);
1046
1069
      if(debug){
1047
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1048
 
                "Mandos server \"%s\" found on %s (%s, %"
1049
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1050
 
                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);
1051
1073
      }
1052
 
      int ret = start_mandos_communication(ip, port, interface,
1053
 
                                           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);
1054
1078
      if(ret == 0){
1055
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1079
        avahi_simple_poll_quit(simple_poll);
1056
1080
      } else {
1057
 
        ret = add_server(ip, port, interface,
1058
 
                         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
        }
1059
1087
      }
1060
1088
    }
1061
1089
  }
1071
1099
                            const char *domain,
1072
1100
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1073
1101
                            flags,
1074
 
                            AVAHI_GCC_UNUSED void* userdata){
1075
 
  assert(b);
 
1102
                            void* mc){
 
1103
  if(b == NULL){
 
1104
    return;
 
1105
  }
1076
1106
  
1077
1107
  /* Called whenever a new services becomes available on the LAN or
1078
1108
     is removed from the LAN */
1085
1115
  default:
1086
1116
  case AVAHI_BROWSER_FAILURE:
1087
1117
    
1088
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1089
 
            "(Avahi browser) %s\n",
1090
 
            avahi_strerror(avahi_server_errno(mc.server)));
1091
 
    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);
1092
1122
    return;
1093
1123
    
1094
1124
  case AVAHI_BROWSER_NEW:
1097
1127
       the callback function is called the Avahi server will free the
1098
1128
       resolver for us. */
1099
1129
    
1100
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1101
 
                                    name, type, domain, protocol, 0,
1102
 
                                    resolve_callback, NULL) == NULL)
1103
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1104
 
              "Avahi: Failed to resolve service '%s': %s\n",
1105
 
              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)));
1106
1138
    break;
1107
1139
    
1108
1140
  case AVAHI_BROWSER_REMOVE:
1111
1143
  case AVAHI_BROWSER_ALL_FOR_NOW:
1112
1144
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1113
1145
    if(debug){
1114
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1115
 
              "No Mandos server found, still searching...\n");
 
1146
      fprintf_plus(stderr, "No Mandos server found, still"
 
1147
                   " searching...\n");
1116
1148
    }
1117
1149
    break;
1118
1150
  }
1127
1159
  signal_received = sig;
1128
1160
  int old_errno = errno;
1129
1161
  /* set main loop to exit */
1130
 
  if(mc.simple_poll != NULL){
1131
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1162
  if(simple_poll != NULL){
 
1163
    avahi_simple_poll_quit(simple_poll);
1132
1164
  }
1133
1165
  errno = old_errno;
1134
1166
}
1135
1167
 
1136
1168
bool get_flags(const char *ifname, struct ifreq *ifr){
1137
1169
  int ret;
 
1170
  error_t ret_errno;
1138
1171
  
1139
1172
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1140
1173
  if(s < 0){
 
1174
    ret_errno = errno;
1141
1175
    perror_plus("socket");
 
1176
    errno = ret_errno;
1142
1177
    return false;
1143
1178
  }
1144
1179
  strcpy(ifr->ifr_name, ifname);
1145
1180
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1146
1181
  if(ret == -1){
1147
1182
    if(debug){
 
1183
      ret_errno = errno;
1148
1184
      perror_plus("ioctl SIOCGIFFLAGS");
 
1185
      errno = ret_errno;
1149
1186
    }
1150
1187
    return false;
1151
1188
  }
1157
1194
  /* Reject the loopback device */
1158
1195
  if(ifr->ifr_flags & IFF_LOOPBACK){
1159
1196
    if(debug){
1160
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1161
 
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1197
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1198
                   ifname);
1162
1199
    }
1163
1200
    return false;
1164
1201
  }
1165
1202
  /* Accept point-to-point devices only if connect_to is specified */
1166
1203
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1167
1204
    if(debug){
1168
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1169
 
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1205
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1206
                   " \"%s\"\n", ifname);
1170
1207
    }
1171
1208
    return true;
1172
1209
  }
1173
1210
  /* Otherwise, reject non-broadcast-capable devices */
1174
1211
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1175
1212
    if(debug){
1176
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1177
 
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1213
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1214
                   " \"%s\"\n", ifname);
1178
1215
    }
1179
1216
    return false;
1180
1217
  }
1181
1218
  /* Reject non-ARP interfaces (including dummy interfaces) */
1182
1219
  if(ifr->ifr_flags & IFF_NOARP){
1183
1220
    if(debug){
1184
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1185
 
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1221
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1222
                   ifname);
1186
1223
    }
1187
1224
    return false;
1188
1225
  }
1189
1226
  
1190
1227
  /* Accept this device */
1191
1228
  if(debug){
1192
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1193
 
            "Interface \"%s\" is good\n", ifname);
 
1229
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1194
1230
  }
1195
1231
  return true;
1196
1232
}
1208
1244
  struct ifreq ifr;
1209
1245
  if(not get_flags(if_entry->d_name, &ifr)){
1210
1246
    if(debug){
1211
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1212
 
              "Failed to get flags for interface \"%s\"\n",
1213
 
              if_entry->d_name);
1214
 
    }
1215
 
    return 0;
1216
 
  }
1217
 
  
1218
 
  if(not good_flags(if_entry->d_name, &ifr)){
1219
 
    return 0;
1220
 
  }
1221
 
  return 1;
1222
 
}
1223
 
 
1224
 
/* 
1225
 
 * This function determines if a directory entry in /sys/class/net
1226
 
 * corresponds to an acceptable network device which is up.
1227
 
 * (This function is passed to scandir(3) as a filter function.)
1228
 
 */
1229
 
int up_interface(const struct dirent *if_entry){
1230
 
  if(if_entry->d_name[0] == '.'){
1231
 
    return 0;
1232
 
  }
1233
 
  
1234
 
  struct ifreq ifr;
1235
 
  if(not get_flags(if_entry->d_name, &ifr)){
1236
 
    if(debug){
1237
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1238
 
              "Failed to get flags for interface \"%s\"\n",
1239
 
              if_entry->d_name);
1240
 
    }
1241
 
    return 0;
1242
 
  }
1243
 
  
1244
 
  /* Reject down interfaces */
1245
 
  if(not (ifr.ifr_flags & IFF_UP)){
1246
 
    if(debug){
1247
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1248
 
              "Rejecting down interface \"%s\"\n",
1249
 
              if_entry->d_name);
1250
 
    }
1251
 
    return 0;
1252
 
  }
1253
 
  
1254
 
  /* Reject non-running interfaces */
1255
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1256
 
    if(debug){
1257
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1258
 
              "Rejecting non-running interface \"%s\"\n",
1259
 
              if_entry->d_name);
1260
 
    }
1261
 
    return 0;
1262
 
  }
1263
 
  
1264
 
  if(not good_flags(if_entry->d_name, &ifr)){
1265
 
    return 0;
1266
 
  }
1267
 
  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);
1268
1289
}
1269
1290
 
1270
1291
int notdotentries(const struct dirent *direntry){
1281
1302
/* Is this directory entry a runnable program? */
1282
1303
int runnable_hook(const struct dirent *direntry){
1283
1304
  int ret;
 
1305
  size_t sret;
1284
1306
  struct stat st;
1285
1307
  
1286
1308
  if((direntry->d_name)[0] == '\0'){
1288
1310
    return 0;
1289
1311
  }
1290
1312
  
1291
 
  /* Save pointer to last character */
1292
 
  char *end = strchr(direntry->d_name, '\0')-1;
1293
 
  
1294
 
  if(*end == '~'){
1295
 
    /* Backup name~ */
1296
 
    return 0;
1297
 
  }
1298
 
  
1299
 
  if(((direntry->d_name)[0] == '#')
1300
 
     and (*end == '#')){
1301
 
    /* Temporary #name# */
1302
 
    return 0;
1303
 
  }
1304
 
  
1305
 
  /* XXX more rules here */
1306
 
  
1307
 
  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);
1308
1334
  if(ret == -1){
1309
1335
    if(debug){
1310
 
      perror_plus("Could not stat plugin");
 
1336
      perror_plus("Could not stat hook");
1311
1337
    }
1312
1338
    return 0;
1313
1339
  }
1314
1340
  if(not (S_ISREG(st.st_mode))){
1315
1341
    /* Not a regular file */
 
1342
    if(debug){
 
1343
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1344
                   direntry->d_name);
 
1345
    }
1316
1346
    return 0;
1317
1347
  }
1318
1348
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1319
1349
    /* Not executable */
 
1350
    if(debug){
 
1351
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1352
                   direntry->d_name);
 
1353
    }
1320
1354
    return 0;
1321
1355
  }
 
1356
  if(debug){
 
1357
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1358
                 direntry->d_name);
 
1359
  }
1322
1360
  return 1;
1323
1361
}
1324
1362
 
1325
 
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){
1326
1365
  int ret;
1327
1366
  struct timespec now;
1328
1367
  struct timespec waited_time;
1329
1368
  intmax_t block_time;
1330
1369
  
1331
1370
  while(true){
1332
 
    if(mc.current_server == NULL){
 
1371
    if(mc->current_server == NULL){
1333
1372
      if (debug){
1334
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1335
 
                "Wait until first server is found. No timeout!\n");
 
1373
        fprintf_plus(stderr, "Wait until first server is found."
 
1374
                     " No timeout!\n");
1336
1375
      }
1337
1376
      ret = avahi_simple_poll_iterate(s, -1);
1338
1377
    } else {
1339
1378
      if (debug){
1340
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1341
 
                "Check current_server if we should run it,"
1342
 
                " or wait\n");
 
1379
        fprintf_plus(stderr, "Check current_server if we should run"
 
1380
                     " it, or wait\n");
1343
1381
      }
1344
1382
      /* the current time */
1345
1383
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1350
1388
      /* Calculating in ms how long time between now and server
1351
1389
         who we visted longest time ago. Now - last seen.  */
1352
1390
      waited_time.tv_sec = (now.tv_sec
1353
 
                            - mc.current_server->last_seen.tv_sec);
 
1391
                            - mc->current_server->last_seen.tv_sec);
1354
1392
      waited_time.tv_nsec = (now.tv_nsec
1355
 
                             - mc.current_server->last_seen.tv_nsec);
 
1393
                             - mc->current_server->last_seen.tv_nsec);
1356
1394
      /* total time is 10s/10,000ms.
1357
1395
         Converting to s from ms by dividing by 1,000,
1358
1396
         and ns to ms by dividing by 1,000,000. */
1361
1399
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1362
1400
      
1363
1401
      if (debug){
1364
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1365
 
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1402
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1403
                     block_time);
1366
1404
      }
1367
1405
      
1368
1406
      if(block_time <= 0){
1369
 
        ret = start_mandos_communication(mc.current_server->ip,
1370
 
                                         mc.current_server->port,
1371
 
                                         mc.current_server->if_index,
1372
 
                                         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);
1373
1411
        if(ret == 0){
1374
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1412
          avahi_simple_poll_quit(s);
1375
1413
          return 0;
1376
1414
        }
1377
1415
        ret = clock_gettime(CLOCK_MONOTONIC,
1378
 
                            &mc.current_server->last_seen);
 
1416
                            &mc->current_server->last_seen);
1379
1417
        if(ret == -1){
1380
1418
          perror_plus("clock_gettime");
1381
1419
          return -1;
1382
1420
        }
1383
 
        mc.current_server = mc.current_server->next;
 
1421
        mc->current_server = mc->current_server->next;
1384
1422
        block_time = 0;         /* Call avahi to find new Mandos
1385
1423
                                   servers, but don't block */
1386
1424
      }
1395
1433
  }
1396
1434
}
1397
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
 
1398
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 };
1399
1798
  AvahiSServiceBrowser *sb = NULL;
1400
 
  int error;
 
1799
  error_t ret_errno;
1401
1800
  int ret;
1402
1801
  intmax_t tmpmax;
1403
1802
  char *tmp;
1404
1803
  int exitcode = EXIT_SUCCESS;
1405
 
  const char *interface = "";
1406
 
  struct ifreq network;
1407
 
  int sd = -1;
1408
 
  bool take_down_interface = false;
1409
 
  uid_t uid;
1410
 
  gid_t gid;
 
1804
  char *interfaces_to_take_down = NULL;
 
1805
  size_t interfaces_to_take_down_size = 0;
1411
1806
  char tempdir[] = "/tmp/mandosXXXXXX";
1412
1807
  bool tempdir_created = false;
1413
1808
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1414
1809
  const char *seckey = PATHDIR "/" SECKEY;
1415
1810
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1811
  char *interfaces_hooks = NULL;
 
1812
  size_t interfaces_hooks_size = 0;
1416
1813
  
1417
1814
  bool gnutls_initialized = false;
1418
1815
  bool gpgme_initialized = false;
1480
1877
        .group = 2 },
1481
1878
      { .name = "retry", .key = 132,
1482
1879
        .arg = "SECONDS",
1483
 
        .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",
1484
1885
        .group = 2 },
1485
1886
      /*
1486
1887
       * These reproduce what we would get without ARGP_NO_HELP
1505
1906
        connect_to = arg;
1506
1907
        break;
1507
1908
      case 'i':                 /* --interface */
1508
 
        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
        }
1509
1914
        break;
1510
1915
      case 's':                 /* --seckey */
1511
1916
        seckey = arg;
1540
1945
          argp_error(state, "Bad retry interval");
1541
1946
        }
1542
1947
        break;
 
1948
      case 133:                 /* --network-hook-dir */
 
1949
        hookdir = arg;
 
1950
        break;
1543
1951
        /*
1544
1952
         * These reproduce what we would get without ARGP_NO_HELP
1545
1953
         */
1551
1959
        argp_state_help(state, state->out_stream,
1552
1960
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1553
1961
      case 'V':                 /* --version */
1554
 
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1555
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1962
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1556
1963
        exit(argp_err_exit_status);
1557
1964
        break;
1558
1965
      default:
1585
1992
  {
1586
1993
    /* Work around Debian bug #633582:
1587
1994
       <http://bugs.debian.org/633582> */
1588
 
    struct stat st;
1589
1995
    
1590
1996
    /* Re-raise priviliges */
1591
 
    errno = 0;
1592
 
    ret = seteuid(0);
1593
 
    if(ret == -1){
1594
 
      perror_plus("seteuid");
1595
 
    }
1596
 
    
1597
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1598
 
      int seckey_fd = open(seckey, O_RDONLY);
1599
 
      if(seckey_fd == -1){
1600
 
        perror_plus("open");
1601
 
      } else {
1602
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1603
 
        if(ret == -1){
1604
 
          perror_plus("fstat");
1605
 
        } else {
1606
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1607
 
            ret = fchown(seckey_fd, uid, gid);
1608
 
            if(ret == -1){
1609
 
              perror_plus("fchown");
1610
 
            }
1611
 
          }
1612
 
        }
1613
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1614
 
      }
1615
 
    }
1616
 
    
1617
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1618
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1619
 
      if(pubkey_fd == -1){
1620
 
        perror_plus("open");
1621
 
      } else {
1622
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1623
 
        if(ret == -1){
1624
 
          perror_plus("fstat");
1625
 
        } else {
1626
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1627
 
            ret = fchown(pubkey_fd, uid, gid);
1628
 
            if(ret == -1){
1629
 
              perror_plus("fchown");
1630
 
            }
1631
 
          }
1632
 
        }
1633
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1634
 
      }
1635
 
    }
1636
 
    
1637
 
    /* Lower privileges */
1638
 
    errno = 0;
1639
 
    ret = seteuid(uid);
1640
 
    if(ret == -1){
1641
 
      perror_plus("seteuid");
1642
 
    }
1643
 
  }
1644
 
  
1645
 
  /* Find network hooks and run them */
1646
 
  {
1647
 
    struct dirent **direntries;
1648
 
    struct dirent *direntry;
1649
 
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
1650
 
                           alphasort);
1651
 
    if(numhooks == -1){
1652
 
      perror_plus("scandir");
1653
 
    } else {
1654
 
      int devnull = open("/dev/null", O_RDONLY);
1655
 
      for(int i = 0; i < numhooks; i++){
1656
 
        direntry = direntries[0];
1657
 
        char *fullname = NULL;
1658
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
1659
 
                       direntry->d_name);
1660
 
        if(ret < 0){
1661
 
          perror_plus("asprintf");
1662
 
          continue;
1663
 
        }
1664
 
        pid_t hook_pid = fork();
1665
 
        if(hook_pid == 0){
1666
 
          /* Child */
1667
 
          dup2(devnull, STDIN_FILENO);
1668
 
          close(devnull);
1669
 
          dup2(STDERR_FILENO, STDOUT_FILENO);
1670
 
          ret = setenv("DEVICE", interface, 1);
1671
 
          if(ret == -1){
1672
 
            perror_plus("setenv");
1673
 
            exit(1);
1674
 
          }
1675
 
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1676
 
          if(ret == -1){
1677
 
            perror_plus("setenv");
1678
 
            exit(1);
1679
 
          }
1680
 
          ret = setenv("MODE", "start", 1);
1681
 
          if(ret == -1){
1682
 
            perror_plus("setenv");
1683
 
            exit(1);
1684
 
          }
1685
 
          char *delaystring;
1686
 
          ret = asprintf(&delaystring, "%f", delay);
1687
 
          if(ret == -1){
1688
 
            perror_plus("asprintf");
1689
 
            exit(1);
1690
 
          }
1691
 
          ret = setenv("DELAY", delaystring, 1);
1692
 
          if(ret == -1){
1693
 
            free(delaystring);
1694
 
            perror_plus("setenv");
1695
 
            exit(1);
1696
 
          }
1697
 
          free(delaystring);
1698
 
          ret = execl(fullname, direntry->d_name, "start", NULL);
1699
 
          perror_plus("execl");
1700
 
        } else {
1701
 
          int status;
1702
 
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1703
 
            perror_plus("waitpid");
1704
 
            free(fullname);
1705
 
            continue;
1706
 
          }
1707
 
          if(WIFEXITED(status)){
1708
 
            if(WEXITSTATUS(status) != 0){
1709
 
              fprintf(stderr, "Mandos plugin mandos-client: "
1710
 
                      "Warning: network hook \"%s\" exited"
1711
 
                      " with status %d\n", direntry->d_name,
1712
 
                      WEXITSTATUS(status));
1713
 
              free(fullname);
1714
 
              continue;
1715
 
            }
1716
 
          } else if(WIFSIGNALED(status)){
1717
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1718
 
                    "Warning: network hook \"%s\" died by"
1719
 
                    " signal %d\n", direntry->d_name,
1720
 
                    WTERMSIG(status));
1721
 
            free(fullname);
1722
 
            continue;
1723
 
          } else {
1724
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1725
 
                    "Warning: network hook \"%s\" crashed\n",
1726
 
                    direntry->d_name);
1727
 
            free(fullname);
1728
 
            continue;
1729
 
          }
1730
 
        }
1731
 
        free(fullname);
1732
 
        if(quit_now){
1733
 
          goto end;
1734
 
        }
1735
 
      }
1736
 
      close(devnull);
 
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");
 
2070
        goto end;
 
2071
      }
 
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;
1737
2080
    }
1738
2081
  }
1739
2082
  
1741
2084
    avahi_set_log_function(empty_log);
1742
2085
  }
1743
2086
  
1744
 
  if(interface[0] == '\0'){
1745
 
    struct dirent **direntries;
1746
 
    /* First look for interfaces that are up */
1747
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1748
 
                  alphasort);
1749
 
    if(ret == 0){
1750
 
      /* No up interfaces, look for any good interfaces */
1751
 
      free(direntries);
1752
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1753
 
                    alphasort);
1754
 
    }
1755
 
    if(ret >= 1){
1756
 
      /* Pick the first interface returned */
1757
 
      interface = strdup(direntries[0]->d_name);
1758
 
      if(debug){
1759
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1760
 
                "Using interface \"%s\"\n", interface);
1761
 
      }
1762
 
      if(interface == NULL){
1763
 
        perror_plus("malloc");
1764
 
        free(direntries);
1765
 
        exitcode = EXIT_FAILURE;
1766
 
        goto end;
1767
 
      }
1768
 
      free(direntries);
1769
 
    } else {
1770
 
      free(direntries);
1771
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1772
 
              "Could not find a network interface\n");
1773
 
      exitcode = EXIT_FAILURE;
1774
 
      goto end;
1775
 
    }
1776
 
  }
1777
 
  
1778
2087
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1779
2088
     from the signal handler */
1780
2089
  /* Initialize the pseudo-RNG for Avahi */
1781
2090
  srand((unsigned int) time(NULL));
1782
 
  mc.simple_poll = avahi_simple_poll_new();
1783
 
  if(mc.simple_poll == NULL){
1784
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1785
 
            "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");
1786
2095
    exitcode = EX_UNAVAILABLE;
1787
2096
    goto end;
1788
2097
  }
1850
2159
    }
1851
2160
  }
1852
2161
  
1853
 
  /* If the interface is down, bring it up */
1854
 
  if(strcmp(interface, "none") != 0){
1855
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1856
 
    if(if_index == 0){
1857
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1858
 
              "No such interface: \"%s\"\n", interface);
1859
 
      exitcode = EX_UNAVAILABLE;
1860
 
      goto end;
1861
 
    }
1862
 
    
1863
 
    if(quit_now){
1864
 
      goto end;
1865
 
    }
1866
 
    
1867
 
    /* Re-raise priviliges */
1868
 
    errno = 0;
1869
 
    ret = seteuid(0);
1870
 
    if(ret == -1){
1871
 
      perror_plus("seteuid");
1872
 
    }
1873
 
    
1874
 
#ifdef __linux__
1875
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1876
 
       messages about the network interface to mess up the prompt */
1877
 
    ret = klogctl(8, NULL, 5);
1878
 
    bool restore_loglevel = true;
1879
 
    if(ret == -1){
1880
 
      restore_loglevel = false;
1881
 
      perror_plus("klogctl");
1882
 
    }
1883
 
#endif  /* __linux__ */
1884
 
    
1885
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1886
 
    if(sd < 0){
1887
 
      perror_plus("socket");
1888
 
      exitcode = EX_OSERR;
1889
 
#ifdef __linux__
1890
 
      if(restore_loglevel){
1891
 
        ret = klogctl(7, NULL, 0);
1892
 
        if(ret == -1){
1893
 
          perror_plus("klogctl");
1894
 
        }
1895
 
      }
1896
 
#endif  /* __linux__ */
1897
 
      /* Lower privileges */
1898
 
      errno = 0;
1899
 
      ret = seteuid(uid);
1900
 
      if(ret == -1){
1901
 
        perror_plus("seteuid");
1902
 
      }
1903
 
      goto end;
1904
 
    }
1905
 
    strcpy(network.ifr_name, interface);
1906
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1907
 
    if(ret == -1){
1908
 
      perror_plus("ioctl SIOCGIFFLAGS");
1909
 
#ifdef __linux__
1910
 
      if(restore_loglevel){
1911
 
        ret = klogctl(7, NULL, 0);
1912
 
        if(ret == -1){
1913
 
          perror_plus("klogctl");
1914
 
        }
1915
 
      }
1916
 
#endif  /* __linux__ */
1917
 
      exitcode = EX_OSERR;
1918
 
      /* Lower privileges */
1919
 
      errno = 0;
1920
 
      ret = seteuid(uid);
1921
 
      if(ret == -1){
1922
 
        perror_plus("seteuid");
1923
 
      }
1924
 
      goto end;
1925
 
    }
1926
 
    if((network.ifr_flags & IFF_UP) == 0){
1927
 
      network.ifr_flags |= IFF_UP;
1928
 
      take_down_interface = true;
1929
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1930
 
      if(ret == -1){
1931
 
        take_down_interface = false;
1932
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1933
 
        exitcode = EX_OSERR;
1934
 
#ifdef __linux__
1935
 
        if(restore_loglevel){
1936
 
          ret = klogctl(7, NULL, 0);
1937
 
          if(ret == -1){
1938
 
            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;
1939
2208
          }
1940
2209
        }
1941
 
#endif  /* __linux__ */
1942
 
        /* Lower privileges */
1943
 
        errno = 0;
1944
 
        ret = seteuid(uid);
1945
 
        if(ret == -1){
1946
 
          perror_plus("seteuid");
1947
 
        }
1948
 
        goto end;
1949
 
      }
1950
 
    }
1951
 
    /* Sleep checking until interface is running.
1952
 
       Check every 0.25s, up to total time of delay */
1953
 
    for(int i=0; i < delay * 4; i++){
1954
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1955
 
      if(ret == -1){
1956
 
        perror_plus("ioctl SIOCGIFFLAGS");
1957
 
      } else if(network.ifr_flags & IFF_RUNNING){
1958
2210
        break;
1959
2211
      }
1960
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1961
 
      ret = nanosleep(&sleeptime, NULL);
1962
 
      if(ret == -1 and errno != EINTR){
1963
 
        perror_plus("nanosleep");
1964
 
      }
1965
 
    }
1966
 
    if(not take_down_interface){
1967
 
      /* We won't need the socket anymore */
1968
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1969
 
      if(ret == -1){
1970
 
        perror_plus("close");
1971
 
      }
1972
 
    }
1973
 
#ifdef __linux__
1974
 
    if(restore_loglevel){
1975
 
      /* Restores kernel loglevel to default */
1976
 
      ret = klogctl(7, NULL, 0);
1977
 
      if(ret == -1){
1978
 
        perror_plus("klogctl");
1979
 
      }
1980
 
    }
1981
 
#endif  /* __linux__ */
1982
 
    /* Lower privileges */
1983
 
    errno = 0;
1984
 
    if(take_down_interface){
1985
 
      /* Lower privileges */
1986
 
      ret = seteuid(uid);
1987
 
      if(ret == -1){
1988
 
        perror_plus("seteuid");
1989
 
      }
1990
 
    } else {
1991
 
      /* Lower privileges permanently */
1992
 
      ret = setuid(uid);
1993
 
      if(ret == -1){
1994
 
        perror_plus("setuid");
1995
 
      }
1996
 
    }
 
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);
1997
2237
  }
1998
2238
  
1999
2239
  if(quit_now){
2000
2240
    goto end;
2001
2241
  }
2002
2242
  
2003
 
  ret = init_gnutls_global(pubkey, seckey);
 
2243
  ret = init_gnutls_global(pubkey, seckey, &mc);
2004
2244
  if(ret == -1){
2005
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2006
 
            "init_gnutls_global failed\n");
 
2245
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2007
2246
    exitcode = EX_UNAVAILABLE;
2008
2247
    goto end;
2009
2248
  } else {
2024
2263
    goto end;
2025
2264
  }
2026
2265
  
2027
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
2028
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2029
 
            "init_gpgme failed\n");
 
2266
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2267
    fprintf_plus(stderr, "init_gpgme failed\n");
2030
2268
    exitcode = EX_UNAVAILABLE;
2031
2269
    goto end;
2032
2270
  } else {
2041
2279
    /* Connect directly, do not use Zeroconf */
2042
2280
    /* (Mainly meant for debugging) */
2043
2281
    char *address = strrchr(connect_to, ':');
 
2282
    
2044
2283
    if(address == NULL){
2045
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2046
 
              "No colon in address\n");
 
2284
      fprintf_plus(stderr, "No colon in address\n");
2047
2285
      exitcode = EX_USAGE;
2048
2286
      goto end;
2049
2287
    }
2052
2290
      goto end;
2053
2291
    }
2054
2292
    
2055
 
    uint16_t port;
 
2293
    in_port_t port;
2056
2294
    errno = 0;
2057
2295
    tmpmax = strtoimax(address+1, &tmp, 10);
2058
2296
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2059
 
       or tmpmax != (uint16_t)tmpmax){
2060
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2061
 
              "Bad port number\n");
 
2297
       or tmpmax != (in_port_t)tmpmax){
 
2298
      fprintf_plus(stderr, "Bad port number\n");
2062
2299
      exitcode = EX_USAGE;
2063
2300
      goto end;
2064
2301
    }
2065
 
  
 
2302
    
2066
2303
    if(quit_now){
2067
2304
      goto end;
2068
2305
    }
2069
2306
    
2070
 
    port = (uint16_t)tmpmax;
 
2307
    port = (in_port_t)tmpmax;
2071
2308
    *address = '\0';
2072
2309
    /* Colon in address indicates IPv6 */
2073
2310
    int af;
2089
2326
    }
2090
2327
    
2091
2328
    while(not quit_now){
2092
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2329
      ret = start_mandos_communication(address, port, if_index, af,
 
2330
                                       &mc);
2093
2331
      if(quit_now or ret == 0){
2094
2332
        break;
2095
2333
      }
2096
2334
      if(debug){
2097
 
        fprintf(stderr, "Mandos plugin mandos-client: "
2098
 
                "Retrying in %d seconds\n", (int)retry_interval);
 
2335
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2336
                     (int)retry_interval);
2099
2337
      }
2100
 
      sleep((int)retry_interval);
 
2338
      sleep((unsigned int)retry_interval);
2101
2339
    }
2102
2340
    
2103
2341
    if (not quit_now){
2121
2359
    config.publish_domain = 0;
2122
2360
    
2123
2361
    /* Allocate a new server */
2124
 
    mc.server = avahi_server_new(avahi_simple_poll_get
2125
 
                                 (mc.simple_poll), &config, NULL,
2126
 
                                 NULL, &error);
 
2362
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2363
                                 &config, NULL, NULL, &ret_errno);
2127
2364
    
2128
2365
    /* Free the Avahi configuration data */
2129
2366
    avahi_server_config_free(&config);
2131
2368
  
2132
2369
  /* Check if creating the Avahi server object succeeded */
2133
2370
  if(mc.server == NULL){
2134
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2135
 
            "Failed to create Avahi server: %s\n",
2136
 
            avahi_strerror(error));
 
2371
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2372
                 avahi_strerror(ret_errno));
2137
2373
    exitcode = EX_UNAVAILABLE;
2138
2374
    goto end;
2139
2375
  }
2145
2381
  /* Create the Avahi service browser */
2146
2382
  sb = avahi_s_service_browser_new(mc.server, if_index,
2147
2383
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2148
 
                                   NULL, 0, browse_callback, NULL);
 
2384
                                   NULL, 0, browse_callback,
 
2385
                                   (void *)&mc);
2149
2386
  if(sb == NULL){
2150
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2151
 
            "Failed to create service browser: %s\n",
2152
 
            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)));
2153
2389
    exitcode = EX_UNAVAILABLE;
2154
2390
    goto end;
2155
2391
  }
2161
2397
  /* Run the main loop */
2162
2398
  
2163
2399
  if(debug){
2164
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2165
 
            "Starting Avahi loop search\n");
 
2400
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2166
2401
  }
2167
2402
 
2168
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2169
 
                                (int)(retry_interval * 1000));
 
2403
  ret = avahi_loop_with_timeout(simple_poll,
 
2404
                                (int)(retry_interval * 1000), &mc);
2170
2405
  if(debug){
2171
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2172
 
            "avahi_loop_with_timeout exited %s\n",
2173
 
            (ret == 0) ? "successfully" : "with error");
 
2406
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2407
                 (ret == 0) ? "successfully" : "with error");
2174
2408
  }
2175
2409
  
2176
2410
 end:
2177
2411
  
2178
2412
  if(debug){
2179
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2180
 
            "%s exiting\n", argv[0]);
 
2413
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2181
2414
  }
2182
2415
  
2183
2416
  /* Cleanup things */
 
2417
  free(mc.interfaces);
 
2418
  
2184
2419
  if(sb != NULL)
2185
2420
    avahi_s_service_browser_free(sb);
2186
2421
  
2187
2422
  if(mc.server != NULL)
2188
2423
    avahi_server_free(mc.server);
2189
2424
  
2190
 
  if(mc.simple_poll != NULL)
2191
 
    avahi_simple_poll_free(mc.simple_poll);
 
2425
  if(simple_poll != NULL)
 
2426
    avahi_simple_poll_free(simple_poll);
2192
2427
  
2193
2428
  if(gnutls_initialized){
2194
2429
    gnutls_certificate_free_credentials(mc.cred);
2199
2434
  if(gpgme_initialized){
2200
2435
    gpgme_release(mc.ctx);
2201
2436
  }
2202
 
 
 
2437
  
2203
2438
  /* Cleans up the circular linked list of Mandos servers the client
2204
2439
     has seen */
2205
2440
  if(mc.current_server != NULL){
2211
2446
    }
2212
2447
  }
2213
2448
  
2214
 
  /* XXX run network hooks "stop" here  */
2215
 
  
2216
 
  /* Take down the network interface */
2217
 
  if(take_down_interface){
2218
 
    /* Re-raise priviliges */
2219
 
    errno = 0;
2220
 
    ret = seteuid(0);
2221
 
    if(ret == -1){
2222
 
      perror_plus("seteuid");
2223
 
    }
2224
 
    if(geteuid() == 0){
2225
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2226
 
      if(ret == -1){
2227
 
        perror_plus("ioctl SIOCGIFFLAGS");
2228
 
      } else if(network.ifr_flags & IFF_UP){
2229
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2230
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2231
 
        if(ret == -1){
2232
 
          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");
2233
2467
        }
2234
2468
      }
2235
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2236
 
      if(ret == -1){
2237
 
        perror_plus("close");
2238
 
      }
2239
 
      /* Lower privileges permanently */
2240
 
      errno = 0;
2241
 
      ret = setuid(uid);
2242
 
      if(ret == -1){
2243
 
        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");
2244
2472
      }
2245
2473
    }
 
2474
    
 
2475
    lower_privileges_permanently();
2246
2476
  }
2247
2477
  
 
2478
  free(interfaces_to_take_down);
 
2479
  free(interfaces_hooks);
 
2480
  
2248
2481
  /* Removes the GPGME temp directory and all files inside */
2249
2482
  if(tempdir_created){
2250
2483
    struct dirent **direntries = NULL;
2263
2496
        }
2264
2497
        ret = remove(fullname);
2265
2498
        if(ret == -1){
2266
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2267
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
2499
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2500
                       strerror(errno));
2268
2501
        }
2269
2502
        free(fullname);
2270
2503
      }