/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2012-06-01 21:48:12 UTC
  • Revision ID: teddy@recompile.se-20120601214812-g7685v5oeiuhi2qw
* debian/copyright (Copyright): Join the two lines to one line.
* debian/mandos-client.README.Debian: Refer to new location of example
  network hooks.
* debian/mandos-client.docs (network-hooks.d): Removed.
* debian/mandos-client.examples: New; contains "network-hooks.d".
* debian/rules (binary-common): Added "dh_installexamples".
  (binary-common/dh_fixperms): Changed to exclude new location of
  "network-hooks.d".
* init.d-mandos (status): Support new "status" action.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008-2012 Teddy Hogeborn
 
13
 * Copyright © 2008-2012 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
 
76
                                   setgid(), pause(), _exit() */
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
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
89
                                   WEXITSTATUS(), WTERMSIG() */
 
90
#include <grp.h>                /* setgroups() */
90
91
 
91
92
#ifdef __linux__
92
93
#include <sys/klog.h>           /* klogctl() */
169
170
 
170
171
/* Function to use when printing errors */
171
172
void perror_plus(const char *print_text){
 
173
  int e = errno;
172
174
  fprintf(stderr, "Mandos plugin %s: ",
173
175
          program_invocation_short_name);
 
176
  errno = e;
174
177
  perror(print_text);
175
178
}
176
179
 
 
180
__attribute__((format (gnu_printf, 2, 3)))
177
181
int fprintf_plus(FILE *stream, const char *format, ...){
178
182
  va_list ap;
179
183
  va_start (ap, format);
180
184
  
181
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", program_invocation_short_name));
 
185
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
186
                             program_invocation_short_name));
182
187
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
183
188
}
184
189
 
200
205
}
201
206
 
202
207
/* Add server to set of servers to retry periodically */
203
 
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
204
 
               int af){
 
208
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
209
                int af){
205
210
  int ret;
206
211
  server *new_server = malloc(sizeof(server));
207
212
  if(new_server == NULL){
208
213
    perror_plus("malloc");
209
 
    return -1;
 
214
    return false;
210
215
  }
211
216
  *new_server = (server){ .ip = strdup(ip),
212
217
                          .port = port,
214
219
                          .af = af };
215
220
  if(new_server->ip == NULL){
216
221
    perror_plus("strdup");
217
 
    return -1;
 
222
    return false;
218
223
  }
219
224
  /* Special case of first server */
220
225
  if (mc.current_server == NULL){
231
236
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
232
237
  if(ret == -1){
233
238
    perror_plus("clock_gettime");
234
 
    return -1;
 
239
    return false;
235
240
  }
236
 
  return 0;
 
241
  return true;
237
242
}
238
243
 
239
244
/* 
261
266
    
262
267
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
263
268
    if(rc != GPG_ERR_NO_ERROR){
264
 
      fprintf(stderr, "Mandos plugin mandos-client: "
265
 
              "bad gpgme_data_new_from_fd: %s: %s\n",
266
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
269
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
270
                   gpgme_strsource(rc), gpgme_strerror(rc));
267
271
      return false;
268
272
    }
269
273
    
270
274
    rc = gpgme_op_import(mc.ctx, pgp_data);
271
275
    if(rc != GPG_ERR_NO_ERROR){
272
 
      fprintf(stderr, "Mandos plugin mandos-client: "
273
 
              "bad gpgme_op_import: %s: %s\n",
274
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
276
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
277
                   gpgme_strsource(rc), gpgme_strerror(rc));
275
278
      return false;
276
279
    }
277
280
    
284
287
  }
285
288
  
286
289
  if(debug){
287
 
    fprintf(stderr, "Mandos plugin mandos-client: "
288
 
            "Initializing GPGME\n");
 
290
    fprintf_plus(stderr, "Initializing GPGME\n");
289
291
  }
290
292
  
291
293
  /* Init GPGME */
292
294
  gpgme_check_version(NULL);
293
295
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
294
296
  if(rc != GPG_ERR_NO_ERROR){
295
 
    fprintf(stderr, "Mandos plugin mandos-client: "
296
 
            "bad gpgme_engine_check_version: %s: %s\n",
297
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
297
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
298
                 gpgme_strsource(rc), gpgme_strerror(rc));
298
299
    return false;
299
300
  }
300
301
  
301
302
  /* Set GPGME home directory for the OpenPGP engine only */
302
303
  rc = gpgme_get_engine_info(&engine_info);
303
304
  if(rc != GPG_ERR_NO_ERROR){
304
 
    fprintf(stderr, "Mandos plugin mandos-client: "
305
 
            "bad gpgme_get_engine_info: %s: %s\n",
306
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
305
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
306
                 gpgme_strsource(rc), gpgme_strerror(rc));
307
307
    return false;
308
308
  }
309
309
  while(engine_info != NULL){
315
315
    engine_info = engine_info->next;
316
316
  }
317
317
  if(engine_info == NULL){
318
 
    fprintf(stderr, "Mandos plugin mandos-client: "
319
 
            "Could not set GPGME home dir to %s\n", tempdir);
 
318
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
319
                 tempdir);
320
320
    return false;
321
321
  }
322
322
  
323
323
  /* Create new GPGME "context" */
