/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: Björn Påhlsson
  • Date: 2011-11-27 19:51:00 UTC
  • mto: (518.2.5 persistent-state-gpgme)
  • mto: This revision was merged to the branch mainline in revision 524.
  • Revision ID: belorn@recompile.se-20111127195100-fx0mpeia9xihvpmd
renamed variables

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