/mandos/release

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2011-11-26 22:22:20 UTC
  • mto: (237.12.8 mandos-persistent)
  • mto: This revision was merged to the branch mainline in revision 290.
  • Revision ID: teddy@recompile.se-20111126222220-1ubwjpb5ugqnrhec
Directory with persistent state can now be changed with the "statedir"
option.  The state directory /var/lib/mandos now gets created on
installation.  Added documentation about "restore" and "statedir"
options.

* Makefile (USER, GROUP, STATEDIR): New.
  (maintainer-clean): Also remove "statedir".
  (run-server): Replaced "--no-restore" with "--statedir=statedir".
  (statedir): New.
  (install-server): Make $(STATEDIR) directory.
* debian/mandos.dirs (var/lib/mandos): Added.
* debian/mandos.postinst: Fix ownership of /var/lib/mandos.
* mandos: New --statedir option.
  (stored_state_path): Not global anymore.
  (stored_state_file): New global.
* mandos.conf: Fix whitespace.
  (restore, statedir): Added.
* mandos.conf.xml (OPTIONS, EXAMPLE): Added "restore" and "statedir".
  mandos.xml (SYNOPSIS, OPTIONS): Added "--statedir".
  (FILES): Added "/var/lib/mandos".

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;
168
 
mandos_context mc = { .server = NULL, .dh_bits = 1024,
169
 
                      .priority = "SECURE256:!CTYPE-X.509:"
170
 
                      "+CTYPE-OPENPGP", .current_server = NULL };
 
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 };
171
162
 
172
163
sig_atomic_t quit_now = 0;
173
164
int signal_received = 0;
174
165
 
175
166
/* Function to use when printing errors */
176
167
void perror_plus(const char *print_text){
177
 
  int e = errno;
178
168
  fprintf(stderr, "Mandos plugin %s: ",
179
169
          program_invocation_short_name);
180
 
  errno = e;
181
170
  perror(print_text);
182
171
}
183
172
 
184
 
__attribute__((format (gnu_printf, 2, 3)))
185
 
int fprintf_plus(FILE *stream, const char *format, ...){
186
 
  va_list ap;
187
 
  va_start (ap, format);
188
 
  
189
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
190
 
                             program_invocation_short_name));
191
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
192
 
}
193
 
 
194
173
/*
195
174
 * Make additional room in "buffer" for at least BUFFER_SIZE more
196
175
 * bytes. "buffer_capacity" is how much is currently allocated,
197
176
 * "buffer_length" is how much is already used.
198
177
 */
199
178
size_t incbuffer(char **buffer, size_t buffer_length,
200
 
                 size_t buffer_capacity){
 
179
                  size_t buffer_capacity){
201
180
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
202
181
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
203
182
    if(buffer == NULL){
209
188
}
210
189
 
211
190
/* Add server to set of servers to retry periodically */
212
 
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
213
 
                int af){
 
191
int add_server(const char *ip, uint16_t port,
 
192
                 AvahiIfIndex if_index,
 
193
                 int af){
214
194
  int ret;
215
195
  server *new_server = malloc(sizeof(server));
216
196
  if(new_server == NULL){
217
197
    perror_plus("malloc");
218
 
    return false;
 
198
    return -1;
219
199
  }
220
200
  *new_server = (server){ .ip = strdup(ip),
221
 
                          .port = port,
222
 
                          .if_index = if_index,
223
 
                          .af = af };
 
201
                         .port = port,
 
202
                         .if_index = if_index,
 
203
                         .af = af };
224
204
  if(new_server->ip == NULL){
225
205
    perror_plus("strdup");
226
 
    return false;
 
206
    return -1;
227
207
  }
228
208
  /* Special case of first server */
229
209
  if (mc.current_server == NULL){
240
220
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
241
221
  if(ret == -1){
242
222
    perror_plus("clock_gettime");
243
 
    return false;
 
223
    return -1;
244
224
  }
245
 
  return true;
 
225
  return 0;
246
226
}
247
227
 
248
228
/* 
249
229
 * Initialize GPGME.
250
230
 */
251
 
static bool init_gpgme(const char *seckey, const char *pubkey,
252
 
                       const char *tempdir){
 
231
static bool init_gpgme(const char *seckey,
 
232
                       const char *pubkey, const char *tempdir){
253
233
  gpgme_error_t rc;
254
234
  gpgme_engine_info_t engine_info;
255
235
  
 
236
  
256
237
  /*
257
238
   * Helper function to insert pub and seckey to the engine keyring.
258
239
   */
269
250
    
270
251
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
271
252
    if(rc != GPG_ERR_NO_ERROR){
272
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
273
 
                   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));
274
255
      return false;
275
256
    }
276
257
    
277
258
    rc = gpgme_op_import(mc.ctx, pgp_data);
278
259
    if(rc != GPG_ERR_NO_ERROR){
279
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
280
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
260
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
261
              gpgme_strsource(rc), gpgme_strerror(rc));
281
262
      return false;
282
263
    }
283
264
    
290
271
  }
291
272
  
292
273
  if(debug){
293
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
274
    fprintf(stderr, "Initializing GPGME\n");
294
275
  }
295
276
  
296
277
  /* Init GPGME */
297
278
  gpgme_check_version(NULL);
298
279
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
299
280
  if(rc != GPG_ERR_NO_ERROR){
300
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
301
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
281
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
282
            gpgme_strsource(rc), gpgme_strerror(rc));
302
283
    return false;
303
284
  }
304
285
  
305
286
  /* Set GPGME home directory for the OpenPGP engine only */
306
287
  rc = gpgme_get_engine_info(&engine_info);
307
288
  if(rc != GPG_ERR_NO_ERROR){
308
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
309
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
289
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
290
            gpgme_strsource(rc), gpgme_strerror(rc));
310
291
    return false;
311
292
  }
312
293
  while(engine_info != NULL){
318
299
    engine_info = engine_info->next;
319
300
  }
320
301
  if(engine_info == NULL){
321
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
322
 
                 tempdir);
 
302
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
323
303
    return false;
324
304
  }
325
305
  
326
306
  /* Create new GPGME "context" */
327
307
  rc = gpgme_new(&(mc.ctx));
328
308
  if(rc != GPG_ERR_NO_ERROR){
329
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
330
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
331
 
                 gpgme_strerror(rc));
 
309
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
310
            gpgme_strsource(rc), gpgme_strerror(rc));
332
311
    return false;
333
312
  }
334
313
  
353
332
  ssize_t plaintext_length = 0;
354
333
  
355
334
  if(debug){
356
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
335
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
357
336
  }
358
337
  
359
338
  /* Create new GPGME data buffer from memory cryptotext */
360
339
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
361
340
                               0);
362
341
  if(rc != GPG_ERR_NO_ERROR){
363
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
364
 
                 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));
365
344
    return -1;