324
324
  rc = gpgme_new(&(mc.ctx));
325
325
  if(rc != GPG_ERR_NO_ERROR){
326
 
    fprintf(stderr, "Mandos plugin mandos-client: "
327
 
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
328
 
            gpgme_strerror(rc));
 
326
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
327
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
328
                 gpgme_strerror(rc));
329
329
    return false;
330
330
  }
331
331
  
350
350
  ssize_t plaintext_length = 0;
351
351
  
352
352
  if(debug){
353
 
    fprintf(stderr, "Mandos plugin mandos-client: "
354
 
            "Trying to decrypt OpenPGP data\n");
 
353
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
355
354
  }
356
355
  
357
356
  /* Create new GPGME data buffer from memory cryptotext */
358
357
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
359
358
                               0);
360
359
  if(rc != GPG_ERR_NO_ERROR){
361
 
    fprintf(stderr, "Mandos plugin mandos-client: "
362
 
            "bad gpgme_data_new_from_mem: %s: %s\n",
363
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
360
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
361
                 gpgme_strsource(rc), gpgme_strerror(rc));
364
362
    return -1;
365
363
  }
366
364
  
367
365
  /* Create new empty GPGME data buffer for the plaintext */
368
366
  rc = gpgme_data_new(&dh_plain);
369
367
  if(rc != GPG_ERR_NO_ERROR){
370
 
    fprintf(stderr, "Mandos plugin mandos-client: "
371
 
            "bad gpgme_data_new: %s: %s\n",
372
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
368
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
369
                 "bad gpgme_data_new: %s: %s\n",
 
370
                 gpgme_strsource(rc), gpgme_strerror(rc));
373
371
    gpgme_data_release(dh_crypto);
374
372
    return -1;
375
373
  }
378
376
     data buffer */
379
377
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
380
378
  if(rc != GPG_ERR_NO_ERROR){
381
 
    fprintf(stderr, "Mandos plugin mandos-client: "
382
 
            "bad gpgme_op_decrypt: %s: %s\n",
383
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
379
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
380
                 gpgme_strsource(rc), gpgme_strerror(rc));
384
381
    plaintext_length = -1;
385
382
    if(debug){
386
383
      gpgme_decrypt_result_t result;
387
384
      result = gpgme_op_decrypt_result(mc.ctx);
388
385
      if(result == NULL){
389
 
        fprintf(stderr, "Mandos plugin mandos-client: "
390
 
                "gpgme_op_decrypt_result failed\n");
 
386
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
391
387
      } else {
392
 
        fprintf(stderr, "Mandos plugin mandos-client: "
393
 
                "Unsupported algorithm: %s\n",
394
 
                result->unsupported_algorithm);
395
 
        fprintf(stderr, "Mandos plugin mandos-client: "
396
 
                "Wrong key usage: %u\n",
397
 
                result->wrong_key_usage);
 
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);
398
392
        if(result->file_name != NULL){
399
 
          fprintf(stderr, "Mandos plugin mandos-client: "
400
 
                  "File name: %s\n", result->file_name);
 
393
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
401
394
        }
402
395
        gpgme_recipient_t recipient;
403
396
        recipient = result->recipients;
404
397
        while(recipient != NULL){
405
 
          fprintf(stderr, "Mandos plugin mandos-client: "
406
 
                  "Public key algorithm: %s\n",
407
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
408
 
          fprintf(stderr, "Mandos plugin mandos-client: "
409
 
                  "Key ID: %s\n", recipient->keyid);
410
 
          fprintf(stderr, "Mandos plugin mandos-client: "
411
 
                  "Secret key available: %s\n",
412
 
                  recipient->status == GPG_ERR_NO_SECKEY
413
 
                  ? "No" : "Yes");
 
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");
414
405
          recipient = recipient->next;
415
406
        }
416
407
      }
419
410
  }
420
411
  
421
412
  if(debug){
422
 
    fprintf(stderr, "Mandos plugin mandos-client: "
423
 
            "Decryption of OpenPGP data succeeded\n");
 
413
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
424
414
  }
425
415
  
426
416
  /* Seek back to the beginning of the GPGME plaintext data buffer */
457
447
  }
458
448
  
