/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: 2012-06-16 23:25:46 UTC
  • Revision ID: teddy@recompile.se-20120616232546-dcrkmnhd4yhq6mvd
* plugins.d/mandos-client (mandos_context): Moved to inside "main()".
                                            All users changed.
  (add_server): Take new "current_server" argument; all callers
                changed.
  (init_gpgme, pgp_packet_decrypt, init_gnutls_global,
  init_gnutls_session, start_mandos_communication,
  avahi_loop_with_timeout): Take new "mc" argument"; all callers
                            changed.
  (resolve_callback, browse_callback): Handle void pointer userdata as
                                       "mc", a pointer to
                                       mandos_context.  All callers
                                       changed.
  (main): New "mc" variable.

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-2012 Teddy Hogeborn
 
13
 * Copyright © 2008-2012 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
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
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";
129
136
const char *argp_program_version = "mandos-client " VERSION;
130
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
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;
154
163
  server *current_server;
155
164
} mandos_context;
156
165
 
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 };
 
166
/* global so signal handler can reach it*/
 
167
AvahiSimplePoll *simple_poll;
162
168
 
163
169
sig_atomic_t quit_now = 0;
164
170
int signal_received = 0;
165
171
 
166
172
/* Function to use when printing errors */
167
173
void perror_plus(const char *print_text){
 
174
  int e = errno;
168
175
  fprintf(stderr, "Mandos plugin %s: ",
169
176
          program_invocation_short_name);
 
177
  errno = e;
170
178
  perror(print_text);
171
179
}
172
180
 
 
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
 
173
191
/*
174
192
 * Make additional room in "buffer" for at least BUFFER_SIZE more
175
193
 * bytes. "buffer_capacity" is how much is currently allocated,
176
194
 * "buffer_length" is how much is already used.
177
195
 */
178
196
size_t incbuffer(char **buffer, size_t buffer_length,
179
 
                  size_t buffer_capacity){
 
197
                 size_t buffer_capacity){
180
198
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
181
199
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
182
200
    if(buffer == NULL){
187
205
  return buffer_capacity;
188
206
}
189
207
 
190
 
int add_server(const char *ip, uint16_t port,
191
 
                 AvahiIfIndex if_index,
192
 
                 int af){
 
208
/* 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){
193
211
  int ret;
194
212
  server *new_server = malloc(sizeof(server));
195
213
  if(new_server == NULL){
196
214
    perror_plus("malloc");
197
 
    return -1;
 
215
    return false;
198
216
  }
199
217
  *new_server = (server){ .ip = strdup(ip),
200
 
                         .port = port,
201
 
                         .if_index = if_index,
202
 
                         .af = af };
 
218
                          .port = port,
 
219
                          .if_index = if_index,
 
220
                          .af = af };
203
221
  if(new_server->ip == NULL){
204
222
    perror_plus("strdup");
205
 
    return -1;
 
223
    return false;
206
224
  }
207
 
  /* unique case of first server */
208
 
  if (mc.current_server == NULL){
 
225
  /* Special case of first server */
 
226
  if(*current_server == NULL){
209
227
    new_server->next = new_server;
210
228
    new_server->prev = new_server;
211
 
    mc.current_server = new_server;
212
 
  /* Placing the new server last in the list */
 
229
    *current_server = new_server;
 
230
  /* Place the new server last in the list */
213
231
  } else {
214
 
    new_server->next = mc.current_server;
215
 
    new_server->prev = mc.current_server->prev;
 
232
    new_server->next = *current_server;
 
233
    new_server->prev = (*current_server)->prev;
216
234
    new_server->prev->next = new_server;
217
 
    mc.current_server->prev = new_server;
 
235
    (*current_server)->prev = new_server;
218
236
  }
219
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
237
  ret = clock_gettime(CLOCK_MONOTONIC, &(*current_server)->last_seen);
220
238
  if(ret == -1){
221
239
    perror_plus("clock_gettime");
222
 
    return -1;
 
240
    return false;
223
241
  }
224
 
  return 0;
 
242
  return true;
225
243
}
226
244
 
227
245
/* 
228
246
 * Initialize GPGME.
229
247
 */
230
 
static bool init_gpgme(const char *seckey,
231
 
                       const char *pubkey, const char *tempdir){
 
248
static bool init_gpgme(const char *seckey, const char *pubkey,
 
249
                       const char *tempdir, mandos_context *mc){
232
250
  gpgme_error_t rc;
233
251
  gpgme_engine_info_t engine_info;
234
252
  
235
 
  
236
253
  /*
237
254
   * Helper function to insert pub and seckey to the engine keyring.
238
255
   */
249
266
    
250
267
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
251
268
    if(rc != GPG_ERR_NO_ERROR){
252
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
253
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
269
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
270
                   gpgme_strsource(rc), gpgme_strerror(rc));
254
271
      return false;
255
272
    }
256
273
    
257
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
274
    rc = gpgme_op_import(mc->ctx, pgp_data);
258
275
    if(rc != GPG_ERR_NO_ERROR){
259
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
260
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
276
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
277
                   gpgme_strsource(rc), gpgme_strerror(rc));
261
278
      return false;
262
279
    }
263
280
    
270
287
  }
271
288
  
272
289
  if(debug){
273
 
    fprintf(stderr, "Initializing GPGME\n");
 
290
    fprintf_plus(stderr, "Initializing GPGME\n");
274
291
  }
275
292
  
276
293
  /* Init GPGME */
277
294
  gpgme_check_version(NULL);
278
295
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
279
296
  if(rc != GPG_ERR_NO_ERROR){
280
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
281
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
297
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
298
                 gpgme_strsource(rc), gpgme_strerror(rc));
282
299
    return false;
283
300
  }
284
301
  
285
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
302
  /* Set GPGME home directory for the OpenPGP engine only */
286
303
  rc = gpgme_get_engine_info(&engine_info);
287
304
  if(rc != GPG_ERR_NO_ERROR){
288
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
289
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
305
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
306
                 gpgme_strsource(rc), gpgme_strerror(rc));
290
307
    return false;
291
308
  }
292
309
  while(engine_info != NULL){
298
315
    engine_info = engine_info->next;
299
316
  }
300
317
  if(engine_info == NULL){
301
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
318
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
319
                 tempdir);
302
320
    return false;
303
321
  }
304
322
  
305
323
  /* Create new GPGME "context" */
306
 
  rc = gpgme_new(&(mc.ctx));
 
324
  rc = gpgme_new(&(mc->ctx));
307
325
  if(rc != GPG_ERR_NO_ERROR){
308
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
309
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
326
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
327
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
328
                 gpgme_strerror(rc));
310
329
    return false;
311
330
  }
