/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

* initramfs-tools-script: Bug fix: Add missing "--options" argument to
                          getopt.

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
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.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, 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() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit() */
 
76
                                   setgid(), pause() */
77
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
78
#include <iso646.h>             /* not, or, and */
79
79
#include <argp.h>               /* struct argp_option, error_t, struct
85
85
                                   raise() */
86
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
90
 
#include <grp.h>                /* setgroups() */
91
88
 
92
89
#ifdef __linux__
93
90
#include <sys/klog.h>           /* klogctl() */
111
108
                                   init_gnutls_session(),
112
109
                                   GNUTLS_* */
113
110
#include <gnutls/openpgp.h>
114
 
                         /* gnutls_certificate_set_openpgp_key_file(),
115
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
111
                          /* gnutls_certificate_set_openpgp_key_file(),
 
112
                                   GNUTLS_OPENPGP_FMT_BASE64 */
116
113
 
117
114
/* GPGME */
118
115
#include <gpgme.h>              /* All GPGME types, constants and
126
123
#define PATHDIR "/conf/conf.d/mandos"
127
124
#define SECKEY "seckey.txt"
128
125
#define PUBKEY "pubkey.txt"
129
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
130
126
 
131
127
bool debug = false;
132
128
static const char mandos_protocol_version[] = "1";
133
129
const char *argp_program_version = "mandos-client " VERSION;
134
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
130
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
135
131
static const char sys_class_net[] = "/sys/class/net";
136
132
char *connect_to = NULL;
137
 
const char *hookdir = HOOKDIR;
138
133
 
139
134
/* Doubly linked list that need to be circularly linked when used */
140
135
typedef struct server{
170
165
 
171
166
/* Function to use when printing errors */
172
167
void perror_plus(const char *print_text){
173
 
  int e = errno;
174
168
  fprintf(stderr, "Mandos plugin %s: ",
175
169
          program_invocation_short_name);
176
 
  errno = e;
177
170
  perror(print_text);
178
171
}
179
172
 
180
 
__attribute__((format (gnu_printf, 2, 3)))
181
 
int fprintf_plus(FILE *stream, const char *format, ...){
182
 
  va_list ap;
183
 
  va_start (ap, format);
184
 
  
185
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
186
 
                             program_invocation_short_name));
187
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
188
 
}
189
 
 
190
173
/*
191
174
 * Make additional room in "buffer" for at least BUFFER_SIZE more
192
175
 * bytes. "buffer_capacity" is how much is currently allocated,
193
176
 * "buffer_length" is how much is already used.
194
177
 */
195
178
size_t incbuffer(char **buffer, size_t buffer_length,
196
 
                 size_t buffer_capacity){
 
179
                  size_t buffer_capacity){
197
180
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
198
181
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
199
182
    if(buffer == NULL){
204
187
  return buffer_capacity;
205
188
}
206
189
 
207
 
/* Add server to set of servers to retry periodically */
208
 
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
209
 
                int af){
 
190
int add_server(const char *ip, uint16_t port,
 
191
                 AvahiIfIndex if_index,
 
192
                 int af){
210
193
  int ret;
211
194
  server *new_server = malloc(sizeof(server));
212
195
  if(new_server == NULL){
213
196
    perror_plus("malloc");
214
 
    return false;
 
197
    return -1;
215
198
  }
216
199
  *new_server = (server){ .ip = strdup(ip),
217
 
                          .port = port,
218
 
                          .if_index = if_index,
219
 
                          .af = af };
 
200
                         .port = port,
 
201
                         .if_index = if_index,
 
202
                         .af = af };
220
203
  if(new_server->ip == NULL){
221
204
    perror_plus("strdup");
222
 
    return false;
 
205
    return -1;
223
206
  }
224
 
  /* Special case of first server */
 
207
  /* unique case of first server */
225
208
  if (mc.current_server == NULL){
226
209
    new_server->next = new_server;
227
210
    new_server->prev = new_server;
228
211
    mc.current_server = new_server;
229
 
  /* Place the new server last in the list */
 
212
  /* Placing the new server last in the list */
230
213
  } else {
231
214
    new_server->next = mc.current_server;
232
215
    new_server->prev = mc.current_server->prev;
236
219
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
237
220
  if(ret == -1){
238
221
    perror_plus("clock_gettime");
239
 
    return false;
 
222
    return -1;
240
223
  }
241
 
  return true;
 
224
  return 0;
242
225
}
243
226
 
244
227
/* 
245
228
 * Initialize GPGME.
246
229
 */
247
 
static bool init_gpgme(const char *seckey, const char *pubkey,
248
 
                       const char *tempdir){
 
230
static bool init_gpgme(const char *seckey,
 
231
                       const char *pubkey, const char *tempdir){
249
232
  gpgme_error_t rc;
250
233
  gpgme_engine_info_t engine_info;
251
234
  
266
249
    
267
250
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
268
251
    if(rc != GPG_ERR_NO_ERROR){
269
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
270
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
252
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
253
              gpgme_strsource(rc), gpgme_strerror(rc));
271
254
      return false;
272
255
    }
273
256
    
274
257
    rc = gpgme_op_import(mc.ctx, pgp_data);
275
258
    if(rc != GPG_ERR_NO_ERROR){
276
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
277
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
259
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
260
              gpgme_strsource(rc), gpgme_strerror(rc));
278
261
      return false;
279
262
    }
280
263
    
287
270
  }
288
271
  
289
272
  if(debug){
290
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
273
    fprintf(stderr, "Initializing GPGME\n");
291
274
  }
292
275
  
293
276
  /* Init GPGME */
294
277
  gpgme_check_version(NULL);
295
278
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
296
279
  if(rc != GPG_ERR_NO_ERROR){
297
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
298
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
280
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
281
            gpgme_strsource(rc), gpgme_strerror(rc));
299
282
    return false;
300
283
  }
301
284
  
302
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
285
    /* Set GPGME home directory for the OpenPGP engine only */
303
286
  rc = gpgme_get_engine_info(&engine_info);
304
287
  if(rc != GPG_ERR_NO_ERROR){
305
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
306
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
288
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
289
            gpgme_strsource(rc), gpgme_strerror(rc));
307
290
    return false;
308
291
  }
309
292
  while(engine_info != NULL){
315
298
    engine_info = engine_info->next;
316
299
  }