459
449
  if(debug){
460
 
    fprintf(stderr, "Mandos plugin mandos-client: "
461
 
            "Decrypted password is: ");
 
450
    fprintf_plus(stderr, "Decrypted password is: ");
462
451
    for(ssize_t i = 0; i < plaintext_length; i++){
463
452
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
464
453
    }
486
475
/* GnuTLS log function callback */
487
476
static void debuggnutls(__attribute__((unused)) int level,
488
477
                        const char* string){
489
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
478
  fprintf_plus(stderr, "GnuTLS: %s", string);
490
479
}
491
480
 
492
481
static int init_gnutls_global(const char *pubkeyfilename,
494
483
  int ret;
495
484
  
496
485
  if(debug){
497
 
    fprintf(stderr, "Mandos plugin mandos-client: "
498
 
            "Initializing GnuTLS\n");
 
486
    fprintf_plus(stderr, "Initializing GnuTLS\n");
499
487
  }
500
488
  
501
489
  ret = gnutls_global_init();
502
490
  if(ret != GNUTLS_E_SUCCESS){
503
 
    fprintf(stderr, "Mandos plugin mandos-client: "
504
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
491
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
492
                 safer_gnutls_strerror(ret));
505
493
    return -1;
506
494
  }
507
495
  
516
504
  /* OpenPGP credentials */
517
505
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
518
506
  if(ret != GNUTLS_E_SUCCESS){
519
 
    fprintf(stderr, "Mandos plugin mandos-client: "
520
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
507
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
508
                 safer_gnutls_strerror(ret));
521
509
    gnutls_global_deinit();
522
510
    return -1;
523
511
  }
524
512
  
525
513
  if(debug){
526
 
    fprintf(stderr, "Mandos plugin mandos-client: "
527
 
            "Attempting to use OpenPGP public key %s and"
528
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
529
 
            seckeyfilename);
 
514
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
515
                 " secret key %s as GnuTLS credentials\n",
 
516
                 pubkeyfilename,
 
517
                 seckeyfilename);
530
518
  }
531
519
  
532
520
  ret = gnutls_certificate_set_openpgp_key_file
533
521
    (mc.cred, pubkeyfilename, seckeyfilename,
534
522
     GNUTLS_OPENPGP_FMT_BASE64);
535
523
  if(ret != GNUTLS_E_SUCCESS){
536
 
    fprintf(stderr,
537
 
            "Mandos plugin mandos-client: "
538
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
539
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
540
 
    fprintf(stderr, "Mandos plugin mandos-client: "
541
 
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
 
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));
542
529
    goto globalfail;
543
530
  }
544
531
  
545
532
  /* GnuTLS server initialization */
546
533
  ret = gnutls_dh_params_init(&mc.dh_params);
547
534
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf(stderr, "Mandos plugin mandos-client: "
549
 
            "Error in GnuTLS DH parameter initialization:"
550
 
            " %s\n", safer_gnutls_strerror(ret));
 
535
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
536
                 " initialization: %s\n",
 
537
                 safer_gnutls_strerror(ret));
551
538
    goto globalfail;
552
539
  }
553
540
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
554
541
  if(ret != GNUTLS_E_SUCCESS){
555
 
    fprintf(stderr, "Mandos plugin mandos-client: "
556
 
            "Error in GnuTLS prime generation: %s\n",
557
 
            safer_gnutls_strerror(ret));
 
542
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
543
                 safer_gnutls_strerror(ret));
558
544
    goto globalfail;
559
545
  }
560
546
  
580
566
    }
581
567
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
582
568
  if(ret != GNUTLS_E_SUCCESS){
583
 
    fprintf(stderr, "Mandos plugin mandos-client: "
584
 
            "Error in GnuTLS session initialization: %s\n",
585
 
            safer_gnutls_strerror(ret));
 
569
    fprintf_plus(stderr,
 
570
                 "Error in GnuTLS session initialization: %s\n",
 
571
                 safer_gnutls_strerror(ret));
586
572
  }
587
573
  
588
574
  {
595
581
      }
596
582
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
597
583
    if(ret != GNUTLS_E_SUCCESS){
598
 
      fprintf(stderr, "Mandos plugin mandos-client: "
599
 
              "Syntax error at: %s\n", err);
600
 
      fprintf(stderr, "Mandos plugin mandos-client: "
601
 
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
 
584
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
585
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
586
                   safer_gnutls_strerror(ret));
602
587
      gnutls_deinit(*session);
603
588
      return -1;
604
589
    }
613
598
    }
614
599
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
615
600
  if(ret != GNUTLS_E_SUCCESS){
616
 
    fprintf(stderr, "Mandos plugin mandos-client: "
617
 
            "Error setting GnuTLS credentials: %s\n",
618
 
            safer_gnutls_strerror(ret));
 
601
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
602
                 safer_gnutls_strerror(ret));
619
603
    gnutls_deinit(*session);
620
604
    return -1;
621
605
  }
666
650
    pf = PF_INET;
667
651
    break;
668
652
  default:
669
 
    fprintf(stderr, "Mandos plugin mandos-client: "
670
 
            "Bad address family: %d\n", af);
 
653
    fprintf_plus(stderr, "Bad address family: %d\n", af);
671
654
    errno = EINVAL;
672
655
    return -1;
673
656
  }
678
661
  }
679
662
  
680
663
  if(debug){
681
 
    fprintf(stderr, "Mandos plugin mandos-client: "
682
 
            "Setting up a TCP connection to %s, port %" PRIu16
683
 
            "\n", ip, port);
 
664
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
665
                 PRIu16 "\n", ip, port);
684
666
  }
685
667
  
686
668
  tcp_sd = socket(pf, SOCK_STREAM, 0);
712
694
  }
713
695
  if(ret == 0){
714
696
    int e = errno;
715
 
    fprintf(stderr, "Mandos plugin mandos-client: "
716
 
            "Bad address: %s\n", ip);
 
697
    fprintf_plus(stderr, "Bad address: %s\n", ip);
717
698
    errno = e;
718
699
    goto mandos_end;
719
700
  }
726
707
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
727
708
                                -Wunreachable-code*/
728
709
      if(if_index == AVAHI_IF_UNSPEC){
729
 
        fprintf(stderr, "Mandos plugin mandos-client: "
730
 
                "An IPv6 link-local address is incomplete"
731
 
                " without a network interface\n");
 
710
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
711
                     " incomplete without a network interface\n");