366
345
  }
367
346
  
368
347
  /* Create new empty GPGME data buffer for the plaintext */
369
348
  rc = gpgme_data_new(&dh_plain);
370
349
  if(rc != GPG_ERR_NO_ERROR){
371
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
372
 
                 "bad gpgme_data_new: %s: %s\n",
373
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
350
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
351
            gpgme_strsource(rc), gpgme_strerror(rc));
374
352
    gpgme_data_release(dh_crypto);
375
353
    return -1;
376
354
  }
379
357
     data buffer */
380
358
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
381
359
  if(rc != GPG_ERR_NO_ERROR){
382
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
383
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
360
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
361
            gpgme_strsource(rc), gpgme_strerror(rc));
384
362
    plaintext_length = -1;
385
363
    if(debug){
386
364
      gpgme_decrypt_result_t result;
387
365
      result = gpgme_op_decrypt_result(mc.ctx);
388
366
      if(result == NULL){
389
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
367
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
390
368
      } else {
391
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
392
 
                     result->unsupported_algorithm);
393
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
394
 
                     result->wrong_key_usage);
 
369
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
370
                result->unsupported_algorithm);
 
371
        fprintf(stderr, "Wrong key usage: %u\n",
 
372
                result->wrong_key_usage);
395
373
        if(result->file_name != NULL){
396
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
374
          fprintf(stderr, "File name: %s\n", result->file_name);
397
375
        }
398
376
        gpgme_recipient_t recipient;
399
377
        recipient = result->recipients;
400
378
        while(recipient != NULL){
401
 
          fprintf_plus(stderr, "Public key algorithm: %s\n",
402
 
                       gpgme_pubkey_algo_name
403
 
                       (recipient->pubkey_algo));
404
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
405
 
          fprintf_plus(stderr, "Secret key available: %s\n",
406
 
                       recipient->status == GPG_ERR_NO_SECKEY
407
 
                       ? "No" : "Yes");
 
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");
408
385
          recipient = recipient->next;
409
386
        }
410
387
      }
413
390
  }
414
391
  
415
392
  if(debug){
416
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
393
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
417
394
  }
418
395
  
419
396
  /* Seek back to the beginning of the GPGME plaintext data buffer */
426
403
  *plaintext = NULL;
427
404
  while(true){
428
405
    plaintext_capacity = incbuffer(plaintext,
429
 
                                   (size_t)plaintext_length,
430
 
                                   plaintext_capacity);
 
406
                                      (size_t)plaintext_length,
 
407
                                      plaintext_capacity);
431
408
    if(plaintext_capacity == 0){
432
 
      perror_plus("incbuffer");
433
 
      plaintext_length = -1;
434
 
      goto decrypt_end;
 
409
        perror_plus("incbuffer");
 
410
        plaintext_length = -1;
 
411
        goto decrypt_end;
435
412
    }
436
413
    
437
414
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
450
427
  }
451
428
  
452
429
  if(debug){
453
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
430
    fprintf(stderr, "Decrypted password is: ");
454
431
    for(ssize_t i = 0; i < plaintext_length; i++){
455
432
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
456
433
    }
468
445
}
469
446
 
470
447
static const char * safer_gnutls_strerror(int value){
471
 
  const char *ret = gnutls_strerror(value);
 
448
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
449
                                               -Wunreachable-code */
472
450
  if(ret == NULL)
473
451
    ret = "(unknown)";
474
452
  return ret;
477
455
/* GnuTLS log function callback */
478
456
static void debuggnutls(__attribute__((unused)) int level,
479
457
                        const char* string){
480
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
458
  fprintf(stderr, "GnuTLS: %s", string);
481
459
}
482
460
 
483
461
static int init_gnutls_global(const char *pubkeyfilename,
485
463
  int ret;
486
464
  
487
465
  if(debug){
488
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
466
    fprintf(stderr, "Initializing GnuTLS\n");
489
467
  }
490
468
  
491
469
  ret = gnutls_global_init();
492
470
  if(ret != GNUTLS_E_SUCCESS){
493
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
494
 
                 safer_gnutls_strerror(ret));
 
471
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
472
            safer_gnutls_strerror(ret));
495
473
    return -1;
496
474
  }
497
475
  
506
484
  /* OpenPGP credentials */
507
485
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
508
486
  if(ret != GNUTLS_E_SUCCESS){
509
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
510
 
                 safer_gnutls_strerror(ret));
 
487
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
488
            safer_gnutls_strerror(ret));
511
489
    gnutls_global_deinit();
512
490
    return -1;
513
491
  }
514
492
  
515
493
  if(debug){
516
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
517
 
                 " secret key %s as GnuTLS credentials\n",
518
 
                 pubkeyfilename,
519
 
                 seckeyfilename);
 
494
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
495
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
496
            seckeyfilename);
520
497
  }
521
498
  
522
499
  ret = gnutls_certificate_set_openpgp_key_file
523
500
    (mc.cred, pubkeyfilename, seckeyfilename,
524
501
     GNUTLS_OPENPGP_FMT_BASE64);
525
502
  if(ret != GNUTLS_E_SUCCESS){
526
 
    fprintf_plus(stderr,
527
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
528
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
529
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
530
 
                 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));
531
508
    goto globalfail;
532
509
  }
533
510
  
534
511
  /* GnuTLS server initialization */
535
512
  ret = gnutls_dh_params_init(&mc.dh_params);
536
513
  if(ret != GNUTLS_E_SUCCESS){
537
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
538
 
                 " initialization: %s\n",
539
 
                 safer_gnutls_strerror(ret));
 
514
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
515
            " %s\n", safer_gnutls_strerror(ret));
540
516
    goto globalfail;
541
517
  }
542
518
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
543
519
  if(ret != GNUTLS_E_SUCCESS){
544
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
545
 
                 safer_gnutls_strerror(ret));
 
520
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
521
            safer_gnutls_strerror(ret));
546
522
    goto globalfail;
547
523
  }
548
524
  
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
  {
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
    }
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
  }
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
599
                                      int af){
625
600
  int ret, tcp_sd = -1;
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
  }
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,
 
911
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
912
                                               buffer_length,
938
913
                                               &decrypted_buffer);
939
914
    if(decrypted_buffer_size >= 0){
940
915
      
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;
1003
978
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1004
979
                             flags,
1005
980
                             AVAHI_GCC_UNUSED void* userdata){
1006
 
  if(r == NULL){
1007
 
    return;
1008
 
  }
 
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(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)));
1024
996
    break;
1025
997
    
1026
998
  case AVAHI_RESOLVER_FOUND:
1028
1000
      char ip[AVAHI_ADDRESS_STR_MAX];
1029
1001
      avahi_address_snprint(ip, sizeof(ip), address);
1030
1002
      if(debug){
1031
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1032
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1033
 
                     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);