317
300
  if(engine_info == NULL){
318
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
319
 
                 tempdir);
 
301
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
320
302
    return false;
321
303
  }
322
304
  
323
305
  /* Create new GPGME "context" */
324
306
  rc = gpgme_new(&(mc.ctx));
325
307
  if(rc != GPG_ERR_NO_ERROR){
326
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
327
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
328
 
                 gpgme_strerror(rc));
 
308
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
309
            gpgme_strsource(rc), gpgme_strerror(rc));
329
310
    return false;
330
311
  }
331
312
  
350
331
  ssize_t plaintext_length = 0;
351
332
  
352
333
  if(debug){
353
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
334
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
354
335
  }
355
336
  
356
337
  /* Create new GPGME data buffer from memory cryptotext */
357
338
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
358
339
                               0);
359
340
  if(rc != GPG_ERR_NO_ERROR){
360
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
361
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
341
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
342
            gpgme_strsource(rc), gpgme_strerror(rc));
362
343
    return -1;
363
344
  }
364
345
  
365
346
  /* Create new empty GPGME data buffer for the plaintext */
366
347
  rc = gpgme_data_new(&dh_plain);
367
348
  if(rc != GPG_ERR_NO_ERROR){
368
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
369
 
                 "bad gpgme_data_new: %s: %s\n",
370
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
349
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
350
            gpgme_strsource(rc), gpgme_strerror(rc));
371
351
    gpgme_data_release(dh_crypto);
372
352
    return -1;
373
353
  }
376
356
     data buffer */
377
357
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
378
358
  if(rc != GPG_ERR_NO_ERROR){
379
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
380
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
359
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
360
            gpgme_strsource(rc), gpgme_strerror(rc));
381
361
    plaintext_length = -1;
382
362
    if(debug){
383
363
      gpgme_decrypt_result_t result;
384
364
      result = gpgme_op_decrypt_result(mc.ctx);
385
365
      if(result == NULL){
386
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
366
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
387
367
      } else {
388
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
389
 
                     result->unsupported_algorithm);
390
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
391
 
                     result->wrong_key_usage);
 
368
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
369
                result->unsupported_algorithm);
 
370
        fprintf(stderr, "Wrong key usage: %u\n",
 
371
                result->wrong_key_usage);
392
372
        if(result->file_name != NULL){
393
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
373
          fprintf(stderr, "File name: %s\n", result->file_name);
394
374
        }
395
375
        gpgme_recipient_t recipient;
396
376
        recipient = result->recipients;
397
377
        while(recipient != NULL){
398
 
          fprintf_plus(stderr, "Public key algorithm: %s\n",
399
 
                       gpgme_pubkey_algo_name
400
 
                       (recipient->pubkey_algo));
401
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
402
 
          fprintf_plus(stderr, "Secret key available: %s\n",
403
 
                       recipient->status == GPG_ERR_NO_SECKEY
404
 
                       ? "No" : "Yes");
 
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");
405
384
          recipient = recipient->next;
406
385
        }
407
386
      }
410
389
  }
411
390
  
412
391
  if(debug){
413
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
392
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
414
393
  }
415
394
  
416
395
  /* Seek back to the beginning of the GPGME plaintext data buffer */
423
402
  *plaintext = NULL;
424
403
  while(true){
425
404
    plaintext_capacity = incbuffer(plaintext,
426
 
                                   (size_t)plaintext_length,
427
 
                                   plaintext_capacity);
 
405
                                      (size_t)plaintext_length,
 
406
                                      plaintext_capacity);
428
407
    if(plaintext_capacity == 0){
429
 
      perror_plus("incbuffer");
430
 
      plaintext_length = -1;
431
 
      goto decrypt_end;
 
408
        perror_plus("incbuffer");
 
409
        plaintext_length = -1;
 
410
        goto decrypt_end;
432
411
    }
433
412
    
434
413
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
447
426
  }
448
427
  
449
428
  if(debug){
450
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
429
    fprintf(stderr, "Decrypted password is: ");
451
430
    for(ssize_t i = 0; i < plaintext_length; i++){
452
431
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
453
432
    }
475
454
/* GnuTLS log function callback */
476
455
static void debuggnutls(__attribute__((unused)) int level,
477
456
                        const char* string){
478
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
457
  fprintf(stderr, "GnuTLS: %s", string);
479
458
}
480
459
 
481
460
static int init_gnutls_global(const char *pubkeyfilename,
483
462
  int ret;
484
463
  
485
464
  if(debug){
486
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
465
    fprintf(stderr, "Initializing GnuTLS\n");
487
466
  }
488
467
  
489
468
  ret = gnutls_global_init();
490
469
  if(ret != GNUTLS_E_SUCCESS){
491
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
492
 
                 safer_gnutls_strerror(ret));
 
470
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
471
            safer_gnutls_strerror(ret));
493
472
    return -1;
494
473
  }
495
474
  
504
483
  /* OpenPGP credentials */
505
484
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
506
485
  if(ret != GNUTLS_E_SUCCESS){
507
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
508
 
                 safer_gnutls_strerror(ret));
 
486
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
487
            safer_gnutls_strerror(ret));
509
488
    gnutls_global_deinit();
510
489
    return -1;
511
490
  }
512
491
  
513
492
  if(debug){
514
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
515
 
                 " secret key %s as GnuTLS credentials\n",
516
 
                 pubkeyfilename,
517
 
                 seckeyfilename);
 
493
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
494
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
495
            seckeyfilename);
518
496
  }
519
497
  
520
498
  ret = gnutls_certificate_set_openpgp_key_file
521
499
    (mc.cred, pubkeyfilename, seckeyfilename,
522
500
     GNUTLS_OPENPGP_FMT_BASE64);
523
501
  if(ret != GNUTLS_E_SUCCESS){
524
 
    fprintf_plus(stderr,
525
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
526
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
527
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
528
 
                 safer_gnutls_strerror(ret));
 
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));
529
507
    goto globalfail;
530
508
  }
531
509
  
532
510
  /* GnuTLS server initialization */
533
511
  ret = gnutls_dh_params_init(&mc.dh_params);
534
512
  if(ret != GNUTLS_E_SUCCESS){
535
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
536
 
                 " initialization: %s\n",
537
 
                 safer_gnutls_strerror(ret));
 