312
331
  
323
342
 */
324
343
static ssize_t pgp_packet_decrypt(const char *cryptotext,
325
344
                                  size_t crypto_size,
326
 
                                  char **plaintext){
 
345
                                  char **plaintext,
 
346
                                  mandos_context *mc){
327
347
  gpgme_data_t dh_crypto, dh_plain;
328
348
  gpgme_error_t rc;
329
349
  ssize_t ret;
331
351
  ssize_t plaintext_length = 0;
332
352
  
333
353
  if(debug){
334
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
354
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
335
355
  }
336
356
  
337
357
  /* Create new GPGME data buffer from memory cryptotext */
338
358
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
339
359
                               0);
340
360
  if(rc != GPG_ERR_NO_ERROR){
341
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
342
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
361
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
362
                 gpgme_strsource(rc), gpgme_strerror(rc));
343
363
    return -1;
344
364
  }
345
365
  
346
366
  /* Create new empty GPGME data buffer for the plaintext */
347
367
  rc = gpgme_data_new(&dh_plain);
348
368
  if(rc != GPG_ERR_NO_ERROR){
349
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
350
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
369
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
370
                 "bad gpgme_data_new: %s: %s\n",
 
371
                 gpgme_strsource(rc), gpgme_strerror(rc));
351
372
    gpgme_data_release(dh_crypto);
352
373
    return -1;
353
374
  }
354
375
  
355
376
  /* Decrypt data from the cryptotext data buffer to the plaintext
356
377
     data buffer */
357
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
378
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
358
379
  if(rc != GPG_ERR_NO_ERROR){
359
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
360
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
380
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
381
                 gpgme_strsource(rc), gpgme_strerror(rc));
361
382
    plaintext_length = -1;
362
383
    if(debug){
363
384
      gpgme_decrypt_result_t result;
364
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
385
      result = gpgme_op_decrypt_result(mc->ctx);
365
386
      if(result == NULL){
366
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
387
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
367
388
      } else {
368
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
369
 
                result->unsupported_algorithm);
370
 
        fprintf(stderr, "Wrong key usage: %u\n",
371
 
                result->wrong_key_usage);
 
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);
372
393
        if(result->file_name != NULL){
373
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
394
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
374
395
        }
375
396
        gpgme_recipient_t recipient;
376
397
        recipient = result->recipients;
377
398
        while(recipient != NULL){
378
 
          fprintf(stderr, "Public key algorithm: %s\n",
379
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
380
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
381
 
          fprintf(stderr, "Secret key available: %s\n",
382
 
                  recipient->status == GPG_ERR_NO_SECKEY
383
 
                  ? "No" : "Yes");
 
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");
384
406
          recipient = recipient->next;
385
407
        }
386
408
      }
389
411
  }
390
412
  
391
413
  if(debug){
392
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
414
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
393
415
  }
394
416
  
395
417
  /* Seek back to the beginning of the GPGME plaintext data buffer */
402
424
  *plaintext = NULL;
403
425
  while(true){
404
426
    plaintext_capacity = incbuffer(plaintext,
405
 
                                      (size_t)plaintext_length,
406
 
                                      plaintext_capacity);
 
427
                                   (size_t)plaintext_length,
 
428
                                   plaintext_capacity);
407
429
    if(plaintext_capacity == 0){
408
 
        perror_plus("incbuffer");
409
 
        plaintext_length = -1;
410
 
        goto decrypt_end;
 
430
      perror_plus("incbuffer");
 
431
      plaintext_length = -1;
 
432
      goto decrypt_end;
411
433
    }
412
434
    
413
435
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
426
448
  }
427
449
  
428
450
  if(debug){
429
 
    fprintf(stderr, "Decrypted password is: ");
 
451
    fprintf_plus(stderr, "Decrypted password is: ");
430
452
    for(ssize_t i = 0; i < plaintext_length; i++){
431
453
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
432
454
    }
444
466
}
445
467
 
446
468
static const char * safer_gnutls_strerror(int value){
447
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
448
 
                                               -Wunreachable-code */
 
469
  const char *ret = gnutls_strerror(value);
449
470
  if(ret == NULL)
450
471
    ret = "(unknown)";
451
472
  return ret;
454
475
/* GnuTLS log function callback */
455
476
static void debuggnutls(__attribute__((unused)) int level,
456
477
                        const char* string){
457
 
  fprintf(stderr, "GnuTLS: %s", string);
 
478
  fprintf_plus(stderr, "GnuTLS: %s", string);
458
479
}
459
480
 
460
481
static int init_gnutls_global(const char *pubkeyfilename,
461
 
                              const char *seckeyfilename){
 
482
                              const char *seckeyfilename,
 
483
                              mandos_context *mc){
462
484
  int ret;
463
485
  
464
486
  if(debug){
465
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
487
    fprintf_plus(stderr, "Initializing GnuTLS\n");
466
488
  }
467
489
  
468
490
  ret = gnutls_global_init();
469
491
  if(ret != GNUTLS_E_SUCCESS){
470
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
471
 
            safer_gnutls_strerror(ret));
 
492
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
493
                 safer_gnutls_strerror(ret));
472
494
    return -1;
473
495
  }
474
496
  
481
503
  }
482
504
  
483
505
  /* OpenPGP credentials */
484
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
506
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
485
507
  if(ret != GNUTLS_E_SUCCESS){
486
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
487
 
            safer_gnutls_strerror(ret));
 
508
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
509
                 safer_gnutls_strerror(ret));
488
510
    gnutls_global_deinit();
489
511
    return -1;
490
512
  }
491
513
  
492
514
  if(debug){
493
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
494
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
495
 
            seckeyfilename);
 
515
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
516
                 " secret key %s as GnuTLS credentials\n",
 
517
                 pubkeyfilename,
 
518
                 seckeyfilename);
496
519
  }
497
520
  
498
521
  ret = gnutls_certificate_set_openpgp_key_file
499
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
522
    (mc->cred, pubkeyfilename, seckeyfilename,
500
523
     GNUTLS_OPENPGP_FMT_BASE64);
501
524
  if(ret != GNUTLS_E_SUCCESS){
502
 
    fprintf(stderr,
503
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
504
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
505
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
506
 
            safer_gnutls_strerror(ret));
 
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));
507
530
    goto globalfail;
508
531
  }
509
532
  
510
533
  /* GnuTLS server initialization */
511
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
534
  ret = gnutls_dh_params_init(&mc->dh_params);
512
535
  if(ret != GNUTLS_E_SUCCESS){
513
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
514
 
            " %s\n", safer_gnutls_strerror(ret));
 
536
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
537
                 " initialization: %s\n",
 
538
                 safer_gnutls_strerror(ret));