1034
1006
      }
1035
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1036
 
                                           interface,
 
1007
      int ret = start_mandos_communication(ip, port, interface,
1037
1008
                                           avahi_proto_to_af(proto));
1038
1009
      if(ret == 0){
1039
 
        avahi_simple_poll_quit(simple_poll);
 
1010
        avahi_simple_poll_quit(mc.simple_poll);
1040
1011
      } else {
1041
 
        if(not add_server(ip, (in_port_t)port, interface,
1042
 
                          avahi_proto_to_af(proto))){
1043
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1044
 
                       " list\n", name);
1045
 
        }
 
1012
        ret = add_server(ip, port, interface,
 
1013
                         avahi_proto_to_af(proto));
1046
1014
      }
1047
1015
    }
1048
1016
  }
1059
1027
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1060
1028
                            flags,
1061
1029
                            AVAHI_GCC_UNUSED void* userdata){
1062
 
  if(b == NULL){
1063
 
    return;
1064
 
  }
 
1030
  assert(b);
1065
1031
  
1066
1032
  /* Called whenever a new services becomes available on the LAN or
1067
1033
     is removed from the LAN */
1074
1040
  default:
1075
1041
  case AVAHI_BROWSER_FAILURE:
1076
1042
    
1077
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1078
 
                 avahi_strerror(avahi_server_errno(mc.server)));
1079
 
    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);
1080
1046
    return;
1081
1047
    
1082
1048
  case AVAHI_BROWSER_NEW:
1088
1054
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1089
1055
                                    name, type, domain, protocol, 0,
1090
1056
                                    resolve_callback, NULL) == NULL)
1091
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1092
 
                   " %s\n", name,
1093
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1057
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1058
              name, avahi_strerror(avahi_server_errno(mc.server)));
1094
1059
    break;
1095
1060
    
1096
1061
  case AVAHI_BROWSER_REMOVE:
1099
1064
  case AVAHI_BROWSER_ALL_FOR_NOW:
1100
1065
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1101
1066
    if(debug){
1102
 
      fprintf_plus(stderr, "No Mandos server found, still"
1103
 
                   " searching...\n");
 
1067
      fprintf(stderr, "No Mandos server found, still searching...\n");
1104
1068
    }
1105
1069
    break;
1106
1070
  }
1115
1079
  signal_received = sig;
1116
1080
  int old_errno = errno;
1117
1081
  /* set main loop to exit */
1118
 
  if(simple_poll != NULL){
1119
 
    avahi_simple_poll_quit(simple_poll);
 
1082
  if(mc.simple_poll != NULL){
 
1083
    avahi_simple_poll_quit(mc.simple_poll);
1120
1084
  }
1121
1085
  errno = old_errno;
1122
1086
}
1123
1087
 
1124
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1125
 
  int ret;
1126
 
  error_t ret_errno;
1127
 
  
1128
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1129
 
  if(s < 0){
1130
 
    ret_errno = errno;
1131
 
    perror_plus("socket");
1132
 
    errno = ret_errno;
1133
 
    return false;
1134
 
  }
1135
 
  strcpy(ifr->ifr_name, ifname);
1136
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1137
 
  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){
1138
1144
    if(debug){
1139
 
      ret_errno = errno;
1140
 
      perror_plus("ioctl SIOCGIFFLAGS");
1141
 
      errno = ret_errno;
 
1145
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1146
              flagstring, if_entry->d_name);
1142
1147
    }
1143
 
    return false;
 
1148
    free(flagstring);
 
1149
    return 0;
1144
1150
  }
1145
 
  return true;
1146
 
}
1147
 
 
1148
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1149
 
  
 
1151
  free(flagstring);
 
1152
  ifreq_flags flags = (ifreq_flags)tmpmax;
1150
1153
  /* Reject the loopback device */
1151
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1154
  if(flags & IFF_LOOPBACK){
1152
1155
    if(debug){
1153
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1154
 
                   ifname);
 
1156
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1157
              if_entry->d_name);
1155
1158
    }
1156
 
    return false;
 
1159
    return 0;
1157
1160
  }
1158
1161
  /* Accept point-to-point devices only if connect_to is specified */
1159
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1162
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1160
1163
    if(debug){
1161
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1162
 
                   " \"%s\"\n", ifname);
 
1164
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1165
              if_entry->d_name);
1163
1166
    }
1164
 
    return true;
 
1167
    return 1;
1165
1168
  }
1166
1169
  /* Otherwise, reject non-broadcast-capable devices */
1167
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1170
  if(not (flags & IFF_BROADCAST)){
1168
1171
    if(debug){
1169
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1170
 
                   " \"%s\"\n", ifname);
 
1172
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1173
              if_entry->d_name);
1171
1174
    }
1172
 
    return false;
 
1175
    return 0;
1173
1176
  }
1174
1177
  /* Reject non-ARP interfaces (including dummy interfaces) */
1175
 
  if(ifr->ifr_flags & IFF_NOARP){
 
1178
  if(flags & IFF_NOARP){
1176
1179
    if(debug){
1177
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1178
 
                   ifname);
 
1180
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1181
              if_entry->d_name);
1179
1182
    }
1180
 
    return false;
 
1183
    return 0;
1181
1184
  }
1182
 
  
1183
1185
  /* Accept this device */
1184
1186
  if(debug){
1185
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1186
 
  }
1187
 
  return true;
1188
 
}
1189
 
 
1190
 
/* 
1191
 
 * This function determines if a directory entry in /sys/class/net
1192
 
 * corresponds to an acceptable network device.
1193
 
 * (This function is passed to scandir(3) as a filter function.)
1194
 
 */
1195
 
int good_interface(const struct dirent *if_entry){
1196
 
  if(if_entry->d_name[0] == '.'){
1197
 
    return 0;
1198
 
  }
1199
 
  
1200
 
  struct ifreq ifr;
1201
 
  if(not get_flags(if_entry->d_name, &ifr)){
1202
 
    if(debug){
1203
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1204
 
                   "\"%s\"\n", if_entry->d_name);
1205
 
    }
1206
 
    return 0;
1207
 
  }
1208
 
  
1209
 
  if(not good_flags(if_entry->d_name, &ifr)){
1210
 
    return 0;
 
1187
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1188
            if_entry->d_name);
1211
1189
  }
1212
1190
  return 1;
1213
1191
}
1214
1192
 
1215
 
/* 
1216
 
 * This function determines if a network interface is up.
1217
 
 */
1218
 
bool interface_is_up(const char *interface){
1219
 
  struct ifreq ifr;
1220
 
  if(not get_flags(interface, &ifr)){
1221
 
    if(debug){
1222
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1223
 
                   "\"%s\"\n", interface);
1224
 
    }
1225
 
    return false;
1226
 
  }
1227
 
  
1228
 
  return (bool)(ifr.ifr_flags & IFF_UP);