513
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
514
            " %s\n", safer_gnutls_strerror(ret));
538
515
    goto globalfail;
539
516
  }
540
517
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
541
518
  if(ret != GNUTLS_E_SUCCESS){
542
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
543
 
                 safer_gnutls_strerror(ret));
 
519
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
520
            safer_gnutls_strerror(ret));
544
521
    goto globalfail;
545
522
  }
546
523
  
566
543
    }
567
544
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
568
545
  if(ret != GNUTLS_E_SUCCESS){
569
 
    fprintf_plus(stderr,
570
 
                 "Error in GnuTLS session initialization: %s\n",
571
 
                 safer_gnutls_strerror(ret));
 
546
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
547
            safer_gnutls_strerror(ret));
572
548
  }
573
549
  
574
550
  {
581
557
      }
582
558
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
583
559
    if(ret != GNUTLS_E_SUCCESS){
584
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
585
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
586
 
                   safer_gnutls_strerror(ret));
 
560
      fprintf(stderr, "Syntax error at: %s\n", err);
 
561
      fprintf(stderr, "GnuTLS error: %s\n",
 
562
              safer_gnutls_strerror(ret));
587
563
      gnutls_deinit(*session);
588
564
      return -1;
589
565
    }
598
574
    }
599
575
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
600
576
  if(ret != GNUTLS_E_SUCCESS){
601
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
602
 
                 safer_gnutls_strerror(ret));
 
577
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
578
            safer_gnutls_strerror(ret));
603
579
    gnutls_deinit(*session);
604
580
    return -1;
605
581
  }
650
626
    pf = PF_INET;
651
627
    break;
652
628
  default:
653
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
629
    fprintf(stderr, "Bad address family: %d\n", af);
654
630
    errno = EINVAL;
655
631
    return -1;
656
632
  }
661
637
  }
662
638
  
663
639
  if(debug){
664
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
665
 
                 PRIu16 "\n", ip, port);
 
640
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
641
            "\n", ip, port);
666
642
  }
667
643
  
668
644
  tcp_sd = socket(pf, SOCK_STREAM, 0);
694
670
  }
695
671
  if(ret == 0){
696
672
    int e = errno;
697
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
673
    fprintf(stderr, "Bad address: %s\n", ip);
698
674
    errno = e;
699
675
    goto mandos_end;
700
676
  }
705
681
    
706
682
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
707
683
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
708
 
                                -Wunreachable-code*/
 
684
                              -Wunreachable-code*/
709
685
      if(if_index == AVAHI_IF_UNSPEC){
710
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
711
 
                     " incomplete without a network interface\n");
 
686
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
687
                " without a network interface\n");
712
688
        errno = EINVAL;
713
689
        goto mandos_end;
714
690
      }
732
708
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
733
709
        perror_plus("if_indextoname");
734
710
      } else {
735
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
736
 
                     "\n", ip, interface, port);
 
711
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
712
                ip, interface, port);
737
713
      }
738
714
    } else {
739
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
740
 
                   ip, port);
 
715
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
716
              port);
741
717
    }
742
718
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
743
719
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
753
729
      perror_plus("inet_ntop");
754
730
    } else {
755
731
      if(strcmp(addrstr, ip) != 0){
756
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
732
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
757
733
      }
758
734
    }
759
735
  }
787
763
  while(true){
788
764
    size_t out_size = strlen(out);
789
765
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
790
 
                                        out_size - written));
 
766
                                   out_size - written));
791
767
    if(ret == -1){
792
768
      int e = errno;
793
769
      perror_plus("write");
813
789
  }
814
790
  
815
791
  if(debug){
816
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
792
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
817
793
  }
818
794
  
819
795
  if(quit_now){
821
797
    goto mandos_end;
822
798
  }
823
799
  
824
 
  /* This casting via intptr_t is to eliminate warning about casting
825
 
     an int to a pointer type.  This is exactly how the GnuTLS Guile
826
 
     function "set-session-transport-fd!" does it. */
827
 
  gnutls_transport_set_ptr(session,
828
 
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
 
800
  /* Spurious warning from -Wint-to-pointer-cast */
 
801
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
829
802
  
830
803
  if(quit_now){
831
804
    errno = EINTR;
842
815
  
843
816
  if(ret != GNUTLS_E_SUCCESS){
844
817
    if(debug){
845
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
818
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
846
819
      gnutls_perror(ret);
847
820
    }
848
821
    errno = EPROTO;
852
825
  /* Read OpenPGP packet that contains the wanted password */
853
826
  
854
827
  if(debug){
855
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
856
 
                 " %s\n", ip);
 
828
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
829
            ip);
857
830
  }
858
831
  
859
832
  while(true){
864
837
    }
865
838
    
866
839
    buffer_capacity = incbuffer(&buffer, buffer_length,
867
 
                                buffer_capacity);
 
840
                                   buffer_capacity);
868
841
    if(buffer_capacity == 0){
869
842
      int e = errno;
870
843
      perror_plus("incbuffer");
897
870
          }
898
871
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
899
872
        if(ret < 0){
900
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
901
 
                       "***\n");
 
873
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
902
874
          gnutls_perror(ret);
903
875
          errno = EPROTO;
904
876
          goto mandos_end;
905
877
        }
906
878
        break;
907
879
      default:
908
 
        fprintf_plus(stderr, "Unknown error while reading data from"
909
 
                     " encrypted session with Mandos server\n");
 
880
        fprintf(stderr, "Unknown error while reading data from"
 
881
                " encrypted session with Mandos server\n");
910
882
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
911
883
        errno = EIO;
912
884
        goto mandos_end;
917
889
  }
918
890
  
919
891
  if(debug){
920
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
892
    fprintf(stderr, "Closing TLS session\n");
921
893
  }
922
894
  
923
895
  if(quit_now){
935
907
  
936
908
  if(buffer_length > 0){
937
909
    ssize_t decrypted_buffer_size;
938
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
910
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
911
                                               buffer_length,
939
912
                                               &decrypted_buffer);
940
913
    if(decrypted_buffer_size >= 0){
941
914
      
952
925
        if(ret == 0 and ferror(stdout)){
953
926
          int e = errno;
954
927
          if(debug){
955
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
956
 
                         strerror(errno));
 
928
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
929
                    strerror(errno));
957
930
          }
958
931
          errno = e;
959
932
          goto mandos_end;
1016
989
  switch(event){
1017
990
  default:
1018
991
  case AVAHI_RESOLVER_FAILURE:
1019
 
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1020
 
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1021
 
                 domain,
1022
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
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)));
1023
995
    break;