732
712
        errno = EINVAL;
733
713
        goto mandos_end;
734
714
      }
752
732
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
753
733
        perror_plus("if_indextoname");
754
734
      } else {
755
 
        fprintf(stderr, "Mandos plugin mandos-client: "
756
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
757
 
                ip, interface, port);
 
735
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
736
                     "\n", ip, interface, port);
758
737
      }
759
738
    } else {
760
 
      fprintf(stderr, "Mandos plugin mandos-client: "
761
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
739
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
740
                   ip, port);
762
741
    }
763
742
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
764
743
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
774
753
      perror_plus("inet_ntop");
775
754
    } else {
776
755
      if(strcmp(addrstr, ip) != 0){
777
 
        fprintf(stderr, "Mandos plugin mandos-client: "
778
 
                "Canonical address form: %s\n", addrstr);
 
756
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
779
757
      }
780
758
    }
781
759
  }
835
813
  }
836
814
  
837
815
  if(debug){
838
 
    fprintf(stderr, "Mandos plugin mandos-client: "
839
 
            "Establishing TLS session with %s\n", ip);
 
816
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
840
817
  }
841
818
  
842
819
  if(quit_now){
844
821
    goto mandos_end;
845
822
  }
846
823
  
847
 
  /* Spurious warning from -Wint-to-pointer-cast */
848
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
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);
849
829
  
850
830
  if(quit_now){
851
831
    errno = EINTR;
862
842
  
863
843
  if(ret != GNUTLS_E_SUCCESS){
864
844
    if(debug){
865
 
      fprintf(stderr, "Mandos plugin mandos-client: "
866
 
              "*** GnuTLS Handshake failed ***\n");
 
845
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
867
846
      gnutls_perror(ret);
868
847
    }
869
848
    errno = EPROTO;
873
852
  /* Read OpenPGP packet that contains the wanted password */
874
853
  
875
854
  if(debug){
876
 
    fprintf(stderr, "Mandos plugin mandos-client: "
877
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
855
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
856
                 " %s\n", ip);
878
857
  }
879
858
  
880
859
  while(true){
918
897
          }
919
898
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
920
899
        if(ret < 0){
921
 
          fprintf(stderr, "Mandos plugin mandos-client: "
922
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
900
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
901
                       "***\n");
923
902
          gnutls_perror(ret);
924
903
          errno = EPROTO;
925
904
          goto mandos_end;
926
905
        }
927
906
        break;
928
907
      default:
929
 
        fprintf(stderr, "Mandos plugin mandos-client: "
930
 
                "Unknown error while reading data from"
931
 
                " encrypted session with Mandos server\n");
 
908
        fprintf_plus(stderr, "Unknown error while reading data from"
 
909
                     " encrypted session with Mandos server\n");
932
910
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
933
911
        errno = EIO;
934
912
        goto mandos_end;
939
917
  }
940
918
  
941
919
  if(debug){
942
 
    fprintf(stderr, "Mandos plugin mandos-client: "
943
 
            "Closing TLS session\n");
 
920
    fprintf_plus(stderr, "Closing TLS session\n");
944
921
  }
945
922
  
946
923
  if(quit_now){
975
952
        if(ret == 0 and ferror(stdout)){
976
953
          int e = errno;
977
954
          if(debug){
978
 
            fprintf(stderr, "Mandos plugin mandos-client: "
979
 
                    "Error writing encrypted data: %s\n",
980
 
                    strerror(errno));
 
955
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
956
                         strerror(errno));
981
957
          }
982
958
          errno = e;
983
959
          goto mandos_end;
1040
1016
  switch(event){
1041
1017
  default:
1042
1018
  case AVAHI_RESOLVER_FAILURE:
1043
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1044
 
            "(Avahi Resolver) Failed to resolve service '%s'"
1045
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1046
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
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)));
1047
1023
    break;
1048
1024
    
1049
1025
  case AVAHI_RESOLVER_FOUND:
1051
1027
      char ip[AVAHI_ADDRESS_STR_MAX];
1052
1028
      avahi_address_snprint(ip, sizeof(ip), address);
1053
1029
      if(debug){
1054
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1055
 
                "Mandos server \"%s\" found on %s (%s, %"
1056
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1057
 
                ip, (intmax_t)interface, port);
 
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);
1058
1033
      }
1059
1034
      int ret = start_mandos_communication(ip, port, interface,
1060
1035
                                           avahi_proto_to_af(proto));
1061
1036
      if(ret == 0){
1062
1037
        avahi_simple_poll_quit(mc.simple_poll);
1063
1038
      } else {
1064
 
        ret = add_server(ip, port, interface,
1065
 
                         avahi_proto_to_af(proto));
 
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
        }
1066
1044
      }
1067
1045
    }
1068
1046
  }
1092
1070
  default:
1093
1071
  case AVAHI_BROWSER_FAILURE:
1094
1072
    
1095
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1096
 
            "(Avahi browser) %s\n",
1097
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1073
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1074
                 avahi_strerror(avahi_server_errno(mc.server)));
1098
1075
    avahi_simple_poll_quit(mc.simple_poll);
1099
1076
    return;
1100
1077
    