515
539
    goto globalfail;
516
540
  }
517
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
541
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
518
542
  if(ret != GNUTLS_E_SUCCESS){
519
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
520
 
            safer_gnutls_strerror(ret));
 
543
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
544
                 safer_gnutls_strerror(ret));
521
545
    goto globalfail;
522
546
  }
523
547
  
524
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
548
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
525
549
  
526
550
  return 0;
527
551
  
528
552
 globalfail:
529
553
  
530
 
  gnutls_certificate_free_credentials(mc.cred);
 
554
  gnutls_certificate_free_credentials(mc->cred);
531
555
  gnutls_global_deinit();
532
 
  gnutls_dh_params_deinit(mc.dh_params);
 
556
  gnutls_dh_params_deinit(mc->dh_params);
533
557
  return -1;
534
558
}
535
559
 
536
 
static int init_gnutls_session(gnutls_session_t *session){
 
560
static int init_gnutls_session(gnutls_session_t *session,
 
561
                               mandos_context *mc){
537
562
  int ret;
538
563
  /* GnuTLS session creation */
539
564
  do {
543
568
    }
544
569
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
545
570
  if(ret != GNUTLS_E_SUCCESS){
546
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
547
 
            safer_gnutls_strerror(ret));
 
571
    fprintf_plus(stderr,
 
572
                 "Error in GnuTLS session initialization: %s\n",
 
573
                 safer_gnutls_strerror(ret));
548
574
  }
549
575
  
550
576
  {
551
577
    const char *err;
552
578
    do {
553
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
579
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
554
580
      if(quit_now){
555
581
        gnutls_deinit(*session);
556
582
        return -1;
557
583
      }
558
584
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
559
585
    if(ret != GNUTLS_E_SUCCESS){
560
 
      fprintf(stderr, "Syntax error at: %s\n", err);
561
 
      fprintf(stderr, "GnuTLS error: %s\n",
562
 
              safer_gnutls_strerror(ret));
 
586
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
587
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
588
                   safer_gnutls_strerror(ret));
563
589
      gnutls_deinit(*session);
564
590
      return -1;
565
591
    }
567
593
  
568
594
  do {
569
595
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
570
 
                                 mc.cred);
 
596
                                 mc->cred);
571
597
    if(quit_now){
572
598
      gnutls_deinit(*session);
573
599
      return -1;
574
600
    }
575
601
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
576
602
  if(ret != GNUTLS_E_SUCCESS){
577
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
578
 
            safer_gnutls_strerror(ret));
 
603
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
604
                 safer_gnutls_strerror(ret));
579
605
    gnutls_deinit(*session);
580
606
    return -1;
581
607
  }
583
609
  /* ignore client certificate if any. */
584
610
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
585
611
  
586
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
612
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
587
613
  
588
614
  return 0;
589
615
}
593
619
                      __attribute__((unused)) const char *txt){}
594
620
 
595
621
/* Called when a Mandos server is found */
596
 
static int start_mandos_communication(const char *ip, uint16_t port,
 
622
static int start_mandos_communication(const char *ip, in_port_t port,
597
623
                                      AvahiIfIndex if_index,
598
 
                                      int af){
 
624
                                      int af, mandos_context *mc){
599
625
  int ret, tcp_sd = -1;
600
626
  ssize_t sret;
601
627
  union {
626
652
    pf = PF_INET;
627
653
    break;
628
654
  default:
629
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
655
    fprintf_plus(stderr, "Bad address family: %d\n", af);
630
656
    errno = EINVAL;
631
657
    return -1;
632
658
  }
633
659
  
634
 
  ret = init_gnutls_session(&session);
 
660
  ret = init_gnutls_session(&session, mc);
635
661
  if(ret != 0){
636
662
    return -1;
637
663
  }
638
664
  
639
665
  if(debug){
640
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
641
 
            "\n", ip, port);
 
666
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
667
                 PRIuMAX "\n", ip, (uintmax_t)port);
642
668
  }
643
669
  
644
670
  tcp_sd = socket(pf, SOCK_STREAM, 0);
670
696
  }
671
697
  if(ret == 0){
672
698
    int e = errno;
673
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
699
    fprintf_plus(stderr, "Bad address: %s\n", ip);
674
700
    errno = e;
675
701
    goto mandos_end;
676
702
  }
677
703
  if(af == AF_INET6){
678
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
679
 
                                       -Wconversion and
680
 
                                       -Wunreachable-code */
681
 
    
 
704
    to.in6.sin6_port = htons(port);    
682
705
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
683
706
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
684
 
                              -Wunreachable-code*/
 
707
                                -Wunreachable-code*/
685
708
      if(if_index == AVAHI_IF_UNSPEC){
686
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
687
 
                " without a network interface\n");
 
709
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
710
                     " incomplete without a network interface\n");
688
711
        errno = EINVAL;
689
712
        goto mandos_end;
690
713
      }
708
731
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
709
732
        perror_plus("if_indextoname");
710
733
      } else {
711
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
712
 
                ip, interface, port);
 
734
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
735
                     "\n", ip, interface, (uintmax_t)port);
713
736
      }
714
737
    } else {
715
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
716
 
              port);
 
738
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
739
                   ip, (uintmax_t)port);
717
740
    }
718
741
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
719
742
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
729
752
      perror_plus("inet_ntop");
730
753
    } else {
731
754
      if(strcmp(addrstr, ip) != 0){
732
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
755
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
733
756
      }
734
757
    }
735
758
  }
763
786
  while(true){
764
787
    size_t out_size = strlen(out);
765
788
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
766
 
                                   out_size - written));
 
789
                                        out_size - written));
767
790
    if(ret == -1){
768
791
      int e = errno;
769
792
      perror_plus("write");
789
812
  }
790
813
  
791
814
  if(debug){
792
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
815
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
793
816
  }
794
817
  
795
818
  if(quit_now){
797
820
    goto mandos_end;
798
821
  }
799
822
  
800
 
  /* Spurious warning from -Wint-to-pointer-cast */
801
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
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);
802
828
  
803
829
  if(quit_now){
804
830
    errno = EINTR;
815
841
  
816
842
  if(ret != GNUTLS_E_SUCCESS){
817
843
    if(debug){
818
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
844
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
819
845
      gnutls_perror(ret);
820
846
    }
821
847
    errno = EPROTO;
825
851
  /* Read OpenPGP packet that contains the wanted password */
826
852
  
827
853
  if(debug){
828
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
829
 
            ip);
 
854
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
855
                 " %s\n", ip);
830
856
  }
831
857
  
832
858
  while(true){
837
863
    }
838
864
    