1024
996
    
1025
997
  case AVAHI_RESOLVER_FOUND:
1027
999
      char ip[AVAHI_ADDRESS_STR_MAX];
1028
1000
      avahi_address_snprint(ip, sizeof(ip), address);
1029
1001
      if(debug){
1030
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1031
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1032
 
                     host_name, ip, (intmax_t)interface, port);
 
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);
1033
1005
      }
1034
1006
      int ret = start_mandos_communication(ip, port, interface,
1035
1007
                                           avahi_proto_to_af(proto));
1036
1008
      if(ret == 0){
1037
1009
        avahi_simple_poll_quit(mc.simple_poll);
1038
1010
      } else {
1039
 
        if(not add_server(ip, port, interface,
1040
 
                          avahi_proto_to_af(proto))){
1041
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1042
 
                       " list\n", name);
1043
 
        }
 
1011
        ret = add_server(ip, port, interface,
 
1012
                         avahi_proto_to_af(proto));
1044
1013
      }
1045
1014
    }
1046
1015
  }
1070
1039
  default:
1071
1040
  case AVAHI_BROWSER_FAILURE:
1072
1041
    
1073
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1074
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1042
    fprintf(stderr, "(Avahi browser) %s\n",
 
1043
            avahi_strerror(avahi_server_errno(mc.server)));
1075
1044
    avahi_simple_poll_quit(mc.simple_poll);
1076
1045
    return;
1077
1046
    
1084
1053
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1085
1054
                                    name, type, domain, protocol, 0,
1086
1055
                                    resolve_callback, NULL) == NULL)
1087
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1088
 
                   " %s\n", name,
1089
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1056
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1057
              name, avahi_strerror(avahi_server_errno(mc.server)));
1090
1058
    break;
1091
1059
    
1092
1060
  case AVAHI_BROWSER_REMOVE:
1095
1063
  case AVAHI_BROWSER_ALL_FOR_NOW:
1096
1064
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1097
1065
    if(debug){
1098
 
      fprintf_plus(stderr, "No Mandos server found, still"
1099
 
                   " searching...\n");
 
1066
      fprintf(stderr, "No Mandos server found, still searching...\n");
1100
1067
    }
1101
1068
    break;
1102
1069
  }
1117
1084
  errno = old_errno;
1118
1085
}
1119
1086
 
1120
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1121
 
  int ret;
1122
 
  
1123
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1124
 
  if(s < 0){
1125
 
    perror_plus("socket");
1126
 
    return false;
1127
 
  }
1128
 
  strcpy(ifr->ifr_name, ifname);
1129
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1130
 
  if(ret == -1){
 
1087
/* 
 
1088
 * This function determines if a directory entry in /sys/class/net
 
1089
 * corresponds to an acceptable network device.
 
1090
 * (This function is passed to scandir(3) as a filter function.)
 
1091
 */
 
1092
int good_interface(const struct dirent *if_entry){
 
1093
  ssize_t ssret;
 
1094
  char *flagname = NULL;
 
1095
  if(if_entry->d_name[0] == '.'){
 
1096
    return 0;
 
1097
  }
 
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){
1131
1143
    if(debug){
1132
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1144
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1145
              flagstring, if_entry->d_name);
1133
1146
    }
1134
 
    return false;
 
1147
    free(flagstring);
 
1148
    return 0;
1135
1149
  }
1136
 
  return true;
1137
 
}
1138
 
 
1139
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1140
 
  
 
1150
  free(flagstring);
 
1151
  ifreq_flags flags = (ifreq_flags)tmpmax;
1141
1152
  /* Reject the loopback device */
1142
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1153
  if(flags & IFF_LOOPBACK){
1143
1154
    if(debug){
1144
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1145
 
                   ifname);
 
1155
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1156
              if_entry->d_name);
1146
1157
    }
1147
 
    return false;
 
1158
    return 0;
1148
1159
  }
1149
1160
  /* Accept point-to-point devices only if connect_to is specified */
1150
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1161
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1151
1162
    if(debug){
1152
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1153
 
                   " \"%s\"\n", ifname);
 
1163
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1164
              if_entry->d_name);
1154
1165
    }
1155
 
    return true;
 
1166
    return 1;
1156
1167
  }
1157
1168
  /* Otherwise, reject non-broadcast-capable devices */
1158
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1169
  if(not (flags & IFF_BROADCAST)){
1159
1170
    if(debug){
1160
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1161
 
                   " \"%s\"\n", ifname);
 
1171
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1172
              if_entry->d_name);
1162
1173
    }
1163
 
    return false;
 
1174
    return 0;
1164
1175
  }
1165
1176
  /* Reject non-ARP interfaces (including dummy interfaces) */
1166
 
  if(ifr->ifr_flags & IFF_NOARP){
 
1177
  if(flags & IFF_NOARP){
1167
1178
    if(debug){
1168
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1169
 
                   ifname);
 
1179
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1180
              if_entry->d_name);
1170
1181
    }
1171
 
    return false;
 
1182
    return 0;
1172
1183
  }
1173
 
  
1174
1184
  /* Accept this device */
1175
1185
  if(debug){
1176
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1177
 
  }
1178
 
  return true;
1179
 
}
1180
 
 
1181
 
/* 
1182
 
 * This function determines if a directory entry in /sys/class/net
1183
 
 * corresponds to an acceptable network device.
1184
 
 * (This function is passed to scandir(3) as a filter function.)
1185
 
 */
1186
 
int good_interface(const struct dirent *if_entry){
1187
 
  if(if_entry->d_name[0] == '.'){
1188
 
    return 0;
1189
 
  }
1190
 
  
1191
 
  struct ifreq ifr;
1192
 
  if(not get_flags(if_entry->d_name, &ifr)){
1193
 
    if(debug){
1194
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1195
 
                   "\"%s\"\n", if_entry->d_name);
1196
 
    }
1197
 
    return 0;
1198
 
  }
1199
 
  
1200
 
  if(not good_flags(if_entry->d_name, &ifr)){
1201
 
    return 0;
1202
 
  }