1229
 
}
1230
 
 
1231
 
/* 
1232
 
 * This function determines if a network interface is running
1233
 
 */
1234
 
bool interface_is_running(const char *interface){
1235
 
  struct ifreq ifr;
1236
 
  if(not get_flags(interface, &ifr)){
1237
 
    if(debug){
1238
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1239
 
                   "\"%s\"\n", interface);
1240
 
    }
1241
 
    return false;
1242
 
  }
1243
 
  
1244
 
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1245
 
}
1246
 
 
1247
1193
int notdotentries(const struct dirent *direntry){
1248
1194
  /* Skip "." and ".." */
1249
1195
  if(direntry->d_name[0] == '.'
1255
1201
  return 1;
1256
1202
}
1257
1203
 
1258
 
/* Is this directory entry a runnable program? */
1259
 
int runnable_hook(const struct dirent *direntry){
1260
 
  int ret;
1261
 
  size_t sret;
1262
 
  struct stat st;
1263
 
  
1264
 
  if((direntry->d_name)[0] == '\0'){
1265
 
    /* Empty name? */
1266
 
    return 0;
1267
 
  }
1268
 
  
1269
 
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1270
 
                "abcdefghijklmnopqrstuvwxyz"
1271
 
                "0123456789"
1272
 
                "_-");
1273
 
  if((direntry->d_name)[sret] != '\0'){
1274
 
    /* Contains non-allowed characters */
1275
 
    if(debug){
1276
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1277
 
                   direntry->d_name);
1278
 
    }
1279
 
    return 0;
1280
 
  }
1281
 
  
1282
 
  char *fullname = NULL;
1283
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1284
 
  if(ret < 0){
1285
 
    perror_plus("asprintf");
1286
 
    return 0;
1287
 
  }
1288
 
  
1289
 
  ret = stat(fullname, &st);
1290
 
  if(ret == -1){
1291
 
    if(debug){
1292
 
      perror_plus("Could not stat hook");
1293
 
    }
1294
 
    return 0;
1295
 
  }
1296
 
  if(not (S_ISREG(st.st_mode))){
1297
 
    /* Not a regular file */
1298
 
    if(debug){
1299
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1300
 
                   direntry->d_name);
1301
 
    }
1302
 
    return 0;
1303
 
  }
1304
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1305
 
    /* Not executable */
1306
 
    if(debug){
1307
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1308
 
                   direntry->d_name);
1309
 
    }
1310
 
    return 0;
1311
 
  }
1312
 
  if(debug){
1313
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1314
 
                 direntry->d_name);
1315
 
  }
1316
 
  return 1;
1317
 
}
1318
 
 
1319
1204
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1320
1205
  int ret;
1321
1206
  struct timespec now;
1325
1210
  while(true){
1326
1211
    if(mc.current_server == NULL){
1327
1212
      if (debug){
1328
 
        fprintf_plus(stderr, "Wait until first server is found."
1329
 
                     " No timeout!\n");
 
1213
        fprintf(stderr,
 
1214
                "Wait until first server is found. No timeout!\n");
1330
1215
      }
1331
1216
      ret = avahi_simple_poll_iterate(s, -1);
1332
1217
    } else {
1333
1218
      if (debug){
1334
 
        fprintf_plus(stderr, "Check current_server if we should run"
1335
 
                     " it, or wait\n");
 
1219
        fprintf(stderr, "Check current_server if we should run it,"
 
1220
                " or wait\n");
1336
1221
      }
1337
1222
      /* the current time */
1338
1223
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1354
1239
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1355
1240
      
1356
1241
      if (debug){
1357
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1358
 
                     block_time);
 
1242
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1359
1243
      }
1360
1244
      
1361
1245
      if(block_time <= 0){
1364
1248
                                         mc.current_server->if_index,
1365
1249
                                         mc.current_server->af);
1366
1250
        if(ret == 0){
1367
 
          avahi_simple_poll_quit(simple_poll);
 
1251
          avahi_simple_poll_quit(mc.simple_poll);
1368
1252
          return 0;
1369
1253
        }
1370
1254
        ret = clock_gettime(CLOCK_MONOTONIC,
1381
1265
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1382
1266
    }
1383
1267
    if(ret != 0){
1384
 
      if (ret > 0 or errno != EINTR){
 
1268
      if (ret > 0 or errno != EINTR) {
1385
1269
        return (ret != 1) ? ret : 0;
1386
1270
      }
1387
1271
    }
1388
1272
  }
1389
1273
}
1390
1274
 
1391
 
/* Set effective uid to 0, return errno */
1392
 
error_t raise_privileges(void){
1393
 
  error_t old_errno = errno;
1394
 
  error_t ret_errno = 0;
1395
 
  if(seteuid(0) == -1){
1396
 
    ret_errno = errno;
1397
 
    perror_plus("seteuid");
1398
 
  }
1399
 
  errno = old_errno;
1400
 
  return ret_errno;
1401
 
}
1402
 
 
1403
 
/* Set effective and real user ID to 0.  Return errno. */
1404
 
error_t raise_privileges_permanently(void){
1405
 
  error_t old_errno = errno;
1406
 
  error_t ret_errno = raise_privileges();
1407
 
  if(ret_errno != 0){
1408
 
    errno = old_errno;
1409
 
    return ret_errno;
1410
 
  }
1411
 
  if(setuid(0) == -1){
1412
 
    ret_errno = errno;
1413
 
    perror_plus("seteuid");
1414
 
  }
1415
 
  errno = old_errno;
1416
 
  return ret_errno;
1417
 
}
1418
 
 
1419
 
/* Set effective user ID to unprivileged saved user ID */
1420
 
error_t lower_privileges(void){
1421
 
  error_t old_errno = errno;
1422
 
  error_t ret_errno = 0;
1423
 
  if(seteuid(uid) == -1){
1424
 
    ret_errno = errno;
1425
 
    perror_plus("seteuid");
1426
 
  }
1427
 
  errno = old_errno;
1428
 
  return ret_errno;
1429
 
}
1430
 
 
1431
 
/* Lower privileges permanently */
1432
 
error_t lower_privileges_permanently(void){
1433
 
  error_t old_errno = errno;
1434
 
  error_t ret_errno = 0;
1435
 
  if(setuid(uid) == -1){
1436
 
    ret_errno = errno;
1437
 
    perror_plus("setuid");
1438
 
  }
1439
 
  errno = old_errno;
1440
 
  return ret_errno;
1441
 
}
1442
 
 
1443
 
bool run_network_hooks(const char *mode, const char *interface,
1444
 
                       const float delay){
1445
 
  struct dirent **direntries;
1446
 
  struct dirent *direntry;
1447
 
  int ret;
1448
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1449
 
                         alphasort);