1107
1084
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1108
1085
                                    name, type, domain, protocol, 0,
1109
1086
                                    resolve_callback, NULL) == NULL)
1110
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1111
 
              "Avahi: Failed to resolve service '%s': %s\n",
1112
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1087
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1088
                   " %s\n", name,
 
1089
                   avahi_strerror(avahi_server_errno(mc.server)));
1113
1090
    break;
1114
1091
    
1115
1092
  case AVAHI_BROWSER_REMOVE:
1118
1095
  case AVAHI_BROWSER_ALL_FOR_NOW:
1119
1096
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1120
1097
    if(debug){
1121
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1122
 
              "No Mandos server found, still searching...\n");
 
1098
      fprintf_plus(stderr, "No Mandos server found, still"
 
1099
                   " searching...\n");
1123
1100
    }
1124
1101
    break;
1125
1102
  }
1164
1141
  /* Reject the loopback device */
1165
1142
  if(ifr->ifr_flags & IFF_LOOPBACK){
1166
1143
    if(debug){
1167
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1168
 
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1144
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1145
                   ifname);
1169
1146
    }
1170
1147
    return false;
1171
1148
  }
1172
1149
  /* Accept point-to-point devices only if connect_to is specified */
1173
1150
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1174
1151
    if(debug){
1175
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1176
 
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1152
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1153
                   " \"%s\"\n", ifname);
1177
1154
    }
1178
1155
    return true;
1179
1156
  }
1180
1157
  /* Otherwise, reject non-broadcast-capable devices */
1181
1158
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1182
1159
    if(debug){
1183
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1184
 
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1160
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1161
                   " \"%s\"\n", ifname);
1185
1162
    }
1186
1163
    return false;
1187
1164
  }
1188
1165
  /* Reject non-ARP interfaces (including dummy interfaces) */
1189
1166
  if(ifr->ifr_flags & IFF_NOARP){
1190
1167
    if(debug){
1191
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1192
 
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1168
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1169
                   ifname);
1193
1170
    }
1194
1171
    return false;
1195
1172
  }
1196
1173
  
1197
1174
  /* Accept this device */
1198
1175
  if(debug){
1199
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1200
 
            "Interface \"%s\" is good\n", ifname);
 
1176
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1201
1177
  }
1202
1178
  return true;
1203
1179
}
1215
1191
  struct ifreq ifr;
1216
1192
  if(not get_flags(if_entry->d_name, &ifr)){
1217
1193
    if(debug){
1218
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1219
 
              "Failed to get flags for interface \"%s\"\n",
1220
 
              if_entry->d_name);
 
1194
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1195
                   "\"%s\"\n", if_entry->d_name);
1221
1196
    }
1222
1197
    return 0;
1223
1198
  }
1241
1216
  struct ifreq ifr;
1242
1217
  if(not get_flags(if_entry->d_name, &ifr)){
1243
1218
    if(debug){
1244
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1245
 
              "Failed to get flags for interface \"%s\"\n",
1246
 
              if_entry->d_name);
 
1219
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1220
                   "\"%s\"\n", if_entry->d_name);
1247
1221
    }
1248
1222
    return 0;
1249
1223
  }
1251
1225
  /* Reject down interfaces */
1252
1226
  if(not (ifr.ifr_flags & IFF_UP)){
1253
1227
    if(debug){
1254
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1255
 
              "Rejecting down interface \"%s\"\n",
1256
 
              if_entry->d_name);
 
1228
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1229
                   if_entry->d_name);
1257
1230
    }
1258
1231
    return 0;
1259
1232
  }
1261
1234
  /* Reject non-running interfaces */
1262
1235
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1263
1236
    if(debug){
1264
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1265
 
              "Rejecting non-running interface \"%s\"\n",
1266
 
              if_entry->d_name);
 
1237
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1238
                   if_entry->d_name);
1267
1239
    }
1268
1240
    return 0;
1269
1241
  }
1303
1275
  if((direntry->d_name)[sret] != '\0'){
1304
1276
    /* Contains non-allowed characters */
1305
1277
    if(debug){
1306
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1307
 
              "Ignoring hook \"%s\" with bad name\n",
1308
 
              direntry->d_name);
 
1278
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1279
                   direntry->d_name);
1309
1280
    }
1310
1281
    return 0;
1311
1282
  }
1327
1298
  if(not (S_ISREG(st.st_mode))){
1328
1299
    /* Not a regular file */
1329
1300
    if(debug){
1330
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1331
 
              "Ignoring hook \"%s\" - not a file\n",
1332
 
              direntry->d_name);
 
1301
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1302
                   direntry->d_name);
1333
1303
    }
1334
1304
    return 0;
1335
1305
  }
1336
1306
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1337
1307
    /* Not executable */
1338
1308
    if(debug){
1339
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1340
 
              "Ignoring hook \"%s\" - not executable\n",
1341
 
              direntry->d_name);
 
1309
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1310
                   direntry->d_name);
1342
1311
    }
1343
1312
    return 0;
1344
1313
  }
 
1314
  if(debug){
 
1315
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1316
                 direntry->d_name);
 
1317
  }
1345
1318
  return 1;
1346
1319
}
1347
1320
 