1203
 
  return 1;
1204
 
}
1205
 
 
1206
 
/* 
1207
 
 * This function determines if a directory entry in /sys/class/net
1208
 
 * corresponds to an acceptable network device which is up.
1209
 
 * (This function is passed to scandir(3) as a filter function.)
1210
 
 */
1211
 
int up_interface(const struct dirent *if_entry){
1212
 
  if(if_entry->d_name[0] == '.'){
1213
 
    return 0;
1214
 
  }
1215
 
  
1216
 
  struct ifreq ifr;
1217
 
  if(not get_flags(if_entry->d_name, &ifr)){
1218
 
    if(debug){
1219
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1220
 
                   "\"%s\"\n", if_entry->d_name);
1221
 
    }
1222
 
    return 0;
1223
 
  }
1224
 
  
1225
 
  /* Reject down interfaces */
1226
 
  if(not (ifr.ifr_flags & IFF_UP)){
1227
 
    if(debug){
1228
 
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1229
 
                   if_entry->d_name);
1230
 
    }
1231
 
    return 0;
1232
 
  }
1233
 
  
1234
 
  /* Reject non-running interfaces */
1235
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1236
 
    if(debug){
1237
 
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1238
 
                   if_entry->d_name);
1239
 
    }
1240
 
    return 0;
1241
 
  }
1242
 
  
1243
 
  if(not good_flags(if_entry->d_name, &ifr)){
1244
 
    return 0;
 
1186
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1187
            if_entry->d_name);
1245
1188
  }
1246
1189
  return 1;
1247
1190
}
1257
1200
  return 1;
1258
1201
}
1259
1202
 
1260
 
/* Is this directory entry a runnable program? */
1261
 
int runnable_hook(const struct dirent *direntry){
1262
 
  int ret;
1263
 
  size_t sret;
1264
 
  struct stat st;
1265
 
  
1266
 
  if((direntry->d_name)[0] == '\0'){
1267
 
    /* Empty name? */
1268
 
    return 0;
1269
 
  }
1270
 
  
1271
 
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1272
 
                "abcdefghijklmnopqrstuvwxyz"
1273
 
                "0123456789"
1274
 
                "_-");
1275
 
  if((direntry->d_name)[sret] != '\0'){
1276
 
    /* Contains non-allowed characters */
1277
 
    if(debug){
1278
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1279
 
                   direntry->d_name);
1280
 
    }
1281
 
    return 0;
1282
 
  }
1283
 
  
1284
 
  char *fullname = NULL;
1285
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1286
 
  if(ret < 0){
1287
 
    perror_plus("asprintf");
1288
 
    return 0;
1289
 
  }
1290
 
  
1291
 
  ret = stat(fullname, &st);
1292
 
  if(ret == -1){
1293
 
    if(debug){
1294
 
      perror_plus("Could not stat hook");
1295
 
    }
1296
 
    return 0;
1297
 
  }
1298
 
  if(not (S_ISREG(st.st_mode))){
1299
 
    /* Not a regular file */
1300
 
    if(debug){
1301
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1302
 
                   direntry->d_name);
1303
 
    }
1304
 
    return 0;
1305
 
  }
1306
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1307
 
    /* Not executable */
1308
 
    if(debug){
1309
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1310
 
                   direntry->d_name);
1311
 
    }
1312
 
    return 0;
1313
 
  }
1314
 
  if(debug){
1315
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1316
 
                 direntry->d_name);
1317
 
  }
1318
 
  return 1;
1319
 
}
1320
 
 
1321
1203
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1322
1204
  int ret;
1323
1205
  struct timespec now;
1324
1206
  struct timespec waited_time;
1325
1207
  intmax_t block_time;
1326
 
  
 
1208
 