1450
 
  if(numhooks == -1){
1451
 
    if(errno == ENOENT){
1452
 
      if(debug){
1453
 
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
1454
 
                     " found\n", hookdir);
1455
 
      }
1456
 
    } else {
1457
 
      perror_plus("scandir");
1458
 
    }
1459
 
  } else {
1460
 
    int devnull = open("/dev/null", O_RDONLY);
1461
 
    for(int i = 0; i < numhooks; i++){
1462
 
      direntry = direntries[i];
1463
 
      char *fullname = NULL;
1464
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1465
 
      if(ret < 0){
1466
 
        perror_plus("asprintf");
1467
 
        continue;
1468
 
      }
1469
 
      if(debug){
1470
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1471
 
                     direntry->d_name);
1472
 
      }
1473
 
      pid_t hook_pid = fork();
1474
 
      if(hook_pid == 0){
1475
 
        /* Child */
1476
 
        /* Raise privileges */
1477
 
        raise_privileges_permanently();
1478
 
        /* Set group */
1479
 
        errno = 0;
1480
 
        ret = setgid(0);
1481
 
        if(ret == -1){
1482
 
          perror_plus("setgid");
1483
 
        }
1484
 
        /* Reset supplementary groups */
1485
 
        errno = 0;
1486
 
        ret = setgroups(0, NULL);
1487
 
        if(ret == -1){
1488
 
          perror_plus("setgroups");
1489
 
        }
1490
 
        dup2(devnull, STDIN_FILENO);
1491
 
        close(devnull);
1492
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1493
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1494
 
        if(ret == -1){
1495
 
          perror_plus("setenv");
1496
 
          _exit(EX_OSERR);
1497
 
        }
1498
 
        ret = setenv("DEVICE", interface, 1);
1499
 
        if(ret == -1){
1500
 
          perror_plus("setenv");
1501
 
          _exit(EX_OSERR);
1502
 
        }
1503
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1504
 
        if(ret == -1){
1505
 
          perror_plus("setenv");
1506
 
          _exit(EX_OSERR);
1507
 
        }
1508
 
        ret = setenv("MODE", mode, 1);
1509
 
        if(ret == -1){
1510
 
          perror_plus("setenv");
1511
 
          _exit(EX_OSERR);
1512
 
        }
1513
 
        char *delaystring;
1514
 
        ret = asprintf(&delaystring, "%f", delay);
1515
 
        if(ret == -1){
1516
 
          perror_plus("asprintf");
1517
 
          _exit(EX_OSERR);
1518
 
        }
1519
 
        ret = setenv("DELAY", delaystring, 1);
1520
 
        if(ret == -1){
1521
 
          free(delaystring);
1522
 
          perror_plus("setenv");
1523
 
          _exit(EX_OSERR);
1524
 
        }
1525
 
        free(delaystring);
1526
 
        if(connect_to != NULL){
1527
 
          ret = setenv("CONNECT", connect_to, 1);
1528
 
          if(ret == -1){
1529
 
            perror_plus("setenv");
1530
 
            _exit(EX_OSERR);
1531
 
          }
1532
 
        }
1533
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1534
 
          perror_plus("execl");
1535
 
          _exit(EXIT_FAILURE);
1536
 
        }
1537
 
      } else {
1538
 
        int status;
1539
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1540
 
          perror_plus("waitpid");
1541
 
          free(fullname);
1542
 
          continue;
1543
 
        }
1544
 
        if(WIFEXITED(status)){
1545
 
          if(WEXITSTATUS(status) != 0){
1546
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1547
 
                         " with status %d\n", direntry->d_name,
1548
 
                         WEXITSTATUS(status));
1549
 
            free(fullname);
1550
 
            continue;
1551
 
          }
1552
 
        } else if(WIFSIGNALED(status)){
1553
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1554
 
                       " signal %d\n", direntry->d_name,
1555
 
                       WTERMSIG(status));
1556
 
          free(fullname);
1557
 
          continue;
1558
 
        } else {
1559
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1560
 
                       " crashed\n", direntry->d_name);
1561
 
          free(fullname);
1562
 
          continue;
1563
 
        }
1564
 
      }
1565
 
      free(fullname);
1566
 
      if(debug){
1567
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1568
 
                     direntry->d_name);
1569
 
      }
1570
 
    }
1571
 
    close(devnull);
1572
 
  }
1573
 
  return true;
1574
 
}
1575
 
 
1576
 
error_t bring_up_interface(const char *const interface,
1577
 
                           const float delay){
1578
 
  int sd = -1;
1579
 
  error_t old_errno = errno;
1580
 
  error_t ret_errno = 0;
1581
 
  int ret, ret_setflags;
1582
 
  struct ifreq network;
1583
 
  unsigned int if_index = if_nametoindex(interface);
1584
 
  if(if_index == 0){
1585
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1586
 
    errno = old_errno;
1587
 
    return ENXIO;
1588
 
  }
1589
 
  
1590
 
  if(quit_now){
1591
 
    errno = old_errno;
1592
 
    return EINTR;
1593
 
  }
1594
 
  
1595
 
  if(not interface_is_up(interface)){
1596
 
    if(not get_flags(interface, &network) and debug){
1597
 
      ret_errno = errno;
1598
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1599
 
                   "\"%s\"\n", interface);
1600
 
      return ret_errno;
1601
 
    }
1602
 
    network.ifr_flags |= IFF_UP;
1603
 
    
1604
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1605
 
    if(sd < 0){
1606
 
      ret_errno = errno;
1607
 
      perror_plus("socket");
1608
 
      errno = old_errno;
1609
 
      return ret_errno;
1610
 
    }
1611
 
  
1612
 
    if(quit_now){
1613
 
      close(sd);
1614
 
      errno = old_errno;
1615
 
      return EINTR;
1616
 
    }
1617
 
    
1618
 
    if(debug){
1619
 
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
1620
 
                   interface);
1621
 
    }
1622
 
    
1623
 
    /* Raise priviliges */
1624
 
    raise_privileges();
1625
 
    
1626
 
#ifdef __linux__
1627
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1628
 
       messages about the network interface to mess up the prompt */
1629
 
    int ret_linux = klogctl(8, NULL, 5);
1630
 
    bool restore_loglevel = true;
1631
 
    if(ret_linux == -1){
1632
 
      restore_loglevel = false;
1633
 
      perror_plus("klogctl");
1634
 
    }
1635
 
#endif  /* __linux__ */
1636
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1637
 
    ret_errno = errno;
1638
 
#ifdef __linux__
1639
 
    if(restore_loglevel){
1640
 
      ret_linux = klogctl(7, NULL, 0);
1641
 
      if(ret_linux == -1){
1642
 
        perror_plus("klogctl");
1643
 
      }
1644
 
    }
1645
 
#endif  /* __linux__ */
1646
 
    
1647
 
    /* Lower privileges */
1648
 
    lower_privileges();