839
865
    buffer_capacity = incbuffer(&buffer, buffer_length,
840
 
                                   buffer_capacity);
 
866
                                buffer_capacity);
841
867
    if(buffer_capacity == 0){
842
868
      int e = errno;
843
869
      perror_plus("incbuffer");
870
896
          }
871
897
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
872
898
        if(ret < 0){
873
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
899
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
900
                       "***\n");
874
901
          gnutls_perror(ret);
875
902
          errno = EPROTO;
876
903
          goto mandos_end;
877
904
        }
878
905
        break;
879
906
      default:
880
 
        fprintf(stderr, "Unknown error while reading data from"
881
 
                " encrypted session with Mandos server\n");
 
907
        fprintf_plus(stderr, "Unknown error while reading data from"
 
908
                     " encrypted session with Mandos server\n");
882
909
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
883
910
        errno = EIO;
884
911
        goto mandos_end;
889
916
  }
890
917
  
891
918
  if(debug){
892
 
    fprintf(stderr, "Closing TLS session\n");
 
919
    fprintf_plus(stderr, "Closing TLS session\n");
893
920
  }
894
921
  
895
922
  if(quit_now){
907
934
  
908
935
  if(buffer_length > 0){
909
936
    ssize_t decrypted_buffer_size;
910
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
911
 
                                               buffer_length,
912
 
                                               &decrypted_buffer);
 
937
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
938
                                               &decrypted_buffer, mc);
913
939
    if(decrypted_buffer_size >= 0){
914
940
      
915
941
      written = 0;
925
951
        if(ret == 0 and ferror(stdout)){
926
952
          int e = errno;
927
953
          if(debug){
928
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
929
 
                    strerror(errno));
 
954
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
955
                         strerror(errno));
930
956
          }
931
957
          errno = e;
932
958
          goto mandos_end;
976
1002
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
977
1003
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
978
1004
                             flags,
979
 
                             AVAHI_GCC_UNUSED void* userdata){
980
 
  assert(r);
 
1005
                             void* mc){
 
1006
  if(r == NULL){
 
1007
    return;
 
1008
  }
981
1009
  
982
1010
  /* Called whenever a service has been resolved successfully or
983
1011
     timed out */
989
1017
  switch(event){
990
1018
  default:
991
1019
  case AVAHI_RESOLVER_FAILURE:
992
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
993
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
994
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
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)));
995
1025
    break;
996
1026
    
997
1027
  case AVAHI_RESOLVER_FOUND:
999
1029
      char ip[AVAHI_ADDRESS_STR_MAX];
1000
1030
      avahi_address_snprint(ip, sizeof(ip), address);
1001
1031
      if(debug){
1002
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1003
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1004
 
                ip, (intmax_t)interface, port);
 
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);
1005
1035
      }
1006
 
      int ret = start_mandos_communication(ip, port, interface,
1007
 
                                           avahi_proto_to_af(proto));
 
1036
      int ret = start_mandos_communication(ip, (in_port_t)port,
 
1037
                                           interface,
 
1038
                                           avahi_proto_to_af(proto),
 
1039
                                           mc);
1008
1040
      if(ret == 0){
1009
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1041
        avahi_simple_poll_quit(simple_poll);
1010
1042
      } else {
1011
 
        ret = add_server(ip, port, interface,
1012
 
                         avahi_proto_to_af(proto));
 
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
        }
1013
1049
      }
1014
1050
    }
1015
1051
  }
1025
1061
                            const char *domain,
1026
1062
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1027
1063
                            flags,
1028
 
                            AVAHI_GCC_UNUSED void* userdata){
1029
 
  assert(b);
 
1064
                            void* mc){
 
1065
  if(b == NULL){
 
1066
    return;
 
1067
  }
1030
1068
  
1031
1069
  /* Called whenever a new services becomes available on the LAN or
1032
1070
     is removed from the LAN */
1039
1077
  default:
1040
1078
  case AVAHI_BROWSER_FAILURE:
1041
1079
    
1042
 
    fprintf(stderr, "(Avahi browser) %s\n",
1043
 
            avahi_strerror(avahi_server_errno(mc.server)));
1044
 
    avahi_simple_poll_quit(mc.simple_poll);
 
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);
1045
1084
    return;
1046
1085
    
1047
1086
  case AVAHI_BROWSER_NEW:
1050
1089
       the callback function is called the Avahi server will free the
1051
1090
       resolver for us. */
1052
1091
    
1053
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1054
 
                                    name, type, domain, protocol, 0,
1055
 
                                    resolve_callback, NULL) == NULL)
1056
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1057
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
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)));
1058
1100
    break;
1059
1101
    
1060
1102
  case AVAHI_BROWSER_REMOVE:
1063
1105
  case AVAHI_BROWSER_ALL_FOR_NOW:
1064
1106
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1065
1107
    if(debug){
1066
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1108
      fprintf_plus(stderr, "No Mandos server found, still"
 
1109
                   " searching...\n");
1067
1110
    }
1068
1111
    break;
1069
1112
  }
1078
1121
  signal_received = sig;
1079
1122
  int old_errno = errno;
1080
1123
  /* set main loop to exit */
1081
 
  if(mc.simple_poll != NULL){
1082
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1124
  if(simple_poll != NULL){
 
1125
    avahi_simple_poll_quit(simple_poll);
1083
1126
  }
1084
1127
  errno = old_errno;
1085
1128
}
1086
1129
 
 
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){
 
1144
    if(debug){
 
1145
      ret_errno = errno;
 
1146
      perror_plus("ioctl SIOCGIFFLAGS");
 
1147
      errno = ret_errno;
 
1148
    }
 
1149
    return false;
 
1150
  }
 
1151
  return true;
 
1152
}
 
1153
 
 
1154
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1155
  
 
1156
  /* Reject the loopback device */
 
1157
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1158
    if(debug){
 
1159
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1160
                   ifname);
 
1161
    }
 
1162
    return false;
 
1163
  }
 
1164
  /* Accept point-to-point devices only if connect_to is specified */
 
1165
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1166
    if(debug){
 
1167
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1168
                   " \"%s\"\n", ifname);
 
1169
    }
 
1170
    return true;
 
1171
  }
 
1172
  /* Otherwise, reject non-broadcast-capable devices */
 
1173
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1174
    if(debug){
 
1175
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1176
                   " \"%s\"\n", ifname);
 
1177
    }
 
1178
    return false;
 
1179
  }
 
1180
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1181
  if(ifr->ifr_flags & IFF_NOARP){
 
1182
    if(debug){
 
1183
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1184
                   ifname);
 
1185
    }
 
1186
    return false;
 
1187
  }
 
1188
  
 
1189
  /* Accept this device */
 
