/mandos/trunk

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

« back to all changes in this revision

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

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

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

Show diffs side-by-side

added added

removed removed

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