1649
 
    
1650
 
    /* Close the socket */
1651
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1652
 
    if(ret == -1){
1653
 
      perror_plus("close");
1654
 
    }
1655
 
    
1656
 
    if(ret_setflags == -1){
1657
 
      errno = ret_errno;
1658
 
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1659
 
      errno = old_errno;
1660
 
      return ret_errno;
1661
 
    }
1662
 
  } else if(debug){
1663
 
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1664
 
                 interface);
1665
 
  }
1666
 
  
1667
 
  /* Sleep checking until interface is running.
1668
 
     Check every 0.25s, up to total time of delay */
1669
 
  for(int i=0; i < delay * 4; i++){
1670
 
    if(interface_is_running(interface)){
1671
 
      break;
1672
 
    }
1673
 
    struct timespec sleeptime = { .tv_nsec = 250000000 };
1674
 
    ret = nanosleep(&sleeptime, NULL);
1675
 
    if(ret == -1 and errno != EINTR){
1676
 
      perror_plus("nanosleep");
1677
 
    }
1678
 
  }
1679
 
  
1680
 
  errno = old_errno;
1681
 
  return 0;
1682
 
}
1683
 
 
1684
 
error_t take_down_interface(const char *const interface){
1685
 
  int sd = -1;
1686
 
  error_t old_errno = errno;
1687
 
  error_t ret_errno = 0;
1688
 
  int ret, ret_setflags;
1689
 
  struct ifreq network;
1690
 
  unsigned int if_index = if_nametoindex(interface);
1691
 
  if(if_index == 0){
1692
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1693
 
    errno = old_errno;
1694
 
    return ENXIO;
1695
 
  }
1696
 
  if(interface_is_up(interface)){
1697
 
    if(not get_flags(interface, &network) and debug){
1698
 
      ret_errno = errno;
1699
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1700
 
                   "\"%s\"\n", interface);
1701
 
      return ret_errno;
1702
 
    }
1703
 
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1704
 
    
1705
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1706
 
    if(sd < 0){
1707
 
      ret_errno = errno;
1708
 
      perror_plus("socket");
1709
 
      errno = old_errno;
1710
 
      return ret_errno;
1711
 
    }
1712
 
    
1713
 
    if(debug){
1714
 
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
1715
 
                   interface);
1716
 
    }
1717
 
    
1718
 
    /* Raise priviliges */
1719
 
    raise_privileges();
1720
 
    
1721
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1722
 
    ret_errno = errno;
1723
 
    
1724
 
    /* Lower privileges */
1725
 
    lower_privileges();
1726
 
    
1727
 
    /* Close the socket */
1728
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1729
 
    if(ret == -1){
1730
 
      perror_plus("close");
1731
 
    }
1732
 
    
1733
 
    if(ret_setflags == -1){
1734
 
      errno = ret_errno;
1735
 
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1736
 
      errno = old_errno;
1737
 
      return ret_errno;
1738
 
    }
1739
 
  } else if(debug){
1740
 
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1741
 
                 interface);
1742
 
  }
1743
 
  
1744
 
  errno = old_errno;
1745
 
  return 0;
1746
 
}
1747
 
 
1748
1275
int main(int argc, char *argv[]){
1749
1276
  AvahiSServiceBrowser *sb = NULL;
1750
 
  error_t ret_errno;
 
1277
  int error;
1751
1278
  int ret;
1752
1279
  intmax_t tmpmax;
1753
1280
  char *tmp;
1754
1281
  int exitcode = EXIT_SUCCESS;
1755
 
  char *interfaces = NULL;
1756
 
  size_t interfaces_size = 0;
1757
 
  char *interfaces_to_take_down = NULL;
1758
 
  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;
1759
1288
  char tempdir[] = "/tmp/mandosXXXXXX";
1760
1289
  bool tempdir_created = false;
1761
1290
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1762
1291
  const char *seckey = PATHDIR "/" SECKEY;
1763
1292
  const char *pubkey = PATHDIR "/" PUBKEY;
1764
 
  char *interfaces_hooks = NULL;
1765
 
  size_t interfaces_hooks_size = 0;
1766
1293
  
1767
1294
  bool gnutls_initialized = false;
1768
1295
  bool gpgme_initialized = false;
1830
1357
        .group = 2 },
1831
1358
      { .name = "retry", .key = 132,
1832
1359
        .arg = "SECONDS",
1833
 
        .doc = "Retry interval used when denied by the Mandos server",
1834
 
        .group = 2 },
1835
 
      { .name = "network-hook-dir", .key = 133,
1836
 
        .arg = "DIR",
1837
 
        .doc = "Directory where network hooks are located",
 
1360
        .doc = "Retry interval used when denied by the mandos server",
1838
1361
        .group = 2 },
1839
1362
      /*
1840
1363
       * These reproduce what we would get without ARGP_NO_HELP
1859
1382
        connect_to = arg;
1860
1383
        break;
1861
1384
      case 'i':                 /* --interface */
1862
 
        ret_errno = argz_add_sep(&interfaces, &interfaces_size, arg,
1863
 
                                 (int)',');
1864
 
        if(ret_errno != 0){
1865
 
          argp_error(state, "%s", strerror(ret_errno));
1866
 
        }
 
1385
        interface = arg;
1867
1386
        break;
1868
1387
      case 's':                 /* --seckey */
1869
1388
        seckey = arg;
1898
1417
          argp_error(state, "Bad retry interval");
1899
1418
        }
1900
1419
        break;
1901
 
      case 133:                 /* --network-hook-dir */
1902
 
        hookdir = arg;
1903
 
        break;
1904
1420
        /*
1905
1421
         * These reproduce what we would get without ARGP_NO_HELP
1906
1422
         */