1190
  if(debug){
 
1191
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1192
  }
 
1193
  return true;
 
1194
}
 
1195
 
1087
1196
/* 
1088
1197
 * This function determines if a directory entry in /sys/class/net
1089
1198
 * corresponds to an acceptable network device.
1090
1199
 * (This function is passed to scandir(3) as a filter function.)
1091
1200
 */
1092
1201
int good_interface(const struct dirent *if_entry){
1093
 
  ssize_t ssret;
1094
 
  char *flagname = NULL;
1095
1202
  if(if_entry->d_name[0] == '.'){
1096
1203
    return 0;
1097
1204
  }
1098
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1099
 
                     if_entry->d_name);
1100
 
  if(ret < 0){
1101
 
    perror_plus("asprintf");
1102
 
    return 0;
1103
 
  }
1104
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1105
 
  if(flags_fd == -1){
1106
 
    perror_plus("open");
1107
 
    free(flagname);
1108
 
    return 0;
1109
 
  }
1110
 
  free(flagname);
1111
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1112
 
  /* read line from flags_fd */
1113
 
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
1114
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1115
 
  flagstring[(size_t)to_read] = '\0';
1116
 
  if(flagstring == NULL){
1117
 
    perror_plus("malloc");
1118
 
    close(flags_fd);
1119
 
    return 0;
1120
 
  }
1121
 
  while(to_read > 0){
1122
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1123
 
                                             (size_t)to_read));
1124
 
    if(ssret == -1){
1125
 
      perror_plus("read");
1126
 
      free(flagstring);
1127
 
      close(flags_fd);
1128
 
      return 0;
1129
 
    }
1130
 
    to_read -= ssret;
1131
 
    if(ssret == 0){
1132
 
      break;
1133
 
    }
1134
 
  }
1135
 
  close(flags_fd);
1136
 
  intmax_t tmpmax;
1137
 
  char *tmp;
1138
 
  errno = 0;
1139
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1140
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1141
 
                                         and not (isspace(*tmp)))
1142
 
     or tmpmax != (ifreq_flags)tmpmax){
1143
 
    if(debug){
1144
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1145
 
              flagstring, if_entry->d_name);
1146
 
    }
1147
 
    free(flagstring);
1148
 
    return 0;
1149
 
  }
1150
 
  free(flagstring);
1151
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
1152
 
  /* Reject the loopback device */
1153
 
  if(flags & IFF_LOOPBACK){
1154
 
    if(debug){
1155
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1156
 
              if_entry->d_name);
1157
 
    }
1158
 
    return 0;
1159
 
  }
1160
 
  /* Accept point-to-point devices only if connect_to is specified */
1161
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1162
 
    if(debug){
1163
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1164
 
              if_entry->d_name);
1165
 
    }
1166
 
    return 1;
1167
 
  }
1168
 
  /* Otherwise, reject non-broadcast-capable devices */
1169
 
  if(not (flags & IFF_BROADCAST)){
1170
 
    if(debug){
1171
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1172
 
              if_entry->d_name);
1173
 
    }
1174
 
    return 0;
1175
 
  }
1176
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1177
 
  if(flags & IFF_NOARP){
1178
 
    if(debug){
1179
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1180
 
              if_entry->d_name);
1181
 
    }
1182
 
    return 0;
1183
 
  }
1184
 
  /* Accept this device */
1185
 
  if(debug){
1186
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1187
 
            if_entry->d_name);
 
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;
1188
1217
  }
1189
1218
  return 1;
1190
1219
}
1191
1220
 
 
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
 
1192
1253
int notdotentries(const struct dirent *direntry){
1193
1254
  /* Skip "." and ".." */
1194
1255
  if(direntry->d_name[0] == '.'
1200
1261
  return 1;
1201
1262
}
1202
1263
 
1203
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
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
1327
  int ret;
1205
1328
  struct timespec now;
1206
1329
  struct timespec waited_time;
1207
1330
  intmax_t block_time;
1208
 
 
 
1331
  
1209
1332
  while(true){
1210
 
    if(mc.current_server == NULL){
 
1333
    if(mc->current_server == NULL){
1211
1334
      if (debug){
1212
 
        fprintf(stderr,
1213
 
                "Wait until first server is found. No timeout!\n");
 
1335
        fprintf_plus(stderr, "Wait until first server is found."
 
1336
                     " No timeout!\n");
1214
1337
      }
1215
1338
      ret = avahi_simple_poll_iterate(s, -1);
1216
1339
    } else {
1217
1340
      if (debug){
1218
 
        fprintf(stderr, "Check current_server if we should run it,"
1219
 
                " or wait\n");
 
1341
        fprintf_plus(stderr, "Check current_server if we should run"
 
1342
                     " it, or wait\n");
1220
1343
      }
1221
1344
      /* the current time */
1222
1345
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1227
1350
      /* Calculating in ms how long time between now and server
1228
1351
         who we visted longest time ago. Now - last seen.  */
1229
1352
      waited_time.tv_sec = (now.tv_sec
1230
 
                            - mc.current_server->last_seen.tv_sec);
 
1353
                            - mc->current_server->last_seen.tv_sec);
1231
1354
      waited_time.tv_nsec = (now.tv_nsec
1232
 
                             - mc.current_server->last_seen.tv_nsec);
 
1355
                             - mc->current_server->last_seen.tv_nsec);
1233
1356
      /* total time is 10s/10,000ms.
1234
1357
         Converting to s from ms by dividing by 1,000,
1235
1358
         and ns to ms by dividing by 1,000,000. */
1236
1359
      block_time = ((retry_interval
1237
1360
                     - ((intmax_t)waited_time.tv_sec * 1000))
1238
1361
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1239
 
 
 
1362
      
1240
1363
      if (debug){
1241
 
        fprintf(stderr, "Blocking for %ld ms\n", block_time);
 
1364
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1365
                     block_time);
1242
1366
      }
1243
 
 
 
1367
      
1244
1368
      if(block_time <= 0){
1245
 
        ret = start_mandos_communication(mc.current_server->ip,
1246
 
                                         mc.current_server->port,
1247
 
                                         mc.current_server->if_index,
1248
 
                                         mc.current_server->af);
 
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);
1249
1373
        if(ret == 0){
1250
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1374
          avahi_simple_poll_quit(s);
1251
1375
          return 0;
1252
1376
        }
1253
1377
        ret = clock_gettime(CLOCK_MONOTONIC,
1254
 
                            &mc.current_server->last_seen);
 
1378
                            &mc->current_server->last_seen);
1255
1379
        if(ret == -1){
1256
1380
          perror_plus("clock_gettime");
1257
1381
          return -1;
1258
1382
        }
1259
 
        mc.current_server = mc.current_server->next;
 
1383
        mc->current_server = mc->current_server->next;
1260
1384
        block_time = 0;         /* Call avahi to find new Mandos
1261
1385
                                   servers, but don't block */
1262
1386
      }