1354
1327
  while(true){
1355
1328
    if(mc.current_server == NULL){
1356
1329
      if (debug){
1357
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1358
 
                "Wait until first server is found. No timeout!\n");
 
1330
        fprintf_plus(stderr, "Wait until first server is found."
 
1331
                     " No timeout!\n");
1359
1332
      }
1360
1333
      ret = avahi_simple_poll_iterate(s, -1);
1361
1334
    } else {
1362
1335
      if (debug){
1363
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1364
 
                "Check current_server if we should run it,"
1365
 
                " or wait\n");
 
1336
        fprintf_plus(stderr, "Check current_server if we should run"
 
1337
                     " it, or wait\n");
1366
1338
      }
1367
1339
      /* the current time */
1368
1340
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1384
1356
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1385
1357
      
1386
1358
      if (debug){
1387
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1388
 
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1359
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1360
                     block_time);
1389
1361
      }
1390
1362
      
1391
1363
      if(block_time <= 0){
1418
1390
  }
1419
1391
}
1420
1392
 
 
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
 
1421
1529
int main(int argc, char *argv[]){
1422
1530
  AvahiSServiceBrowser *sb = NULL;
1423
1531
  int error;
1503
1611
        .group = 2 },
1504
1612
      { .name = "retry", .key = 132,
1505
1613
        .arg = "SECONDS",
1506
 
        .doc = "Retry interval used when denied by the mandos server",
 
1614
        .doc = "Retry interval used when denied by the Mandos server",
1507
1615
        .group = 2 },
1508
1616
      { .name = "network-hook-dir", .key = 133,
1509
1617
        .arg = "DIR",
1581
1689
        argp_state_help(state, state->out_stream,
1582
1690
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1583
1691
      case 'V':                 /* --version */
1584
 
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1585
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1692
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1586
1693
        exit(argp_err_exit_status);
1587
1694
        break;
1588
1695
      default:
1615
1722
  {
1616
1723
    /* Work around Debian bug #633582:
1617
1724
       <http://bugs.debian.org/633582> */
1618
 
    struct stat st;
1619
1725
    
1620
1726
    /* Re-raise priviliges */
1621
1727
    errno = 0;
1622
1728
    ret = seteuid(0);
1623
1729
    if(ret == -1){
1624
1730
      perror_plus("seteuid");
1625
 
    }
1626
 
    
1627
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1628
 
      int seckey_fd = open(seckey, O_RDONLY);
1629
 
      if(seckey_fd == -1){
1630
 
        perror_plus("open");
1631
 
      } else {
1632
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1633
 
        if(ret == -1){
1634
 
          perror_plus("fstat");
1635
 
        } else {
1636
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1637
 
            ret = fchown(seckey_fd, uid, gid);
1638
 
            if(ret == -1){
1639
 
              perror_plus("fchown");
1640
 
            }
1641
 
          }
1642
 
        }
1643
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1644
 
      }
1645
 
    }
1646
 
    
1647
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1648
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1649
 
      if(pubkey_fd == -1){
1650
 
        perror_plus("open");
1651
 
      } else {
1652
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1653
 
        if(ret == -1){
1654
 
          perror_plus("fstat");
1655
 
        } else {
1656
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1657
 
            ret = fchown(pubkey_fd, uid, gid);
1658
 
            if(ret == -1){
1659
 
              perror_plus("fchown");
1660
 
            }
1661
 
          }
1662
 
        }
1663
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1664
 
      }
1665
 
    }
1666
 
    
1667
 
    /* Lower privileges */
1668
 
    errno = 0;
1669
 
    ret = seteuid(uid);
1670
 
    if(ret == -1){
1671
 
      perror_plus("seteuid");
1672
 
    }
1673
 
  }
1674
 
  
1675
 
  /* Find network hooks and run them */
1676
 
  {
1677
 
    struct dirent **direntries;
1678
 
    struct dirent *direntry;
1679
 
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
1680
 
                           alphasort);