1327
1209
  while(true){
1328
1210
    if(mc.current_server == NULL){
1329
1211
      if (debug){
1330
 
        fprintf_plus(stderr, "Wait until first server is found."
1331
 
                     " No timeout!\n");
 
1212
        fprintf(stderr,
 
1213
                "Wait until first server is found. No timeout!\n");
1332
1214
      }
1333
1215
      ret = avahi_simple_poll_iterate(s, -1);
1334
1216
    } else {
1335
1217
      if (debug){
1336
 
        fprintf_plus(stderr, "Check current_server if we should run"
1337
 
                     " it, or wait\n");
 
1218
        fprintf(stderr, "Check current_server if we should run it,"
 
1219
                " or wait\n");
1338
1220
      }
1339
1221
      /* the current time */
1340
1222
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1354
1236
      block_time = ((retry_interval
1355
1237
                     - ((intmax_t)waited_time.tv_sec * 1000))
1356
1238
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1357
 
      
 
1239
 
1358
1240
      if (debug){
1359
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1360
 
                     block_time);
 
1241
        fprintf(stderr, "Blocking for %ld ms\n", block_time);
1361
1242
      }
1362
 
      
 
1243
 
1363
1244
      if(block_time <= 0){
1364
1245
        ret = start_mandos_communication(mc.current_server->ip,
1365
1246
                                         mc.current_server->port,
1383
1264
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1384
1265
    }
1385
1266
    if(ret != 0){
1386
 
      if (ret > 0 or errno != EINTR){
 
1267
      if (ret > 0 or errno != EINTR) {
1387
1268
        return (ret != 1) ? ret : 0;
1388
1269
      }
1389
1270
    }
1390
1271
  }
1391
1272
}
1392
1273
 
1393
 
bool run_network_hooks(const char *mode, const char *interface,
1394
 
                       const float delay){
1395
 
  struct dirent **direntries;
1396
 
  struct dirent *direntry;
1397
 
  int ret;
1398
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1399
 
                         alphasort);
1400
 
  if(numhooks == -1){
1401
 
    perror_plus("scandir");
1402
 
  } else {
1403
 
    int devnull = open("/dev/null", O_RDONLY);
1404
 
    for(int i = 0; i < numhooks; i++){
1405
 
      direntry = direntries[i];
1406
 
      char *fullname = NULL;
1407
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1408
 
      if(ret < 0){
1409
 
        perror_plus("asprintf");
1410
 
        continue;
1411
 
      }
1412
 
      if(debug){
1413
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1414
 
                     direntry->d_name);
1415
 
      }
1416
 
      pid_t hook_pid = fork();
1417
 
      if(hook_pid == 0){
1418
 
        /* Child */
1419
 
        /* Raise privileges */
1420
 
        errno = 0;
1421
 
        ret = seteuid(0);
1422
 
        if(ret == -1){
1423
 
          perror_plus("seteuid");
1424
 
        }
1425
 
        /* Raise privileges even more */
1426
 
        errno = 0;
1427
 
        ret = setuid(0);
1428
 
        if(ret == -1){
1429
 
          perror_plus("setuid");
1430
 
        }
1431
 
        /* Set group */
1432
 
        errno = 0;
1433
 
        ret = setgid(0);
1434
 
        if(ret == -1){
1435
 
          perror_plus("setgid");
1436
 
        }
1437
 
        /* Reset supplementary groups */
1438
 
        errno = 0;
1439
 
        ret = setgroups(0, NULL);
1440
 
        if(ret == -1){
1441
 
          perror_plus("setgroups");
1442
 
        }
1443
 
        dup2(devnull, STDIN_FILENO);
1444
 
        close(devnull);
1445
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1446
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1447
 
        if(ret == -1){
1448
 
          perror_plus("setenv");
1449
 
          _exit(EX_OSERR);
1450
 
        }
1451
 
        ret = setenv("DEVICE", interface, 1);
1452
 
        if(ret == -1){
1453
 
          perror_plus("setenv");
1454
 
          _exit(EX_OSERR);
1455
 
        }
1456
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1457
 
        if(ret == -1){
1458
 
          perror_plus("setenv");
1459
 
          _exit(EX_OSERR);
1460
 
        }
1461
 
        ret = setenv("MODE", mode, 1);
1462
 
        if(ret == -1){
1463
 
          perror_plus("setenv");
1464
 
          _exit(EX_OSERR);
1465
 
        }
1466
 
        char *delaystring;
1467
 
        ret = asprintf(&delaystring, "%f", delay);
1468
 
        if(ret == -1){
1469
 
          perror_plus("asprintf");
1470
 
          _exit(EX_OSERR);
1471
 
        }
1472
 
        ret = setenv("DELAY", delaystring, 1);
1473
 
        if(ret == -1){
1474
 
          free(delaystring);
1475
 
          perror_plus("setenv");
1476
 
          _exit(EX_OSERR);
1477
 
        }
1478
 
        free(delaystring);
1479
 
        if(connect_to != NULL){
1480
 
          ret = setenv("CONNECT", connect_to, 1);
1481
 
          if(ret == -1){
1482
 
            perror_plus("setenv");
1483
 
            _exit(EX_OSERR);
1484
 
          }
1485
 
        }
1486
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1487
 
          perror_plus("execl");
1488
 
          _exit(EXIT_FAILURE);
1489
 
        }
1490
 
      } else {
1491
 
        int status;
1492
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1493
 
          perror_plus("waitpid");
1494
 
          free(fullname);
1495
 
          continue;
1496
 
        }
1497
 
        if(WIFEXITED(status)){
1498
 
          if(WEXITSTATUS(status) != 0){
1499
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1500
 
                         " with status %d\n", direntry->d_name,
1501
 
                         WEXITSTATUS(status));
1502
 
            free(fullname);
1503
 
            continue;
1504
 
          }
1505
 
        } else if(WIFSIGNALED(status)){
1506
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1507
 
                       " signal %d\n", direntry->d_name,
1508
 
                       WTERMSIG(status));
1509
 
          free(fullname);
1510
 
          continue;
1511
 
        } else {
1512
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1513
 
                       " crashed\n", direntry->d_name);
1514
 
          free(fullname);
1515
 
          continue;
1516
 
        }
1517
 
      }
1518
 
      free(fullname);
1519
 
      if(debug){
1520
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1521
 
                     direntry->d_name);
1522
 
      }
1523
 
    }
1524
 
    close(devnull);
1525
 
  }
1526
 
  return true;
1527
 
}
1528
 
 
1529
1274
int main(int argc, char *argv[]){
1530
1275
  AvahiSServiceBrowser *sb = NULL;
1531
1276
  int error;
1611
1356
        .group = 2 },
1612
1357
      { .name = "retry", .key = 132,
1613
1358
        .arg = "SECONDS",
1614
 
        .doc = "Retry interval used when denied by the Mandos server",
1615
 
        .group = 2 },
1616
 
      { .name = "network-hook-dir", .key = 133,
1617
 
        .arg = "DIR",
1618
 
        .doc = "Directory where network hooks are located",
 
1359
        .doc = "Retry interval used when denied by the mandos server",
1619
1360
        .group = 2 },
1620
1361
      /*
1621
1362
       * These reproduce what we would get without ARGP_NO_HELP
1670
1411
        errno = 0;
1671
1412
        retry_interval = strtod(arg, &tmp);
1672
1413
        if(errno != 0 or tmp == arg or *tmp != '\0'
1673
 
           or (retry_interval * 1000) > INT_MAX
1674
 
           or retry_interval < 0){
 
1414
           or (retry_interval * 1000) > INT_MAX){
1675
1415
          argp_error(state, "Bad retry interval");
1676
1416
        }
1677
1417
        break;
1678
 
      case 133:                 /* --network-hook-dir */
1679
 
        hookdir = arg;
1680
 
        break;
1681
1418
        /*
1682
1419
         * These reproduce what we would get without ARGP_NO_HELP
1683
1420
         */
1689
1426
        argp_state_help(state, state->out_stream,
1690
1427
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1691
1428
      case 'V':                 /* --version */
1692
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1429
        fprintf(state->out_stream, "%s\n", argp_program_version);
1693
1430
        exit(argp_err_exit_status);
1694
1431
        break;
1695
1432
      default:
1718
1455
      goto end;
1719
1456
    }
1720
1457
  }