1264
1388
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1265
1389
    }
1266
1390
    if(ret != 0){
1267
 
      if (ret > 0 or errno != EINTR) {
 
1391
      if (ret > 0 or errno != EINTR){
1268
1392
        return (ret != 1) ? ret : 0;
1269
1393
      }
1270
1394
    }
1271
1395
  }
1272
1396
}
1273
1397
 
 
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
 
1274
1755
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 };
1275
1759
  AvahiSServiceBrowser *sb = NULL;
1276
 
  int error;
 
1760
  error_t ret_errno;
1277
1761
  int ret;
1278
1762
  intmax_t tmpmax;
1279
1763
  char *tmp;
1280
1764
  int exitcode = EXIT_SUCCESS;
1281
 
  const char *interface = "";
1282
 
  struct ifreq network;
1283
 
  int sd = -1;
1284
 
  bool take_down_interface = false;
1285
 
  uid_t uid;
1286
 
  gid_t gid;
 
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;
1287
1769
  char tempdir[] = "/tmp/mandosXXXXXX";
1288
1770
  bool tempdir_created = false;
1289
1771
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1290
1772
  const char *seckey = PATHDIR "/" SECKEY;
1291
1773
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1774
  char *interfaces_hooks = NULL;
 
1775
  size_t interfaces_hooks_size = 0;
1292
1776
  
1293
1777
  bool gnutls_initialized = false;
1294
1778
  bool gpgme_initialized = false;
1356
1840
        .group = 2 },
1357
1841
      { .name = "retry", .key = 132,
1358
1842
        .arg = "SECONDS",
1359
 
        .doc = "Retry interval used when denied by the mandos server",
 
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
1848
        .group = 2 },
1361
1849
      /*
1362
1850
       * These reproduce what we would get without ARGP_NO_HELP
1381
1869
        connect_to = arg;
1382
1870
        break;
1383
1871
      case 'i':                 /* --interface */
1384
 
        interface = arg;
 
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
1877
        break;
1386
1878
      case 's':                 /* --seckey */
1387
1879
        seckey = arg;
1411
1903
        errno = 0;
1412
1904
        retry_interval = strtod(arg, &tmp);
1413
1905
        if(errno != 0 or tmp == arg or *tmp != '\0'
1414
 
           or (retry_interval * 1000) > INT_MAX){
 
1906
           or (retry_interval * 1000) > INT_MAX
 
1907
           or retry_interval < 0){
1415
1908
          argp_error(state, "Bad retry interval");
1416
1909
        }
1417
1910
        break;
 
1911
      case 133:                 /* --network-hook-dir */
 
1912
        hookdir = arg;
 
1913
        break;
1418
1914
        /*
1419
1915
         * These reproduce what we would get without ARGP_NO_HELP
1420
1916
         */
1426
1922
        argp_state_help(state, state->out_stream,
1427
1923
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1428
1924
      case 'V':                 /* --version */
1429
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1925
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1430
1926
        exit(argp_err_exit_status);
1431
1927
        break;
1432
1928
      default:
1455
1951
      goto end;
1456
1952
    }
1457
1953
  }
 
1954
    
 
1955
  {
 
1956
    /* Work around Debian bug #633582:
 
1957
       <http://bugs.debian.org/633582> */
 
1958
    
 
1959
    /* 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;
 
2047
    }
 
2048
  }
1458
2049
  
1459
2050
  if(not debug){
1460
2051
    avahi_set_log_function(empty_log);
1461
2052
  }
1462
 
 
1463
 
  if(interface[0] == '\0'){
1464
 
    struct dirent **direntries;
1465
 
    ret = scandir(sys_class_net, &direntries, good_interface,
1466
 
                  alphasort);
1467
 
    if(ret >= 1){
1468
 
      /* Pick the first good interface */
1469
 
      interface = strdup(direntries[0]->d_name);
1470
 
      if(debug){
1471
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1472
 
      }
1473
 
      if(interface == NULL){
1474
 
        perror_plus("malloc");
1475
 
        free(direntries);
1476
 
        exitcode = EXIT_FAILURE;
1477
 
        goto end;
1478
 
      }
1479
 
      free(direntries);
1480
 
    } else {
1481
 
      free(direntries);
1482
 
      fprintf(stderr, "Could not find a network interface\n");
1483
 
      exitcode = EXIT_FAILURE;
1484
 
      goto end;
1485
 
    }
1486
 
  }
1487
2053
  
1488
2054
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1489
2055
     from the signal handler */
1490
2056
  /* Initialize the pseudo-RNG for Avahi */
1491
2057
  srand((unsigned int) time(NULL));
1492
 
  mc.simple_poll = avahi_simple_poll_new();
1493
 
  if(mc.simple_poll == NULL){
1494
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
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");
1495
2062
    exitcode = EX_UNAVAILABLE;
1496
2063
    goto end;
1497
2064
  }
1559
2126
    }
1560
2127
  }
1561
2128
  
1562
 
  /* If the interface is down, bring it up */