1912
1428
        argp_state_help(state, state->out_stream,
1913
1429
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1914
1430
      case 'V':                 /* --version */
1915
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1431
        fprintf(state->out_stream, "%s\n", argp_program_version);
1916
1432
        exit(argp_err_exit_status);
1917
1433
        break;
1918
1434
      default:
1945
1461
  {
1946
1462
    /* Work around Debian bug #633582:
1947
1463
       <http://bugs.debian.org/633582> */
 
1464
    struct stat st;
1948
1465
    
1949
1466
    /* Re-raise priviliges */
1950
 
    if(raise_privileges() == 0){
1951
 
      struct stat st;
1952
 
      
1953
 
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1954
 
        int seckey_fd = open(seckey, O_RDONLY);
1955
 
        if(seckey_fd == -1){
1956
 
          perror_plus("open");
1957
 
        } else {
1958
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1959
 
          if(ret == -1){
1960
 
            perror_plus("fstat");
1961
 
          } else {
1962
 
            if(S_ISREG(st.st_mode)
1963
 
               and st.st_uid == 0 and st.st_gid == 0){
1964
 
              ret = fchown(seckey_fd, uid, gid);
1965
 
              if(ret == -1){
1966
 
                perror_plus("fchown");
1967
 
              }
1968
 
            }
1969
 
          }
1970
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
1971
 
        }
1972
 
      }
1973
 
    
1974
 
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1975
 
        int pubkey_fd = open(pubkey, O_RDONLY);
1976
 
        if(pubkey_fd == -1){
1977
 
          perror_plus("open");
1978
 
        } else {
1979
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1980
 
          if(ret == -1){
1981
 
            perror_plus("fstat");
1982
 
          } else {
1983
 
            if(S_ISREG(st.st_mode)
1984
 
               and st.st_uid == 0 and st.st_gid == 0){
1985
 
              ret = fchown(pubkey_fd, uid, gid);
1986
 
              if(ret == -1){
1987
 
                perror_plus("fchown");
1988
 
              }
1989
 
            }
1990
 
          }
1991
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
1992
 
        }
1993
 
      }
1994
 
    
1995
 
      /* Lower privileges */
1996
 
      errno = 0;
1997
 
      ret = seteuid(uid);
1998
 
      if(ret == -1){
1999
 
        perror_plus("seteuid");
2000
 
      }
2001
 
    }
2002
 
  }
2003
 
  
2004
 
  /* Remove empty interface names */
2005
 
  {
2006
 
    char *interface = NULL;
2007
 
    while((interface = argz_next(interfaces, interfaces_size,
2008
 
                                 interface))){
2009
 
      if(if_nametoindex(interface) == 0){
2010
 
        if(interface[0] != '\0' and strcmp(interface, "none") != 0){
2011
 
          fprintf_plus(stderr, "Not using nonexisting interface"
2012
 
                       " \"%s\"\n", interface);
2013
 
        }
2014
 
        argz_delete(&interfaces, &interfaces_size, interface);
2015
 
        interface = NULL;
2016
 
      }
2017
 
    }
2018
 
  }
2019
 
  
2020
 
  /* Run network hooks */
2021
 
  {
2022
 
    
2023
 
    if(interfaces != NULL){
2024
 
      interfaces_hooks = malloc(interfaces_size);
2025
 
      if(interfaces_hooks == NULL){
2026
 
        perror_plus("malloc");
2027
 
        goto end;
2028
 
      }
2029
 
      memcpy(interfaces_hooks, interfaces, interfaces_size);
2030
 
      interfaces_hooks_size = interfaces_size;
2031
 
      argz_stringify(interfaces_hooks, interfaces_hooks_size,
2032
 
                     (int)',');
2033
 
    }
2034
 
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
2035
 
                             interfaces_hooks : "", delay)){
2036
 
      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");
2037
1518
    }
2038
1519
  }
2039
1520
  
2040
1521
  if(not debug){
2041
1522
    avahi_set_log_function(empty_log);
2042
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
  }
2043
1549
  
2044
1550
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2045
1551
     from the signal handler */
2046
1552
  /* Initialize the pseudo-RNG for Avahi */
2047
1553
  srand((unsigned int) time(NULL));
2048
 
  simple_poll = avahi_simple_poll_new();
2049
 
  if(simple_poll == NULL){
2050
 
    fprintf_plus(stderr,
2051
 
                 "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");
2052
1557
    exitcode = EX_UNAVAILABLE;
2053
1558
    goto end;
2054
1559
  }
2116
1621
    }
2117
1622
  }
2118
1623
  
2119
 
  /* If no interfaces were specified, make a list */
2120
 
  if(interfaces == NULL){
2121
 
    struct dirent **direntries;
2122
 
    /* Look for any good interfaces */
2123
 
    ret = scandir(sys_class_net, &direntries, good_interface,
2124
 
                  alphasort);
2125
 
    if(ret >= 1){
2126
 
      /* Add all found interfaces to interfaces list */
2127
 
      for(int i = 0; i < ret; ++i){
2128
 
        ret_errno = argz_add(&interfaces, &interfaces_size,
2129
 
                             direntries[i]->d_name);
2130
 
        if(ret_errno != 0){
2131
 
          perror_plus("argz_add");
2132
 
          continue;
2133
 
        }
2134
 
        if(debug){
2135
 
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2136
 
                       direntries[i]->d_name);
2137
 
        }
2138
 
      }
2139
 
      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
      }
2140
1760
    } else {
2141
 
      free(direntries);
2142
 
      fprintf_plus(stderr, "Could not find a network interface\n");
2143
 
      exitcode = EXIT_FAILURE;
2144
 
      goto end;
2145
 
    }
2146
 
  }
2147
 
  
2148
 
  /* If we only got one interface, explicitly use only that one */
2149
 
  if(argz_count(interfaces, interfaces_size) == 1){
2150
 
    if(debug){
2151
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2152
 
                   interfaces);
2153
 
    }
2154
 
    if_index = (AvahiIfIndex)if_nametoindex(interfaces);
2155
 
  }
2156
 
  
2157
 
  /* Bring up interfaces which are down */
2158
 
  if(not (argz_count(interfaces, interfaces_size) == 1
2159
 
          and strcmp(interfaces, "none") == 0)){
2160
 
    char *interface = NULL;
2161
 
    while((interface = argz_next(interfaces, interfaces_size,
2162
 
                                 interface))){
2163
 
      bool interface_was_up = interface_is_up(interface);
2164
 
      ret = bring_up_interface(interface, delay);
2165
 
      if(not interface_was_up){
2166
 
        if(ret != 0){
2167
 
          errno = ret;
2168
 
          perror_plus("Failed to bring up interface");
2169
 
        } else {
2170
 
          ret_errno = argz_add(&interfaces_to_take_down,
2171
 
                               &interfaces_to_take_down_size,
2172
 
                               interface);
2173
 
        }
 
1761
      /* Lower privileges permanently */
 
1762
      ret = setuid(uid);
 
1763
      if(ret == -1){
 
1764
        perror_plus("setuid");
2174
1765
      }
2175
1766
    }
2176
 
    free(interfaces);
2177
 
    interfaces = NULL;
2178
 
    interfaces_size = 0;
2179
 
    if(debug and (interfaces_to_take_down == NULL)){
2180
 
      fprintf_plus(stderr, "No interfaces were brought up\n");
2181
 
    }
2182
1767
  }
2183
1768
  
2184
1769
  if(quit_now){
2187
1772
  
2188
1773
  ret = init_gnutls_global(pubkey, seckey);
2189
1774
  if(ret == -1){
2190
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1775
    fprintf(stderr, "init_gnutls_global failed\n");
2191
1776
    exitcode = EX_UNAVAILABLE;
2192
1777
    goto end;
2193
1778
  } else {
2209
1794
  }
2210
1795
  
2211
1796
  if(not init_gpgme(pubkey, seckey, tempdir)){
2212
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1797
    fprintf(stderr, "init_gpgme failed\n");
2213
1798
    exitcode = EX_UNAVAILABLE;
2214
1799
    goto end;
2215
1800
  } else {
2224
1809
    /* Connect directly, do not use Zeroconf */
2225
1810
    /* (Mainly meant for debugging) */
2226
1811
    char *address = strrchr(connect_to, ':');
2227
 
    
2228
1812
    if(address == NULL){
2229
 
      fprintf_plus(stderr, "No colon in address\n");
 
1813
      fprintf(stderr, "No colon in address\n");
2230
1814
      exitcode = EX_USAGE;
2231
1815
      goto end;
2232
1816
    }
2235
1819
      goto end;
2236
1820
    }
2237
1821
    
2238
 
    in_port_t port;
 
1822
    uint16_t port;
2239
1823
    errno = 0;
2240
1824
    tmpmax = strtoimax(address+1, &tmp, 10);
2241
1825
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2242
 
       or tmpmax != (in_port_t)tmpmax){
2243
 
      fprintf_plus(stderr, "Bad port number\n");
 
1826
       or tmpmax != (uint16_t)tmpmax){
 
1827
      fprintf(stderr, "Bad port number\n");
2244
1828
      exitcode = EX_USAGE;
2245
1829
      goto end;
2246
1830
    }
2249
1833
      goto end;
2250
1834
    }