1721
 
    
1722
 
  {
1723
 
    /* Work around Debian bug #633582:
1724
 
       <http://bugs.debian.org/633582> */
1725
 
    
1726
 
    /* Re-raise priviliges */
1727
 
    errno = 0;
1728
 
    ret = seteuid(0);
1729
 
    if(ret == -1){
1730
 
      perror_plus("seteuid");
1731
 
    } else {
1732
 
      struct stat st;
1733
 
      
1734
 
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1735
 
        int seckey_fd = open(seckey, O_RDONLY);
1736
 
        if(seckey_fd == -1){
1737
 
          perror_plus("open");
1738
 
        } else {
1739
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1740
 
          if(ret == -1){
1741
 
            perror_plus("fstat");
1742
 
          } else {
1743
 
            if(S_ISREG(st.st_mode)
1744
 
               and st.st_uid == 0 and st.st_gid == 0){
1745
 
              ret = fchown(seckey_fd, uid, gid);
1746
 
              if(ret == -1){
1747
 
                perror_plus("fchown");
1748
 
              }
1749
 
            }
1750
 
          }
1751
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
1752
 
        }
1753
 
      }
1754
 
    
1755
 
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1756
 
        int pubkey_fd = open(pubkey, O_RDONLY);
1757
 
        if(pubkey_fd == -1){
1758
 
          perror_plus("open");
1759
 
        } else {
1760
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1761
 
          if(ret == -1){
1762
 
            perror_plus("fstat");
1763
 
          } else {
1764
 
            if(S_ISREG(st.st_mode)
1765
 
               and st.st_uid == 0 and st.st_gid == 0){
1766
 
              ret = fchown(pubkey_fd, uid, gid);
1767
 
              if(ret == -1){
1768
 
                perror_plus("fchown");
1769
 
              }
1770
 
            }
1771
 
          }
1772
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
1773
 
        }
1774
 
      }
1775
 
    
1776
 
      /* Lower privileges */
1777
 
      errno = 0;
1778
 
      ret = seteuid(uid);
1779
 
      if(ret == -1){
1780
 
        perror_plus("seteuid");
1781
 
      }
1782
 
    }
1783
 
  }
1784
 
  
1785
 
  /* Run network hooks */
1786
 
  if(not run_network_hooks("start", interface, delay)){
1787
 
    goto end;
1788
 
  }
1789
1458
  
1790
1459
  if(not debug){
1791
1460
    avahi_set_log_function(empty_log);
1792
1461
  }
1793
 
  
 
1462
 
1794
1463
  if(interface[0] == '\0'){
1795
1464
    struct dirent **direntries;
1796
 
    /* First look for interfaces that are up */
1797
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1465
    ret = scandir(sys_class_net, &direntries, good_interface,
1798
1466
                  alphasort);
1799
 
    if(ret == 0){
1800
 
      /* No up interfaces, look for any good interfaces */
1801
 
      free(direntries);
1802
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1803
 
                    alphasort);
1804
 
    }
1805
1467
    if(ret >= 1){
1806
 
      /* Pick the first interface returned */
 
1468
      /* Pick the first good interface */
1807
1469
      interface = strdup(direntries[0]->d_name);
1808
1470
      if(debug){
1809
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1471
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1810
1472
      }
1811
1473
      if(interface == NULL){
1812
1474
        perror_plus("malloc");
1817
1479
      free(direntries);
1818
1480
    } else {
1819
1481
      free(direntries);
1820
 
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1482
      fprintf(stderr, "Could not find a network interface\n");
1821
1483
      exitcode = EXIT_FAILURE;
1822
1484
      goto end;
1823
1485
    }
1829
1491
  srand((unsigned int) time(NULL));
1830
1492
  mc.simple_poll = avahi_simple_poll_new();
1831
1493
  if(mc.simple_poll == NULL){
1832
 
    fprintf_plus(stderr,
1833
 
                 "Avahi: Failed to create simple poll object.\n");
 
1494
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1834
1495
    exitcode = EX_UNAVAILABLE;
1835
1496
    goto end;
1836
1497
  }
1902
1563
  if(strcmp(interface, "none") != 0){
1903
1564
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1904
1565
    if(if_index == 0){
1905
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1566
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1906
1567
      exitcode = EX_UNAVAILABLE;
1907
1568
      goto end;
1908
1569
    }
2028
1689
#endif  /* __linux__ */
2029
1690
    /* Lower privileges */
2030
1691
    errno = 0;
2031
 
    /* Lower privileges */
2032
 
    ret = seteuid(uid);
2033
 
    if(ret == -1){
2034
 
      perror_plus("seteuid");
 
1692
    if(take_down_interface){
 
1693
      /* Lower privileges */
 
1694
      ret = seteuid(uid);
 
1695
      if(ret == -1){
 
1696
        perror_plus("seteuid");
 
1697
      }
 
1698
    } else {
 
1699
      /* Lower privileges permanently */
 
1700
      ret = setuid(uid);
 
1701
      if(ret == -1){
 
1702
        perror_plus("setuid");
 
1703
      }
2035
1704
    }
2036
1705
  }
2037
1706
  
2041
1710
  
2042
1711
  ret = init_gnutls_global(pubkey, seckey);
2043
1712
  if(ret == -1){
2044
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1713
    fprintf(stderr, "init_gnutls_global failed\n");
2045
1714
    exitcode = EX_UNAVAILABLE;
2046
1715
    goto end;
2047
1716
  } else {
2063
1732
  }
2064
1733
  
2065
1734
  if(not init_gpgme(pubkey, seckey, tempdir)){
2066
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1735
    fprintf(stderr, "init_gpgme failed\n");
2067
1736
    exitcode = EX_UNAVAILABLE;
2068
1737
    goto end;
2069
1738
  } else {
2079
1748
    /* (Mainly meant for debugging) */
2080
1749
    char *address = strrchr(connect_to, ':');
2081
1750
    if(address == NULL){
2082
 
      fprintf_plus(stderr, "No colon in address\n");
 
1751
      fprintf(stderr, "No colon in address\n");
2083
1752
      exitcode = EX_USAGE;
2084
1753
      goto end;
2085
1754
    }
2093
1762
    tmpmax = strtoimax(address+1, &tmp, 10);
2094
1763
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2095
1764
       or tmpmax != (uint16_t)tmpmax){
2096
 
      fprintf_plus(stderr, "Bad port number\n");
 
1765
      fprintf(stderr, "Bad port number\n");
2097
1766
      exitcode = EX_USAGE;
2098
1767
      goto end;
2099
1768
    }
2104
1773
    
2105
1774
    port = (uint16_t)tmpmax;
2106
1775
    *address = '\0';
 
1776
    address = connect_to;
2107
1777
    /* Colon in address indicates IPv6 */
2108
1778
    int af;
2109
 
    if(strchr(connect_to, ':') != NULL){
 
1779
    if(strchr(address, ':') != NULL){
2110
1780
      af = AF_INET6;
2111
 
      /* Accept [] around IPv6 address - see RFC 5952 */
2112
 
      if(connect_to[0] == '[' and address[-1] == ']')
2113
 
        {
2114
 
          connect_to++;
2115
 
          address[-1] = '\0';
2116
 
        }
2117
1781
    } else {
2118
1782
      af = AF_INET;
2119
1783
    }
2120
 
    address = connect_to;
2121
1784
    
2122
1785
    if(quit_now){
2123
1786
      goto end;
2124
1787
    }
2125
 
    
 
1788
 
2126
1789
    while(not quit_now){
2127
1790
      ret = start_mandos_communication(address, port, if_index, af);
2128
1791
      if(quit_now or ret == 0){
2129
1792
        break;
2130
1793
      }
2131
 
      if(debug){
2132
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2133
 
                     (int)retry_interval);
2134
 
      }
2135
 
      sleep((int)retry_interval);
2136
 
    }
2137
 
    
 
1794
      sleep((int)retry_interval or 1);
 
1795
    };
 
1796
 
2138
1797
    if (not quit_now){
2139
1798
      exitcode = EXIT_SUCCESS;
2140
1799
    }
2141
 
    
 
1800
 
2142
1801
    goto end;
2143
1802
  }