1563
 
  if(strcmp(interface, "none") != 0){
1564
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1565
 
    if(if_index == 0){
1566
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1567
 
      exitcode = EX_UNAVAILABLE;
1568
 
      goto end;
1569
 
    }
1570
 
    
1571
 
    if(quit_now){
1572
 
      goto end;
1573
 
    }
1574
 
    
1575
 
    /* Re-raise priviliges */
1576
 
    errno = 0;
1577
 
    ret = seteuid(0);
1578
 
    if(ret == -1){
1579
 
      perror_plus("seteuid");
1580
 
    }
1581
 
    
1582
 
#ifdef __linux__
1583
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1584
 
       messages about the network interface to mess up the prompt */
1585
 
    ret = klogctl(8, NULL, 5);
1586
 
    bool restore_loglevel = true;
1587
 
    if(ret == -1){
1588
 
      restore_loglevel = false;
1589
 
      perror_plus("klogctl");
1590
 
    }
1591
 
#endif  /* __linux__ */
1592
 
    
1593
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1594
 
    if(sd < 0){
1595
 
      perror_plus("socket");
1596
 
      exitcode = EX_OSERR;
1597
 
#ifdef __linux__
1598
 
      if(restore_loglevel){
1599
 
        ret = klogctl(7, NULL, 0);
1600
 
        if(ret == -1){
1601
 
          perror_plus("klogctl");
1602
 
        }
1603
 
      }
1604
 
#endif  /* __linux__ */
1605
 
      /* Lower privileges */
1606
 
      errno = 0;
1607
 
      ret = seteuid(uid);
1608
 
      if(ret == -1){
1609
 
        perror_plus("seteuid");
1610
 
      }
1611
 
      goto end;
1612
 
    }
1613
 
    strcpy(network.ifr_name, interface);
1614
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1615
 
    if(ret == -1){
1616
 
      perror_plus("ioctl SIOCGIFFLAGS");
1617
 
#ifdef __linux__
1618
 
      if(restore_loglevel){
1619
 
        ret = klogctl(7, NULL, 0);
1620
 
        if(ret == -1){
1621
 
          perror_plus("klogctl");
1622
 
        }
1623
 
      }
1624
 
#endif  /* __linux__ */
1625
 
      exitcode = EX_OSERR;
1626
 
      /* Lower privileges */
1627
 
      errno = 0;
1628
 
      ret = seteuid(uid);
1629
 
      if(ret == -1){
1630
 
        perror_plus("seteuid");
1631
 
      }
1632
 
      goto end;
1633
 
    }
1634
 
    if((network.ifr_flags & IFF_UP) == 0){
1635
 
      network.ifr_flags |= IFF_UP;
1636
 
      take_down_interface = true;
1637
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1638
 
      if(ret == -1){
1639
 
        take_down_interface = false;
1640
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1641
 
        exitcode = EX_OSERR;
1642
 
#ifdef __linux__
1643
 
        if(restore_loglevel){
1644
 
          ret = klogctl(7, NULL, 0);
1645
 
          if(ret == -1){
1646
 
            perror_plus("klogctl");
1647
 
          }
1648
 
        }
1649
 
#endif  /* __linux__ */
1650
 
        /* Lower privileges */
1651
 
        errno = 0;
1652
 
        ret = seteuid(uid);
1653
 
        if(ret == -1){
1654
 
          perror_plus("seteuid");
1655
 
        }
1656
 
        goto end;
1657
 
      }
1658
 
    }
1659
 
    /* Sleep checking until interface is running.
1660
 
       Check every 0.25s, up to total time of delay */
1661
 
    for(int i=0; i < delay * 4; i++){
1662
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1663
 
      if(ret == -1){
1664
 
        perror_plus("ioctl SIOCGIFFLAGS");
1665
 
      } else if(network.ifr_flags & IFF_RUNNING){
1666
 
        break;
1667
 
      }
1668
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1669
 
      ret = nanosleep(&sleeptime, NULL);
1670
 
      if(ret == -1 and errno != EINTR){
1671
 
        perror_plus("nanosleep");
1672
 
      }
1673
 
    }
1674
 
    if(not take_down_interface){
1675
 
      /* We won't need the socket anymore */
1676
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1677
 
      if(ret == -1){
1678
 
        perror_plus("close");
1679
 
      }
1680
 
    }
1681
 
#ifdef __linux__
1682
 
    if(restore_loglevel){
1683
 
      /* Restores kernel loglevel to default */
1684
 
      ret = klogctl(7, NULL, 0);
1685
 
      if(ret == -1){
1686
 
        perror_plus("klogctl");
1687
 
      }
1688
 
    }
1689
 
#endif  /* __linux__ */
1690
 
    /* Lower privileges */
1691
 
    errno = 0;
1692
 
    if(take_down_interface){
1693
 
      /* Lower privileges */
1694
 
      ret = seteuid(uid);
1695
 
      if(ret == -1){
1696
 
        perror_plus("seteuid");
1697
 
      }
 
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);
1698
2150
    } else {
1699
 
      /* Lower privileges permanently */
1700
 
      ret = setuid(uid);
1701
 
      if(ret == -1){
1702
 
        perror_plus("setuid");
 
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
        }
1703
2184
      }
1704
2185
    }
 
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
    }
1705
2192
  }
1706
2193
  
1707
2194
  if(quit_now){
1708
2195
    goto end;
1709
2196
  }
1710
2197
  
1711
 
  ret = init_gnutls_global(pubkey, seckey);
 
2198
  ret = init_gnutls_global(pubkey, seckey, &mc);
1712
2199
  if(ret == -1){
1713
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2200
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1714
2201
    exitcode = EX_UNAVAILABLE;
1715
2202
    goto end;
1716
2203
  } else {
1731
2218
    goto end;
1732
2219
  }
1733
2220
  
1734
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
1735
 
    fprintf(stderr, "init_gpgme failed\n");
 
2221
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2222
    fprintf_plus(stderr, "init_gpgme failed\n");
1736
2223
    exitcode = EX_UNAVAILABLE;
1737
2224
    goto end;
1738
2225
  } else {
1747
2234
    /* Connect directly, do not use Zeroconf */
1748
2235
    /* (Mainly meant for debugging) */
1749
2236
    char *address = strrchr(connect_to, ':');
 
2237
    
1750
2238
    if(address == NULL){
1751
 
      fprintf(stderr, "No colon in address\n");
 
2239
      fprintf_plus(stderr, "No colon in address\n");
1752
2240
      exitcode = EX_USAGE;
1753
2241
      goto end;
1754
2242
    }
1757
2245
      goto end;
1758
2246
    }
1759
2247
    
1760
 
    uint16_t port;
 
2248
    in_port_t port;
1761
2249
    errno = 0;
1762
2250
    tmpmax = strtoimax(address+1, &tmp, 10);
1763
2251
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1764
 
       or tmpmax != (uint16_t)tmpmax){
1765
 
      fprintf(stderr, "Bad port number\n");
 
2252
       or tmpmax != (in_port_t)tmpmax){
 
2253
      fprintf_plus(stderr, "Bad port number\n");
1766
2254
      exitcode = EX_USAGE;
1767
2255
      goto end;
1768
2256
    }
1771
2259
      goto end;
1772
2260
    }
1773
2261
    
1774
 
    port = (uint16_t)tmpmax;
 
2262
    port = (in_port_t)tmpmax;
1775
2263
    *address = '\0';
1776
 
    address = connect_to;
1777
2264
    /* Colon in address indicates IPv6 */
1778
2265
    int af;
1779
 
    if(strchr(address, ':') != NULL){
 
2266
    if(strchr(connect_to, ':') != NULL){
1780
2267
      af = AF_INET6;
 
2268
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2269
      if(connect_to[0] == '[' and address[-1] == ']')
 
2270
        {
 
2271
          connect_to++;
 
2272
          address[-1] = '\0';
 
2273
        }
1781
2274
    } else {
1782
2275
      af = AF_INET;
1783
2276
    }
 
2277
    address = connect_to;
1784
2278
    
1785
2279
    if(quit_now){
1786
2280
      goto end;
1787
2281
    }
1788
 
 
 
2282
    
1789
2283
    while(not quit_now){
1790
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2284
      ret = start_mandos_communication(address, port, if_index, af,
 
2285
                                       &mc);
1791
2286
      if(quit_now or ret == 0){
1792
2287
        break;
1793
2288
      }
1794
 
      sleep((int)retry_interval or 1);
1795
 
    };
1796
 
 
 
2289
      if(debug){
 
2290
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2291
                     (int)retry_interval);
 
2292
      }
 