2251
1835
    
2252
 
    port = (in_port_t)tmpmax;
 
1836
    port = (uint16_t)tmpmax;
2253
1837
    *address = '\0';
2254
1838
    /* Colon in address indicates IPv6 */
2255
1839
    int af;
2276
1860
        break;
2277
1861
      }
2278
1862
      if(debug){
2279
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2280
 
                     (int)retry_interval);
 
1863
        fprintf(stderr, "Retrying in %d seconds\n",
 
1864
                (int)retry_interval);
2281
1865
      }
2282
1866
      sleep((int)retry_interval);
2283
1867
    }
2285
1869
    if (not quit_now){
2286
1870
      exitcode = EXIT_SUCCESS;
2287
1871
    }
2288
 
    
 
1872
 
2289
1873
    goto end;
2290
1874
  }
2291
1875
  
2303
1887
    config.publish_domain = 0;
2304
1888
    
2305
1889
    /* Allocate a new server */
2306
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2307
 
                                 &config, NULL, NULL, &ret_errno);
 
1890
    mc.server = avahi_server_new(avahi_simple_poll_get
 
1891
                                 (mc.simple_poll), &config, NULL,
 
1892
                                 NULL, &error);
2308
1893
    
2309
1894
    /* Free the Avahi configuration data */
2310
1895
    avahi_server_config_free(&config);
2312
1897
  
2313
1898
  /* Check if creating the Avahi server object succeeded */
2314
1899
  if(mc.server == NULL){
2315
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2316
 
                 avahi_strerror(ret_errno));
 
1900
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1901
            avahi_strerror(error));
2317
1902
    exitcode = EX_UNAVAILABLE;
2318
1903
    goto end;
2319
1904
  }
2327
1912
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2328
1913
                                   NULL, 0, browse_callback, NULL);
2329
1914
  if(sb == NULL){
2330
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2331
 
                 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)));
2332
1917
    exitcode = EX_UNAVAILABLE;
2333
1918
    goto end;
2334
1919
  }
2340
1925
  /* Run the main loop */
2341
1926
  
2342
1927
  if(debug){
2343
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
1928
    fprintf(stderr, "Starting Avahi loop search\n");
2344
1929
  }
2345
1930
 
2346
 
  ret = avahi_loop_with_timeout(simple_poll,
 
1931
  ret = avahi_loop_with_timeout(mc.simple_poll,
2347
1932
                                (int)(retry_interval * 1000));
2348
1933
  if(debug){
2349
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2350
 
                 (ret == 0) ? "successfully" : "with error");
 
1934
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1935
            (ret == 0) ? "successfully" : "with error");
2351
1936
  }
2352
1937
  
2353
1938
 end:
2354
1939
  
2355
1940
  if(debug){
2356
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
1941
    fprintf(stderr, "%s exiting\n", argv[0]);
2357
1942
  }
2358
1943
  
2359
1944
  /* Cleanup things */
2363
1948
  if(mc.server != NULL)
2364
1949
    avahi_server_free(mc.server);
2365
1950
  
2366
 
  if(simple_poll != NULL)
2367
 
    avahi_simple_poll_free(simple_poll);
 
1951
  if(mc.simple_poll != NULL)
 
1952
    avahi_simple_poll_free(mc.simple_poll);
2368
1953
  
2369
1954
  if(gnutls_initialized){
2370
1955
    gnutls_certificate_free_credentials(mc.cred);
2375
1960
  if(gpgme_initialized){
2376
1961
    gpgme_release(mc.ctx);
2377
1962
  }
2378
 
  
 
1963
 
2379
1964
  /* Cleans up the circular linked list of Mandos servers the client
2380
1965
     has seen */
2381
1966
  if(mc.current_server != NULL){
2387
1972
    }
2388
1973
  }
2389
1974
  
2390
 
  /* Re-raise priviliges */
2391
 
  {
2392
 
    raise_privileges();
2393
 
    
2394
 
    /* Run network hooks */
2395
 
    run_network_hooks("stop", interfaces_hooks != NULL ?
2396
 
                      interfaces_hooks : "", delay);
2397
 
    
2398
 
    /* Take down the network interfaces which were brought up */
2399
 
    {
2400
 
      char *interface = NULL;
2401
 
      while((interface=argz_next(interfaces_to_take_down,
2402
 
                                 interfaces_to_take_down_size,
2403
 
                                 interface))){
2404
 
        ret_errno = take_down_interface(interface);
2405
 
        if(ret_errno != 0){
2406
 
          errno = ret_errno;
2407
 
          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");
2408
1992
        }
2409
1993
      }
2410
 
      if(debug and (interfaces_to_take_down == NULL)){
2411
 
        fprintf_plus(stderr, "No interfaces needed to be taken"
2412
 
                     " 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");
2413
2003
      }
2414
2004
    }
2415
 
    
2416
 
    lower_privileges_permanently();
2417
2005
  }
2418
2006
  
2419
 
  free(interfaces_to_take_down);
2420
 
  free(interfaces_hooks);
2421
 
  
2422
2007
  /* Removes the GPGME temp directory and all files inside */
2423
2008
  if(tempdir_created){
2424
2009
    struct dirent **direntries = NULL;
2437
2022
        }
2438
2023
        ret = remove(fullname);
2439
2024
        if(ret == -1){
2440
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2441
 
                       strerror(errno));
 
2025
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
2026
                  strerror(errno));
2442
2027
        }
2443
2028
        free(fullname);
2444
2029
      }