/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: 2013-10-24 20:38:44 UTC
  • mto: This revision was merged to the branch mainline in revision 635.
  • Revision ID: teddy@recompile.se-20131024203844-j0y0ir6vnlj9mkix
Tags: version-1.6.2-1
* Makefile (version): Changed to "1.6.2".
* NEWS (Version 1.6.2): New entry.
* debian/changelog (1.6.2-1): - '' -

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