2293
      sleep((int)retry_interval);
 
2294
    }
 
2295
    
1797
2296
    if (not quit_now){
1798
2297
      exitcode = EXIT_SUCCESS;
1799
2298
    }
1800
 
 
 
2299
    
1801
2300
    goto end;
1802
2301
  }
1803
2302
  
1815
2314
    config.publish_domain = 0;
1816
2315
    
1817
2316
    /* Allocate a new server */
1818
 
    mc.server = avahi_server_new(avahi_simple_poll_get
1819
 
                                 (mc.simple_poll), &config, NULL,
1820
 
                                 NULL, &error);
 
2317
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2318
                                 &config, NULL, NULL, &ret_errno);
1821
2319
    
1822
2320
    /* Free the Avahi configuration data */
1823
2321
    avahi_server_config_free(&config);
1825
2323
  
1826
2324
  /* Check if creating the Avahi server object succeeded */
1827
2325
  if(mc.server == NULL){
1828
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1829
 
            avahi_strerror(error));
 
2326
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2327
                 avahi_strerror(ret_errno));
1830
2328
    exitcode = EX_UNAVAILABLE;
1831
2329
    goto end;
1832
2330
  }
1838
2336
  /* Create the Avahi service browser */
1839
2337
  sb = avahi_s_service_browser_new(mc.server, if_index,
1840
2338
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1841
 
                                   NULL, 0, browse_callback, NULL);
 
2339
                                   NULL, 0, browse_callback,
 
2340
                                   (void *)&mc);
1842
2341
  if(sb == NULL){
1843
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1844
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2342
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2343
                 avahi_strerror(avahi_server_errno(mc.server)));
1845
2344
    exitcode = EX_UNAVAILABLE;
1846
2345
    goto end;
1847
2346
  }
1853
2352
  /* Run the main loop */
1854
2353
  
1855
2354
  if(debug){
1856
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2355
    fprintf_plus(stderr, "Starting Avahi loop search\n");
1857
2356
  }
1858
2357
 
1859
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
1860
 
                                (int)(retry_interval * 1000));
 
2358
  ret = avahi_loop_with_timeout(simple_poll,
 
2359
                                (int)(retry_interval * 1000), &mc);
1861
2360
  if(debug){
1862
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
1863
 
            (ret == 0) ? "successfully" : "with error");
 
2361
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2362
                 (ret == 0) ? "successfully" : "with error");
1864
2363
  }
1865
2364
  
1866
2365
 end:
1867
2366
  
1868
2367
  if(debug){
1869
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2368
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1870
2369
  }
1871
2370
  
1872
2371
  /* Cleanup things */
1876
2375
  if(mc.server != NULL)
1877
2376
    avahi_server_free(mc.server);
1878
2377
  
1879
 
  if(mc.simple_poll != NULL)
1880
 
    avahi_simple_poll_free(mc.simple_poll);
 
2378
  if(simple_poll != NULL)
 
2379
    avahi_simple_poll_free(simple_poll);
1881
2380
  
1882
2381
  if(gnutls_initialized){
1883
2382
    gnutls_certificate_free_credentials(mc.cred);
1888
2387
  if(gpgme_initialized){
1889
2388
    gpgme_release(mc.ctx);
1890
2389
  }
1891
 
 
 
2390
  
1892
2391
  /* Cleans up the circular linked list of Mandos servers the client
1893
2392
     has seen */
1894
2393
  if(mc.current_server != NULL){
1900
2399
    }
1901
2400
  }
1902
2401
  
1903
 
  /* Take down the network interface */
1904
 
  if(take_down_interface){
1905
 
    /* Re-raise priviliges */
1906
 
    errno = 0;
1907
 
    ret = seteuid(0);
1908
 
    if(ret == -1){
1909
 
      perror_plus("seteuid");
1910
 
    }
1911
 
    if(geteuid() == 0){
1912
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1913
 
      if(ret == -1){
1914
 
        perror_plus("ioctl SIOCGIFFLAGS");
1915
 
      } else if(network.ifr_flags & IFF_UP) {
1916
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1917
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1918
 
        if(ret == -1){
1919
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
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");
1920
2420
        }
1921
2421
      }
1922
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1923
 
      if(ret == -1){
1924
 
        perror_plus("close");
1925
 
      }
1926
 
      /* Lower privileges permanently */
1927
 
      errno = 0;
1928
 
      ret = setuid(uid);
1929
 
      if(ret == -1){
1930
 
        perror_plus("setuid");
 
2422
      if(debug and (interfaces_to_take_down == NULL)){
 
2423
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2424
                     " down\n");
1931
2425
      }
1932
2426
    }
 
2427
    
 
2428
    lower_privileges_permanently();
1933
2429
  }
1934
2430
  
 
2431
  free(interfaces_to_take_down);
 
2432
  free(interfaces_hooks);
 
2433
  
1935
2434
  /* Removes the GPGME temp directory and all files inside */
1936
2435
  if(tempdir_created){
1937
2436
    struct dirent **direntries = NULL;
1938
2437
    struct dirent *direntry = NULL;
1939
 
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
1940
 
    if (ret > 0){
1941
 
      for(int i = 0; i < ret; i++){
 
2438
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2439
                             alphasort);
 
2440
    if (numentries > 0){
 
2441
      for(int i = 0; i < numentries; i++){
1942
2442
        direntry = direntries[i];
1943
2443
        char *fullname = NULL;
1944
2444
        ret = asprintf(&fullname, "%s/%s", tempdir,
1949
2449
        }
1950
2450
        ret = remove(fullname);
1951
2451
        if(ret == -1){
1952
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1953
 
                  strerror(errno));
 
2452
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2453
                       strerror(errno));
1954
2454
        }
1955
2455
        free(fullname);
1956
2456
      }
1957
2457
    }
1958
2458
 
1959
 
    /* need to be cleaned even if ret == 0 because man page doesn't
1960
 
       specify */
 
2459
    /* need to clean even if 0 because man page doesn't specify */
1961
2460
    free(direntries);
1962
 
    if (ret == -1){
 
2461
    if (numentries == -1){
1963
2462
      perror_plus("scandir");
1964
2463
    }
1965
2464
    ret = rmdir(tempdir);