1681
 
    if(numhooks == -1){
1682
 
      perror_plus("scandir");
1683
1731
    } else {
1684
 
      int devnull = open("/dev/null", O_RDONLY);
1685
 
      for(int i = 0; i < numhooks; i++){
1686
 
        direntry = direntries[0];
1687
 
        char *fullname = NULL;
1688
 
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1689
 
        if(ret < 0){
1690
 
          perror_plus("asprintf");
1691
 
          continue;
1692
 
        }
1693
 
        pid_t hook_pid = fork();
1694
 
        if(hook_pid == 0){
1695
 
          /* Child */
1696
 
          dup2(devnull, STDIN_FILENO);
1697
 
          close(devnull);
1698
 
          dup2(STDERR_FILENO, STDOUT_FILENO);
1699
 
          ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1700
 
          if(ret == -1){
1701
 
            perror_plus("setenv");
1702
 
            exit(1);
1703
 
          }
1704
 
          ret = setenv("DEVICE", interface, 1);
1705
 
          if(ret == -1){
1706
 
            perror_plus("setenv");
1707
 
            exit(1);
1708
 
          }
1709
 
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1710
 
          if(ret == -1){
1711
 
            perror_plus("setenv");
1712
 
            exit(1);
1713
 
          }
1714
 
          ret = setenv("MODE", "start", 1);
1715
 
          if(ret == -1){
1716
 
            perror_plus("setenv");
1717
 
            exit(1);
1718
 
          }
1719
 
          char *delaystring;
1720
 
          ret = asprintf(&delaystring, "%f", delay);
1721
 
          if(ret == -1){
1722
 
            perror_plus("asprintf");
1723
 
            exit(1);
1724
 
          }
1725
 
          ret = setenv("DELAY", delaystring, 1);
1726
 
          if(ret == -1){
1727
 
            free(delaystring);
1728
 
            perror_plus("setenv");
1729
 
            exit(1);
1730
 
          }
1731
 
          free(delaystring);
1732
 
          ret = execl(fullname, direntry->d_name, "start", NULL);
1733
 
          perror_plus("execl");
1734
 
        } else {
1735
 
          int status;
1736
 
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1737
 
            perror_plus("waitpid");
1738
 
            free(fullname);
1739
 
            continue;
1740
 
          }
1741
 
          if(WIFEXITED(status)){
1742
 
            if(WEXITSTATUS(status) != 0){
1743
 
              fprintf(stderr, "Mandos plugin mandos-client: "
1744
 
                      "Warning: network hook \"%s\" exited"
1745
 
                      " with status %d\n", direntry->d_name,
1746
 
                      WEXITSTATUS(status));
1747
 
              free(fullname);
1748
 
              continue;
1749
 
            }
1750
 
          } else if(WIFSIGNALED(status)){
1751
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1752
 
                    "Warning: network hook \"%s\" died by"
1753
 
                    " signal %d\n", direntry->d_name,
1754
 
                    WTERMSIG(status));
1755
 
            free(fullname);
1756
 
            continue;
1757
 
          } else {
1758
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1759
 
                    "Warning: network hook \"%s\" crashed\n",
1760
 
                    direntry->d_name);
1761
 
            free(fullname);
1762
 
            continue;
1763
 
          }
1764
 
        }
1765
 
        free(fullname);
1766
 
        if(quit_now){
1767
 
          goto end;
1768
 
        }
1769
 
      }
1770
 
      close(devnull);
 
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
      }
1771
1782
    }
1772
1783
  }
1773
1784
  
 
1785
  /* Run network hooks */
 
1786
  if(not run_network_hooks("start", interface, delay)){
 
1787
    goto end;
 
1788
  }
 
1789
  
1774
1790
  if(not debug){
1775
1791
    avahi_set_log_function(empty_log);
1776
1792
  }
1790
1806
      /* Pick the first interface returned */
1791
1807
      interface = strdup(direntries[0]->d_name);
1792
1808
      if(debug){
1793
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1794
 
                "Using interface \"%s\"\n", interface);
 
1809
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1795
1810
      }
1796
1811
      if(interface == NULL){
1797
1812
        perror_plus("malloc");
1802
1817
      free(direntries);
1803
1818
    } else {
1804
1819
      free(direntries);
1805
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1806
 
              "Could not find a network interface\n");
 
1820
      fprintf_plus(stderr, "Could not find a network interface\n");
1807
1821
      exitcode = EXIT_FAILURE;
1808
1822
      goto end;
1809
1823
    }
1815
1829
  srand((unsigned int) time(NULL));
1816
1830
  mc.simple_poll = avahi_simple_poll_new();
1817
1831
  if(mc.simple_poll == NULL){
1818
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1819
 
            "Avahi: Failed to create simple poll object.\n");
 
1832
    fprintf_plus(stderr,
 
1833
                 "Avahi: Failed to create simple poll object.\n");
1820
1834
    exitcode = EX_UNAVAILABLE;
1821
1835
    goto end;
1822
1836
  }
1888
1902
  if(strcmp(interface, "none") != 0){
1889
1903
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1890
1904
    if(if_index == 0){
1891
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1892
 
              "No such interface: \"%s\"\n", interface);
 
1905
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1893
1906
      exitcode = EX_UNAVAILABLE;
1894
1907
      goto end;
1895
1908
    }
2015
2028
#endif  /* __linux__ */
2016
2029
    /* Lower privileges */
2017
2030
    errno = 0;
2018
 
    if(take_down_interface){
2019
 
      /* Lower privileges */
2020
 
      ret = seteuid(uid);
2021
 
      if(ret == -1){
2022
 
        perror_plus("seteuid");
2023
 
      }
2024
 
    } else {
2025
 
      /* Lower privileges permanently */
2026
 
      ret = setuid(uid);
2027
 
      if(ret == -1){
2028
 
        perror_plus("setuid");
2029
 
      }
 
2031
    /* Lower privileges */
 
2032
    ret = seteuid(uid);
 
2033
    if(ret == -1){
 
2034
      perror_plus("seteuid");
2030
2035
    }
2031
2036
  }
2032
2037
  
2036
2041
  
2037
2042
  ret = init_gnutls_global(pubkey, seckey);
2038
2043
  if(ret == -1){
2039
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2040
 
            "init_gnutls_global failed\n");
 
2044
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2041
2045
    exitcode = EX_UNAVAILABLE;
2042
2046
    goto end;
2043
2047
  } else {
2059
2063
  }
2060
2064
  
2061
2065
  if(not init_gpgme(pubkey, seckey, tempdir)){
2062
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2063
 
            "init_gpgme failed\n");
 
2066
    fprintf_plus(stderr, "init_gpgme failed\n");