2144
1803
  
2166
1825
  
2167
1826
  /* Check if creating the Avahi server object succeeded */
2168
1827
  if(mc.server == NULL){
2169
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2170
 
                 avahi_strerror(error));
 
1828
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1829
            avahi_strerror(error));
2171
1830
    exitcode = EX_UNAVAILABLE;
2172
1831
    goto end;
2173
1832
  }
2181
1840
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2182
1841
                                   NULL, 0, browse_callback, NULL);
2183
1842
  if(sb == NULL){
2184
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2185
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1843
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1844
            avahi_strerror(avahi_server_errno(mc.server)));
2186
1845
    exitcode = EX_UNAVAILABLE;
2187
1846
    goto end;
2188
1847
  }
2194
1853
  /* Run the main loop */
2195
1854
  
2196
1855
  if(debug){
2197
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
1856
    fprintf(stderr, "Starting Avahi loop search\n");
2198
1857
  }
2199
1858
 
2200
1859
  ret = avahi_loop_with_timeout(mc.simple_poll,
2201
1860
                                (int)(retry_interval * 1000));
2202
1861
  if(debug){
2203
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2204
 
                 (ret == 0) ? "successfully" : "with error");
 
1862
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1863
            (ret == 0) ? "successfully" : "with error");
2205
1864
  }
2206
1865
  
2207
1866
 end:
2208
1867
  
2209
1868
  if(debug){
2210
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
1869
    fprintf(stderr, "%s exiting\n", argv[0]);
2211
1870
  }
2212
1871
  
2213
1872
  /* Cleanup things */
2229
1888
  if(gpgme_initialized){
2230
1889
    gpgme_release(mc.ctx);
2231
1890
  }
2232
 
  
 
1891
 
2233
1892
  /* Cleans up the circular linked list of Mandos servers the client
2234
1893
     has seen */
2235
1894
  if(mc.current_server != NULL){
2241
1900
    }
2242
1901
  }
2243
1902
  
2244
 
  /* Run network hooks */
2245
 
  run_network_hooks("stop", interface, delay);
2246
 
  
2247
 
  /* Re-raise priviliges */
2248
 
  {
 
1903
  /* Take down the network interface */
 
1904
  if(take_down_interface){
 
1905
    /* Re-raise priviliges */
2249
1906
    errno = 0;
2250
1907
    ret = seteuid(0);
2251
1908
    if(ret == -1){
2252
1909
      perror_plus("seteuid");
2253
1910
    }
2254
 
    
2255
 
    /* Take down the network interface */
2256
 
    if(take_down_interface and geteuid() == 0){
 
1911
    if(geteuid() == 0){
2257
1912
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2258
1913
      if(ret == -1){
2259
1914
        perror_plus("ioctl SIOCGIFFLAGS");
2260
 
      } else if(network.ifr_flags & IFF_UP){
 
1915
      } else if(network.ifr_flags & IFF_UP) {
2261
1916
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2262
1917
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2263
1918
        if(ret == -1){
2268
1923
      if(ret == -1){
2269
1924
        perror_plus("close");
2270
1925
      }
 
1926
      /* Lower privileges permanently */
 
1927
      errno = 0;
 
1928
      ret = setuid(uid);
 
1929
      if(ret == -1){
 
1930
        perror_plus("setuid");
 
1931
      }
2271
1932
    }
2272
1933
  }
2273
 
  /* Lower privileges permanently */
2274
 
  errno = 0;
2275
 
  ret = setuid(uid);
2276
 
  if(ret == -1){
2277
 
    perror_plus("setuid");
2278
 
  }
2279
1934
  
2280
1935
  /* Removes the GPGME temp directory and all files inside */
2281
1936
  if(tempdir_created){
2282
1937
    struct dirent **direntries = NULL;
2283
1938
    struct dirent *direntry = NULL;
2284
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2285
 
                             alphasort);
2286
 
    if (numentries > 0){
2287
 
      for(int i = 0; i < numentries; i++){
 
1939
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
 
1940
    if (ret > 0){
 
1941
      for(int i = 0; i < ret; i++){
2288
1942
        direntry = direntries[i];
2289
1943
        char *fullname = NULL;
2290
1944
        ret = asprintf(&fullname, "%s/%s", tempdir,
2295
1949
        }
2296
1950
        ret = remove(fullname);
2297
1951
        if(ret == -1){
2298
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2299
 
                       strerror(errno));
 
1952
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1953
                  strerror(errno));
2300
1954
        }
2301
1955
        free(fullname);
2302
1956
      }
2303
1957
    }
2304
1958
 
2305
 
    /* need to clean even if 0 because man page doesn't specify */
 
1959
    /* need to be cleaned even if ret == 0 because man page doesn't
 
1960
       specify */
2306
1961
    free(direntries);
2307
 
    if (numentries == -1){
 
1962
    if (ret == -1){
2308
1963
      perror_plus("scandir");
2309
1964
    }
2310
1965
    ret = rmdir(tempdir);