2064
2067
    exitcode = EX_UNAVAILABLE;
2065
2068
    goto end;
2066
2069
  } else {
2076
2079
    /* (Mainly meant for debugging) */
2077
2080
    char *address = strrchr(connect_to, ':');
2078
2081
    if(address == NULL){
2079
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2080
 
              "No colon in address\n");
 
2082
      fprintf_plus(stderr, "No colon in address\n");
2081
2083
      exitcode = EX_USAGE;
2082
2084
      goto end;
2083
2085
    }
2091
2093
    tmpmax = strtoimax(address+1, &tmp, 10);
2092
2094
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2093
2095
       or tmpmax != (uint16_t)tmpmax){
2094
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2095
 
              "Bad port number\n");
 
2096
      fprintf_plus(stderr, "Bad port number\n");
2096
2097
      exitcode = EX_USAGE;
2097
2098
      goto end;
2098
2099
    }
2128
2129
        break;
2129
2130
      }
2130
2131
      if(debug){
2131
 
        fprintf(stderr, "Mandos plugin mandos-client: "
2132
 
                "Retrying in %d seconds\n", (int)retry_interval);
 
2132
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2133
                     (int)retry_interval);
2133
2134
      }
2134
2135
      sleep((int)retry_interval);
2135
2136
    }
2165
2166
  
2166
2167
  /* Check if creating the Avahi server object succeeded */
2167
2168
  if(mc.server == NULL){
2168
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2169
 
            "Failed to create Avahi server: %s\n",
2170
 
            avahi_strerror(error));
 
2169
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2170
                 avahi_strerror(error));
2171
2171
    exitcode = EX_UNAVAILABLE;
2172
2172
    goto end;
2173
2173
  }
2181
2181
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2182
2182
                                   NULL, 0, browse_callback, NULL);
2183
2183
  if(sb == NULL){
2184
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2185
 
            "Failed to create service browser: %s\n",
2186
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2184
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2185
                 avahi_strerror(avahi_server_errno(mc.server)));
2187
2186
    exitcode = EX_UNAVAILABLE;
2188
2187
    goto end;
2189
2188
  }
2195
2194
  /* Run the main loop */
2196
2195
  
2197
2196
  if(debug){
2198
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2199
 
            "Starting Avahi loop search\n");
 
2197
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2200
2198
  }
2201
2199
 
2202
2200
  ret = avahi_loop_with_timeout(mc.simple_poll,
2203
2201
                                (int)(retry_interval * 1000));
2204
2202
  if(debug){
2205
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2206
 
            "avahi_loop_with_timeout exited %s\n",
2207
 
            (ret == 0) ? "successfully" : "with error");
 
2203
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2204
                 (ret == 0) ? "successfully" : "with error");
2208
2205
  }
2209
2206
  
2210
2207
 end:
2211
2208
  
2212
2209
  if(debug){
2213
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2214
 
            "%s exiting\n", argv[0]);
 
2210
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2215
2211
  }
2216
2212
  
2217
2213
  /* Cleanup things */
2233
2229
  if(gpgme_initialized){
2234
2230
    gpgme_release(mc.ctx);
2235
2231
  }
2236
 
 
 
2232
  
2237
2233
  /* Cleans up the circular linked list of Mandos servers the client
2238
2234
     has seen */
2239
2235
  if(mc.current_server != NULL){
2245
2241
    }
2246
2242
  }
2247
2243
  
2248
 
  /* XXX run network hooks "stop" here  */
 
2244
  /* Run network hooks */
 
2245
  run_network_hooks("stop", interface, delay);
2249
2246
  
2250
 
  /* Take down the network interface */
2251
 
  if(take_down_interface){
2252
 
    /* Re-raise priviliges */
 
2247
  /* Re-raise priviliges */
 
2248
  {
2253
2249
    errno = 0;
2254
2250
    ret = seteuid(0);
2255
2251
    if(ret == -1){
2256
2252
      perror_plus("seteuid");
2257
2253
    }
2258
 
    if(geteuid() == 0){
 
2254
    
 
2255
    /* Take down the network interface */
 
2256
    if(take_down_interface and geteuid() == 0){
2259
2257
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2260
2258
      if(ret == -1){
2261
2259
        perror_plus("ioctl SIOCGIFFLAGS");
2270
2268
      if(ret == -1){
2271
2269
        perror_plus("close");
2272
2270
      }
2273
 
      /* Lower privileges permanently */
2274
 
      errno = 0;
2275
 
      ret = setuid(uid);
2276
 
      if(ret == -1){
2277
 
        perror_plus("setuid");
2278
 
      }
2279
2271
    }
2280
2272
  }
 
2273
  /* Lower privileges permanently */
 
2274
  errno = 0;
 
2275
  ret = setuid(uid);
 
2276
  if(ret == -1){
 
2277
    perror_plus("setuid");
 
2278
  }
2281
2279
  
2282
2280
  /* Removes the GPGME temp directory and all files inside */
2283
2281
  if(tempdir_created){
2297
2295
        }
2298
2296
        ret = remove(fullname);
2299
2297
        if(ret == -1){
2300
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2301
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
2298
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2299
                       strerror(errno));
2302
2300
        }
2303
2301
        free(fullname);
2304
2302
      }