/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

* plugins.d/mandos-client.c (SYNOPSIS, OPTIONS): Document
                                                 "--network-hook-dir"
                                                 option.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
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() */
91
90
 
92
91
#ifdef __linux__
93
92
#include <sys/klog.h>           /* klogctl() */
111
110
                                   init_gnutls_session(),
112
111
                                   GNUTLS_* */
113
112
#include <gnutls/openpgp.h>
114
 
                         /* gnutls_certificate_set_openpgp_key_file(),
115
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
113
                          /* gnutls_certificate_set_openpgp_key_file(),
 
114
                                   GNUTLS_OPENPGP_FMT_BASE64 */
116
115
 
117
116
/* GPGME */
118
117
#include <gpgme.h>              /* All GPGME types, constants and
175
174
  perror(print_text);
176
175
}
177
176
 
178
 
int fprintf_plus(FILE *stream, const char *format, ...){
179
 
  va_list ap;
180
 
  va_start (ap, format);
181
 
  
182
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
183
 
                             program_invocation_short_name));
184
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
185
 
}
186
 
 
187
177
/*
188
178
 * Make additional room in "buffer" for at least BUFFER_SIZE more
189
179
 * bytes. "buffer_capacity" is how much is currently allocated,
190
180
 * "buffer_length" is how much is already used.
191
181
 */
192
182
size_t incbuffer(char **buffer, size_t buffer_length,
193
 
                 size_t buffer_capacity){
 
183
                  size_t buffer_capacity){
194
184
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
195
185
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
196
186
    if(buffer == NULL){
202
192
}
203
193
 
204
194
/* Add server to set of servers to retry periodically */
205
 
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
206
 
               int af){
 
195
int add_server(const char *ip, uint16_t port,
 
196
                 AvahiIfIndex if_index,
 
197
                 int af){
207
198
  int ret;
208
199
  server *new_server = malloc(sizeof(server));
209
200
  if(new_server == NULL){
211
202
    return -1;
212
203
  }
213
204
  *new_server = (server){ .ip = strdup(ip),
214
 
                          .port = port,
215
 
                          .if_index = if_index,
216
 
                          .af = af };
 
205
                         .port = port,
 
206
                         .if_index = if_index,
 
207
                         .af = af };
217
208
  if(new_server->ip == NULL){
218
209
    perror_plus("strdup");
219
210
    return -1;
241
232
/* 
242
233
 * Initialize GPGME.
243
234
 */
244
 
static bool init_gpgme(const char *seckey, const char *pubkey,
245
 
                       const char *tempdir){
 
235
static bool init_gpgme(const char *seckey,
 
236
                       const char *pubkey, const char *tempdir){
246
237
  gpgme_error_t rc;
247
238
  gpgme_engine_info_t engine_info;
248
239
  
263
254
    
264
255
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
265
256
    if(rc != GPG_ERR_NO_ERROR){
266
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
267
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
257
      fprintf(stderr, "Mandos plugin mandos-client: "
 
258
              "bad gpgme_data_new_from_fd: %s: %s\n",
 
259
              gpgme_strsource(rc), gpgme_strerror(rc));
268
260
      return false;
269
261
    }
270
262
    
271
263
    rc = gpgme_op_import(mc.ctx, pgp_data);
272
264
    if(rc != GPG_ERR_NO_ERROR){
273
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
274
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
265
      fprintf(stderr, "Mandos plugin mandos-client: "
 
266
              "bad gpgme_op_import: %s: %s\n",
 
267
              gpgme_strsource(rc), gpgme_strerror(rc));
275
268
      return false;
276
269
    }
277
270
    
284
277
  }
285
278
  
286
279
  if(debug){
287
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
280
    fprintf(stderr, "Mandos plugin mandos-client: "
 
281
            "Initializing GPGME\n");
288
282
  }
289
283
  
290
284
  /* Init GPGME */
291
285
  gpgme_check_version(NULL);
292
286
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
293
287
  if(rc != GPG_ERR_NO_ERROR){
294
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
295
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
288
    fprintf(stderr, "Mandos plugin mandos-client: "
 
289
            "bad gpgme_engine_check_version: %s: %s\n",
 
290
            gpgme_strsource(rc), gpgme_strerror(rc));
296
291
    return false;
297
292
  }
298
293
  
299
294
  /* Set GPGME home directory for the OpenPGP engine only */
300
295
  rc = gpgme_get_engine_info(&engine_info);
301
296
  if(rc != GPG_ERR_NO_ERROR){
302
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
303
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
297
    fprintf(stderr, "Mandos plugin mandos-client: "
 
298
            "bad gpgme_get_engine_info: %s: %s\n",
 
299
            gpgme_strsource(rc), gpgme_strerror(rc));
304
300
    return false;
305
301
  }
306
302
  while(engine_info != NULL){
312
308
    engine_info = engine_info->next;
313
309
  }
314
310
  if(engine_info == NULL){
315
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
316
 
                 tempdir);
 
311
    fprintf(stderr, "Mandos plugin mandos-client: "
 
312
            "Could not set GPGME home dir to %s\n", tempdir);
317
313
    return false;
318
314
  }
319
315
  
320
316
  /* Create new GPGME "context" */
321
317
  rc = gpgme_new(&(mc.ctx));
322
318
  if(rc != GPG_ERR_NO_ERROR){
323
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
324
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
325
 
                 gpgme_strerror(rc));
 
319
    fprintf(stderr, "Mandos plugin mandos-client: "
 
320
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
321
            gpgme_strerror(rc));
326
322
    return false;
327
323
  }
328
324
  
347
343
  ssize_t plaintext_length = 0;
348
344
  
349
345
  if(debug){
350
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
346
    fprintf(stderr, "Mandos plugin mandos-client: "
 
347
            "Trying to decrypt OpenPGP data\n");
351
348
  }
352
349
  
353
350
  /* Create new GPGME data buffer from memory cryptotext */
354
351
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
355
352
                               0);
356
353
  if(rc != GPG_ERR_NO_ERROR){
357
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
358
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
354
    fprintf(stderr, "Mandos plugin mandos-client: "
 
355
            "bad gpgme_data_new_from_mem: %s: %s\n",
 
356
            gpgme_strsource(rc), gpgme_strerror(rc));
359
357
    return -1;
360
358
  }
361
359
  
362
360
  /* Create new empty GPGME data buffer for the plaintext */
363
361
  rc = gpgme_data_new(&dh_plain);
364
362
  if(rc != GPG_ERR_NO_ERROR){
365
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
366
 
                 "bad gpgme_data_new: %s: %s\n",
367
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
363
    fprintf(stderr, "Mandos plugin mandos-client: "
 
364
            "bad gpgme_data_new: %s: %s\n",
 
365
            gpgme_strsource(rc), gpgme_strerror(rc));
368
366
    gpgme_data_release(dh_crypto);
369
367
    return -1;
370
368
  }
373
371
     data buffer */
374
372
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
375
373
  if(rc != GPG_ERR_NO_ERROR){
376
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
377
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
374
    fprintf(stderr, "Mandos plugin mandos-client: "
 
375
            "bad gpgme_op_decrypt: %s: %s\n",
 
376
            gpgme_strsource(rc), gpgme_strerror(rc));
378
377
    plaintext_length = -1;
379
378
    if(debug){
380
379
      gpgme_decrypt_result_t result;
381
380
      result = gpgme_op_decrypt_result(mc.ctx);
382
381
      if(result == NULL){
383
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
382
        fprintf(stderr, "Mandos plugin mandos-client: "
 
383
                "gpgme_op_decrypt_result failed\n");
384
384
      } else {
385
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
386
 
                     result->unsupported_algorithm);
387
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
388
 
                     result->wrong_key_usage);
 
385
        fprintf(stderr, "Mandos plugin mandos-client: "
 
386
                "Unsupported algorithm: %s\n",
 
387
                result->unsupported_algorithm);
 
388
        fprintf(stderr, "Mandos plugin mandos-client: "
 
389
                "Wrong key usage: %u\n",
 
390
                result->wrong_key_usage);
389
391
        if(result->file_name != NULL){
390
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
392
          fprintf(stderr, "Mandos plugin mandos-client: "
 
393
                  "File name: %s\n", result->file_name);
391
394
        }
392
395
        gpgme_recipient_t recipient;
393
396
        recipient = result->recipients;
394
397
        while(recipient != NULL){
395
 
          fprintf_plus(stderr, "Public key algorithm: %s\n",
396
 
                       gpgme_pubkey_algo_name
397
 
                       (recipient->pubkey_algo));
398
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
399
 
          fprintf_plus(stderr, "Secret key available: %s\n",
400
 
                       recipient->status == GPG_ERR_NO_SECKEY
401
 
                       ? "No" : "Yes");
 
398
          fprintf(stderr, "Mandos plugin mandos-client: "
 
399
                  "Public key algorithm: %s\n",
 
400
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
401
          fprintf(stderr, "Mandos plugin mandos-client: "
 
402
                  "Key ID: %s\n", recipient->keyid);
 
403
          fprintf(stderr, "Mandos plugin mandos-client: "
 
404
                  "Secret key available: %s\n",
 
405
                  recipient->status == GPG_ERR_NO_SECKEY
 
406
                  ? "No" : "Yes");
402
407
          recipient = recipient->next;
403
408
        }
404
409
      }
407
412
  }
408
413
  
409
414
  if(debug){
410
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
415
    fprintf(stderr, "Mandos plugin mandos-client: "
 
416
            "Decryption of OpenPGP data succeeded\n");
411
417
  }
412
418
  
413
419
  /* Seek back to the beginning of the GPGME plaintext data buffer */
420
426
  *plaintext = NULL;
421
427
  while(true){
422
428
    plaintext_capacity = incbuffer(plaintext,
423
 
                                   (size_t)plaintext_length,
424
 
                                   plaintext_capacity);
 
429
                                      (size_t)plaintext_length,
 
430
                                      plaintext_capacity);
425
431
    if(plaintext_capacity == 0){
426
 
      perror_plus("incbuffer");
427
 
      plaintext_length = -1;
428
 
      goto decrypt_end;
 
432
        perror_plus("incbuffer");
 
433
        plaintext_length = -1;
 
434
        goto decrypt_end;
429
435
    }
430
436
    
431
437
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
444
450
  }
445
451
  
446
452
  if(debug){
447
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
453
    fprintf(stderr, "Mandos plugin mandos-client: "
 
454
            "Decrypted password is: ");
448
455
    for(ssize_t i = 0; i < plaintext_length; i++){
449
456
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
450
457
    }
472
479
/* GnuTLS log function callback */
473
480
static void debuggnutls(__attribute__((unused)) int level,
474
481
                        const char* string){
475
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
482
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
476
483
}
477
484
 
478
485
static int init_gnutls_global(const char *pubkeyfilename,
480
487
  int ret;
481
488
  
482
489
  if(debug){
483
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
490
    fprintf(stderr, "Mandos plugin mandos-client: "
 
491
            "Initializing GnuTLS\n");
484
492
  }
485
493
  
486
494
  ret = gnutls_global_init();
487
495
  if(ret != GNUTLS_E_SUCCESS){
488
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
489
 
                 safer_gnutls_strerror(ret));
 
496
    fprintf(stderr, "Mandos plugin mandos-client: "
 
497
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
490
498
    return -1;
491
499
  }
492
500
  
501
509
  /* OpenPGP credentials */
502
510
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
503
511
  if(ret != GNUTLS_E_SUCCESS){
504
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
505
 
                 safer_gnutls_strerror(ret));
 
512
    fprintf(stderr, "Mandos plugin mandos-client: "
 
513
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
506
514
    gnutls_global_deinit();
507
515
    return -1;
508
516
  }
509
517
  
510
518
  if(debug){
511
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
512
 
                 " secret key %s as GnuTLS credentials\n",
513
 
                 pubkeyfilename,
514
 
                 seckeyfilename);
 
519
    fprintf(stderr, "Mandos plugin mandos-client: "
 
520
            "Attempting to use OpenPGP public key %s and"
 
521
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
522
            seckeyfilename);
515
523
  }
516
524
  
517
525
  ret = gnutls_certificate_set_openpgp_key_file
518
526
    (mc.cred, pubkeyfilename, seckeyfilename,
519
527
     GNUTLS_OPENPGP_FMT_BASE64);
520
528
  if(ret != GNUTLS_E_SUCCESS){
521
 
    fprintf_plus(stderr,
522
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
523
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
524
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
525
 
                 safer_gnutls_strerror(ret));
 
529
    fprintf(stderr,
 
530
            "Mandos plugin mandos-client: "
 
531
            "Error[%d] while reading the OpenPGP key pair ('%s',"
 
532
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
533
    fprintf(stderr, "Mandos plugin mandos-client: "
 
534
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
526
535
    goto globalfail;
527
536
  }
528
537
  
529
538
  /* GnuTLS server initialization */
530
539
  ret = gnutls_dh_params_init(&mc.dh_params);
531
540
  if(ret != GNUTLS_E_SUCCESS){
532
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
533
 
                 " initialization: %s\n",
534
 
                 safer_gnutls_strerror(ret));
 
541
    fprintf(stderr, "Mandos plugin mandos-client: "
 
542
            "Error in GnuTLS DH parameter initialization:"
 
543
            " %s\n", safer_gnutls_strerror(ret));
535
544
    goto globalfail;
536
545
  }
537
546
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
538
547
  if(ret != GNUTLS_E_SUCCESS){
539
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
540
 
                 safer_gnutls_strerror(ret));
 
548
    fprintf(stderr, "Mandos plugin mandos-client: "
 
549
            "Error in GnuTLS prime generation: %s\n",
 
550
            safer_gnutls_strerror(ret));
541
551
    goto globalfail;
542
552
  }
543
553
  
563
573
    }
564
574
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
565
575
  if(ret != GNUTLS_E_SUCCESS){
566
 
    fprintf_plus(stderr,
567
 
                 "Error in GnuTLS session initialization: %s\n",
568
 
                 safer_gnutls_strerror(ret));
 
576
    fprintf(stderr, "Mandos plugin mandos-client: "
 
577
            "Error in GnuTLS session initialization: %s\n",
 
578
            safer_gnutls_strerror(ret));
569
579
  }
570
580
  
571
581
  {
578
588
      }
579
589
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
580
590
    if(ret != GNUTLS_E_SUCCESS){
581
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
582
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
583
 
                   safer_gnutls_strerror(ret));
 
591
      fprintf(stderr, "Mandos plugin mandos-client: "
 
592
              "Syntax error at: %s\n", err);
 
593
      fprintf(stderr, "Mandos plugin mandos-client: "
 
594
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
584
595
      gnutls_deinit(*session);
585
596
      return -1;
586
597
    }
595
606
    }
596
607
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
597
608
  if(ret != GNUTLS_E_SUCCESS){
598
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
599
 
                 safer_gnutls_strerror(ret));
 
609
    fprintf(stderr, "Mandos plugin mandos-client: "
 
610
            "Error setting GnuTLS credentials: %s\n",
 
611
            safer_gnutls_strerror(ret));
600
612
    gnutls_deinit(*session);
601
613
    return -1;
602
614
  }
647
659
    pf = PF_INET;
648
660
    break;
649
661
  default:
650
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
662
    fprintf(stderr, "Mandos plugin mandos-client: "
 
663
            "Bad address family: %d\n", af);
651
664
    errno = EINVAL;
652
665
    return -1;
653
666
  }
658
671
  }
659
672
  
660
673
  if(debug){
661
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
662
 
                 PRIu16 "\n", ip, port);
 
674
    fprintf(stderr, "Mandos plugin mandos-client: "
 
675
            "Setting up a TCP connection to %s, port %" PRIu16
 
676
            "\n", ip, port);
663
677
  }
664
678
  
665
679
  tcp_sd = socket(pf, SOCK_STREAM, 0);
691
705
  }
692
706
  if(ret == 0){
693
707
    int e = errno;
694
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
708
    fprintf(stderr, "Mandos plugin mandos-client: "
 
709
            "Bad address: %s\n", ip);
695
710
    errno = e;
696
711
    goto mandos_end;
697
712
  }
702
717
    
703
718
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
704
719
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
705
 
                                -Wunreachable-code*/
 
720
                              -Wunreachable-code*/
706
721
      if(if_index == AVAHI_IF_UNSPEC){
707
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
708
 
                     " incomplete without a network interface\n");
 
722
        fprintf(stderr, "Mandos plugin mandos-client: "
 
723
                "An IPv6 link-local address is incomplete"
 
724
                " without a network interface\n");
709
725
        errno = EINVAL;
710
726
        goto mandos_end;
711
727
      }
729
745
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
730
746
        perror_plus("if_indextoname");
731
747
      } else {
732
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
733
 
                     "\n", ip, interface, port);
 
748
        fprintf(stderr, "Mandos plugin mandos-client: "
 
749
                "Connection to: %s%%%s, port %" PRIu16 "\n",
 
750
                ip, interface, port);
734
751
      }
735
752
    } else {
736
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
737
 
                   ip, port);
 
753
      fprintf(stderr, "Mandos plugin mandos-client: "
 
754
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
738
755
    }
739
756
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
740
757
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
750
767
      perror_plus("inet_ntop");
751
768
    } else {
752
769
      if(strcmp(addrstr, ip) != 0){
753
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
770
        fprintf(stderr, "Mandos plugin mandos-client: "
 
771
                "Canonical address form: %s\n", addrstr);
754
772
      }
755
773
    }
756
774
  }
784
802
  while(true){
785
803
    size_t out_size = strlen(out);
786
804
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
787
 
                                        out_size - written));
 
805
                                   out_size - written));
788
806
    if(ret == -1){
789
807
      int e = errno;
790
808
      perror_plus("write");
810
828
  }
811
829
  
812
830
  if(debug){
813
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
831
    fprintf(stderr, "Mandos plugin mandos-client: "
 
832
            "Establishing TLS session with %s\n", ip);
814
833
  }
815
834
  
816
835
  if(quit_now){
836
855
  
837
856
  if(ret != GNUTLS_E_SUCCESS){
838
857
    if(debug){
839
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
858
      fprintf(stderr, "Mandos plugin mandos-client: "
 
859
              "*** GnuTLS Handshake failed ***\n");
840
860
      gnutls_perror(ret);
841
861
    }
842
862
    errno = EPROTO;
846
866
  /* Read OpenPGP packet that contains the wanted password */
847
867
  
848
868
  if(debug){
849
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
850
 
                 " %s\n", ip);
 
869
    fprintf(stderr, "Mandos plugin mandos-client: "
 
870
            "Retrieving OpenPGP encrypted password from %s\n", ip);
851
871
  }
852
872
  
853
873
  while(true){
858
878
    }
859
879
    
860
880
    buffer_capacity = incbuffer(&buffer, buffer_length,
861
 
                                buffer_capacity);
 
881
                                   buffer_capacity);
862
882
    if(buffer_capacity == 0){
863
883
      int e = errno;
864
884
      perror_plus("incbuffer");
891
911
          }
892
912
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
893
913
        if(ret < 0){
894
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
895
 
                       "***\n");
 
914
          fprintf(stderr, "Mandos plugin mandos-client: "
 
915
                  "*** GnuTLS Re-handshake failed ***\n");
896
916
          gnutls_perror(ret);
897
917
          errno = EPROTO;
898
918
          goto mandos_end;
899
919
        }
900
920
        break;
901
921
      default:
902
 
        fprintf_plus(stderr, "Unknown error while reading data from"
903
 
                     " encrypted session with Mandos server\n");
 
922
        fprintf(stderr, "Mandos plugin mandos-client: "
 
923
                "Unknown error while reading data from"
 
924
                " encrypted session with Mandos server\n");
904
925
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
905
926
        errno = EIO;
906
927
        goto mandos_end;
911
932
  }
912
933
  
913
934
  if(debug){
914
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
935
    fprintf(stderr, "Mandos plugin mandos-client: "
 
936
            "Closing TLS session\n");
915
937
  }
916
938
  
917
939
  if(quit_now){
929
951
  
930
952
  if(buffer_length > 0){
931
953
    ssize_t decrypted_buffer_size;
932
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
954
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
955
                                               buffer_length,
933
956
                                               &decrypted_buffer);
934
957
    if(decrypted_buffer_size >= 0){
935
958
      
946
969
        if(ret == 0 and ferror(stdout)){
947
970
          int e = errno;
948
971
          if(debug){
949
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
950
 
                         strerror(errno));
 
972
            fprintf(stderr, "Mandos plugin mandos-client: "
 
973
                    "Error writing encrypted data: %s\n",
 
974
                    strerror(errno));
951
975
          }
952
976
          errno = e;
953
977
          goto mandos_end;
1010
1034
  switch(event){
1011
1035
  default:
1012
1036
  case AVAHI_RESOLVER_FAILURE:
1013
 
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1014
 
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1015
 
                 domain,
1016
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1037
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1038
            "(Avahi Resolver) Failed to resolve service '%s'"
 
1039
            " of type '%s' in domain '%s': %s\n", name, type, domain,
 
1040
            avahi_strerror(avahi_server_errno(mc.server)));
1017
1041
    break;
1018
1042
    
1019
1043
  case AVAHI_RESOLVER_FOUND:
1021
1045
      char ip[AVAHI_ADDRESS_STR_MAX];
1022
1046
      avahi_address_snprint(ip, sizeof(ip), address);
1023
1047
      if(debug){
1024
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1025
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1026
 
                     host_name, ip, (intmax_t)interface, port);
 
1048
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1049
                "Mandos server \"%s\" found on %s (%s, %"
 
1050
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
1051
                ip, (intmax_t)interface, port);
1027
1052
      }
1028
1053
      int ret = start_mandos_communication(ip, port, interface,
1029
1054
                                           avahi_proto_to_af(proto));
1061
1086
  default:
1062
1087
  case AVAHI_BROWSER_FAILURE:
1063
1088
    
1064
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1065
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1089
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1090
            "(Avahi browser) %s\n",
 
1091
            avahi_strerror(avahi_server_errno(mc.server)));
1066
1092
    avahi_simple_poll_quit(mc.simple_poll);
1067
1093
    return;
1068
1094
    
1075
1101
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1076
1102
                                    name, type, domain, protocol, 0,
1077
1103
                                    resolve_callback, NULL) == NULL)
1078
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1079
 
                   " %s\n", name,
1080
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1104
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1105
              "Avahi: Failed to resolve service '%s': %s\n",
 
1106
              name, avahi_strerror(avahi_server_errno(mc.server)));
1081
1107
    break;
1082
1108
    
1083
1109
  case AVAHI_BROWSER_REMOVE:
1086
1112
  case AVAHI_BROWSER_ALL_FOR_NOW:
1087
1113
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1088
1114
    if(debug){
1089
 
      fprintf_plus(stderr, "No Mandos server found, still"
1090
 
                   " searching...\n");
 
1115
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1116
              "No Mandos server found, still searching...\n");
1091
1117
    }
1092
1118
    break;
1093
1119
  }
1132
1158
  /* Reject the loopback device */
1133
1159
  if(ifr->ifr_flags & IFF_LOOPBACK){
1134
1160
    if(debug){
1135
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1136
 
                   ifname);
 
1161
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1162
              "Rejecting loopback interface \"%s\"\n", ifname);
1137
1163
    }
1138
1164
    return false;
1139
1165
  }
1140
1166
  /* Accept point-to-point devices only if connect_to is specified */
1141
1167
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1142
1168
    if(debug){
1143
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1144
 
                   " \"%s\"\n", ifname);
 
1169
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1170
              "Accepting point-to-point interface \"%s\"\n", ifname);
1145
1171
    }
1146
1172
    return true;
1147
1173
  }
1148
1174
  /* Otherwise, reject non-broadcast-capable devices */
1149
1175
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1150
1176
    if(debug){
1151
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1152
 
                   " \"%s\"\n", ifname);
 
1177
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1178
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
1153
1179
    }
1154
1180
    return false;
1155
1181
  }
1156
1182
  /* Reject non-ARP interfaces (including dummy interfaces) */
1157
1183
  if(ifr->ifr_flags & IFF_NOARP){
1158
1184
    if(debug){
1159
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1160
 
                   ifname);
 
1185
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1186
              "Rejecting non-ARP interface \"%s\"\n", ifname);
1161
1187
    }
1162
1188
    return false;
1163
1189
  }
1164
1190
  
1165
1191
  /* Accept this device */
1166
1192
  if(debug){
1167
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1193
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1194
            "Interface \"%s\" is good\n", ifname);
1168
1195
  }
1169
1196
  return true;
1170
1197
}
1182
1209
  struct ifreq ifr;
1183
1210
  if(not get_flags(if_entry->d_name, &ifr)){
1184
1211
    if(debug){
1185
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1186
 
                   "\"%s\"\n", if_entry->d_name);
 
1212
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1213
              "Failed to get flags for interface \"%s\"\n",
 
1214
              if_entry->d_name);
1187
1215
    }
1188
1216
    return 0;
1189
1217
  }
1207
1235
  struct ifreq ifr;
1208
1236
  if(not get_flags(if_entry->d_name, &ifr)){
1209
1237
    if(debug){
1210
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1211
 
                   "\"%s\"\n", if_entry->d_name);
 
1238
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1239
              "Failed to get flags for interface \"%s\"\n",
 
1240
              if_entry->d_name);
1212
1241
    }
1213
1242
    return 0;
1214
1243
  }
1216
1245
  /* Reject down interfaces */
1217
1246
  if(not (ifr.ifr_flags & IFF_UP)){
1218
1247
    if(debug){
1219
 
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1220
 
                   if_entry->d_name);
 
1248
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1249
              "Rejecting down interface \"%s\"\n",
 
1250
              if_entry->d_name);
1221
1251
    }
1222
1252
    return 0;
1223
1253
  }
1225
1255
  /* Reject non-running interfaces */
1226
1256
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1227
1257
    if(debug){
1228
 
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1229
 
                   if_entry->d_name);
 
1258
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1259
              "Rejecting non-running interface \"%s\"\n",
 
1260
              if_entry->d_name);
1230
1261
    }
1231
1262
    return 0;
1232
1263
  }
1251
1282
/* Is this directory entry a runnable program? */
1252
1283
int runnable_hook(const struct dirent *direntry){
1253
1284
  int ret;
1254
 
  size_t sret;
1255
1285
  struct stat st;
1256
1286
  
1257
1287
  if((direntry->d_name)[0] == '\0'){
1259
1289
    return 0;
1260
1290
  }
1261
1291
  
1262
 
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1263
 
                "abcdefghijklmnopqrstuvwxyz"
1264
 
                "0123456789"
1265
 
                "_-");
1266
 
  if((direntry->d_name)[sret] != '\0'){
1267
 
    /* Contains non-allowed characters */
1268
 
    if(debug){
1269
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1270
 
                   direntry->d_name);
1271
 
    }
1272
 
    return 0;
1273
 
  }
 
1292
  /* Save pointer to last character */
 
1293
  char *end = strchr(direntry->d_name, '\0')-1;
 
1294
  
 
1295
  if(*end == '~'){
 
1296
    /* Backup name~ */
 
1297
    return 0;
 
1298
  }
 
1299
  
 
1300
  if(((direntry->d_name)[0] == '#')
 
1301
     and (*end == '#')){
 
1302
    /* Temporary #name# */
 
1303
    return 0;
 
1304
  }
 
1305
  
 
1306
  /* XXX more rules here */
1274
1307
  
1275
1308
  char *fullname = NULL;
1276
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1309
  ret = asprintf(&fullname, "%s/%s", hookdir,
 
1310
                 direntry->d_name);
1277
1311
  if(ret < 0){
1278
1312
    perror_plus("asprintf");
1279
1313
    return 0;
1282
1316
  ret = stat(fullname, &st);
1283
1317
  if(ret == -1){
1284
1318
    if(debug){
1285
 
      perror_plus("Could not stat hook");
 
1319
      perror_plus("Could not stat plugin");
1286
1320
    }
1287
1321
    return 0;
1288
1322
  }
1289
1323
  if(not (S_ISREG(st.st_mode))){
1290
1324
    /* Not a regular file */
1291
 
    if(debug){
1292
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1293
 
                   direntry->d_name);
1294
 
    }
1295
1325
    return 0;
1296
1326
  }
1297
1327
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1298
1328
    /* Not executable */
1299
 
    if(debug){
1300
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1301
 
                   direntry->d_name);
1302
 
    }
1303
1329
    return 0;
1304
1330
  }
1305
 
  if(debug){
1306
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1307
 
                 direntry->d_name);
1308
 
  }
1309
1331
  return 1;
1310
1332
}
1311
1333
 
1318
1340
  while(true){
1319
1341
    if(mc.current_server == NULL){
1320
1342
      if (debug){
1321
 
        fprintf_plus(stderr, "Wait until first server is found."
1322
 
                     " No timeout!\n");
 
1343
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1344
                "Wait until first server is found. No timeout!\n");
1323
1345
      }
1324
1346
      ret = avahi_simple_poll_iterate(s, -1);
1325
1347
    } else {
1326
1348
      if (debug){
1327
 
        fprintf_plus(stderr, "Check current_server if we should run"
1328
 
                     " it, or wait\n");
 
1349
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1350
                "Check current_server if we should run it,"
 
1351
                " or wait\n");
1329
1352
      }
1330
1353
      /* the current time */
1331
1354
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1347
1370
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1348
1371
      
1349
1372
      if (debug){
1350
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1351
 
                     block_time);
 
1373
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1374
                "Blocking for %" PRIdMAX " ms\n", block_time);
1352
1375
      }
1353
1376
      
1354
1377
      if(block_time <= 0){
1381
1404
  }
1382
1405
}
1383
1406
 
1384
 
bool run_network_hooks(const char *mode, const char *interface,
1385
 
                       const float delay){
1386
 
  struct dirent **direntries;
1387
 
  struct dirent *direntry;
1388
 
  int ret;
1389
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1390
 
                         alphasort);
1391
 
  if(numhooks == -1){
1392
 
    perror_plus("scandir");
1393
 
  } else {
1394
 
    int devnull = open("/dev/null", O_RDONLY);
1395
 
    for(int i = 0; i < numhooks; i++){
1396
 
      direntry = direntries[i];
1397
 
      char *fullname = NULL;
1398
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1399
 
      if(ret < 0){
1400
 
        perror_plus("asprintf");
1401
 
        continue;
1402
 
      }
1403
 
      if(debug){
1404
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1405
 
                     direntry->d_name);
1406
 
      }
1407
 
      pid_t hook_pid = fork();
1408
 
      if(hook_pid == 0){
1409
 
        /* Child */
1410
 
        /* Raise privileges */
1411
 
        errno = 0;
1412
 
        ret = seteuid(0);
1413
 
        if(ret == -1){
1414
 
          perror_plus("seteuid");
1415
 
        }
1416
 
        /* Raise privileges even more */
1417
 
        errno = 0;
1418
 
        ret = setuid(0);
1419
 
        if(ret == -1){
1420
 
          perror_plus("setuid");
1421
 
        }
1422
 
        /* Set group */
1423
 
        errno = 0;
1424
 
        ret = setgid(0);
1425
 
        if(ret == -1){
1426
 
          perror_plus("setgid");
1427
 
        }
1428
 
        /* Reset supplementary groups */
1429
 
        errno = 0;
1430
 
        ret = setgroups(0, NULL);
1431
 
        if(ret == -1){
1432
 
          perror_plus("setgroups");
1433
 
        }
1434
 
        dup2(devnull, STDIN_FILENO);
1435
 
        close(devnull);
1436
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1437
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1438
 
        if(ret == -1){
1439
 
          perror_plus("setenv");
1440
 
          _exit(EX_OSERR);
1441
 
        }
1442
 
        ret = setenv("DEVICE", interface, 1);
1443
 
        if(ret == -1){
1444
 
          perror_plus("setenv");
1445
 
          _exit(EX_OSERR);
1446
 
        }
1447
 
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1448
 
        if(ret == -1){
1449
 
          perror_plus("setenv");
1450
 
          _exit(EX_OSERR);
1451
 
        }
1452
 
        ret = setenv("MODE", mode, 1);
1453
 
        if(ret == -1){
1454
 
          perror_plus("setenv");
1455
 
          _exit(EX_OSERR);
1456
 
        }
1457
 
        char *delaystring;
1458
 
        ret = asprintf(&delaystring, "%f", delay);
1459
 
        if(ret == -1){
1460
 
          perror_plus("asprintf");
1461
 
          _exit(EX_OSERR);
1462
 
        }
1463
 
        ret = setenv("DELAY", delaystring, 1);
1464
 
        if(ret == -1){
1465
 
          free(delaystring);
1466
 
          perror_plus("setenv");
1467
 
          _exit(EX_OSERR);
1468
 
        }
1469
 
        free(delaystring);
1470
 
        ret = execl(fullname, direntry->d_name, mode, NULL);
1471
 
        perror_plus("execl");
1472
 
      } else {
1473
 
        int status;
1474
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1475
 
          perror_plus("waitpid");
1476
 
          free(fullname);
1477
 
          continue;
1478
 
        }
1479
 
        if(WIFEXITED(status)){
1480
 
          if(WEXITSTATUS(status) != 0){
1481
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1482
 
                         " with status %d\n", direntry->d_name,
1483
 
                         WEXITSTATUS(status));
1484
 
            free(fullname);
1485
 
            continue;
1486
 
          }
1487
 
        } else if(WIFSIGNALED(status)){
1488
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1489
 
                       " signal %d\n", direntry->d_name,
1490
 
                       WTERMSIG(status));
1491
 
          free(fullname);
1492
 
          continue;
1493
 
        } else {
1494
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1495
 
                       " crashed\n", direntry->d_name);
1496
 
          free(fullname);
1497
 
          continue;
1498
 
        }
1499
 
      }
1500
 
      free(fullname);
1501
 
      if(debug){
1502
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1503
 
                     direntry->d_name);
1504
 
      }
1505
 
    }
1506
 
    close(devnull);
1507
 
  }
1508
 
  return true;
1509
 
}
1510
 
 
1511
1407
int main(int argc, char *argv[]){
1512
1408
  AvahiSServiceBrowser *sb = NULL;
1513
1409
  int error;
1671
1567
        argp_state_help(state, state->out_stream,
1672
1568
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1673
1569
      case 'V':                 /* --version */
1674
 
        fprintf_plus(state->out_stream,
1675
 
                     "Mandos plugin mandos-client: ");
1676
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1570
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
 
1571
        fprintf(state->out_stream, "%s\n", argp_program_version);
1677
1572
        exit(argp_err_exit_status);
1678
1573
        break;
1679
1574
      default:
1706
1601
  {
1707
1602
    /* Work around Debian bug #633582:
1708
1603
       <http://bugs.debian.org/633582> */
 
1604
    struct stat st;
1709
1605
    
1710
1606
    /* Re-raise priviliges */
1711
1607
    errno = 0;
1712
1608
    ret = seteuid(0);
1713
1609
    if(ret == -1){
1714
1610
      perror_plus("seteuid");
 
1611
    }
 
1612
    
 
1613
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1614
      int seckey_fd = open(seckey, O_RDONLY);
 
1615
      if(seckey_fd == -1){
 
1616
        perror_plus("open");
 
1617
      } else {
 
1618
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1619
        if(ret == -1){
 
1620
          perror_plus("fstat");
 
1621
        } else {
 
1622
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1623
            ret = fchown(seckey_fd, uid, gid);
 
1624
            if(ret == -1){
 
1625
              perror_plus("fchown");
 
1626
            }
 
1627
          }
 
1628
        }
 
1629
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1630
      }
 
1631
    }
 
1632
    
 
1633
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1634
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1635
      if(pubkey_fd == -1){
 
1636
        perror_plus("open");
 
1637
      } else {
 
1638
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1639
        if(ret == -1){
 
1640
          perror_plus("fstat");
 
1641
        } else {
 
1642
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1643
            ret = fchown(pubkey_fd, uid, gid);
 
1644
            if(ret == -1){
 
1645
              perror_plus("fchown");
 
1646
            }
 
1647
          }
 
1648
        }
 
1649
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1650
      }
 
1651
    }
 
1652
    
 
1653
    /* Lower privileges */
 
1654
    errno = 0;
 
1655
    ret = seteuid(uid);
 
1656
    if(ret == -1){
 
1657
      perror_plus("seteuid");
 
1658
    }
 
1659
  }
 
1660
  
 
1661
  /* Find network hooks and run them */
 
1662
  {
 
1663
    struct dirent **direntries;
 
1664
    struct dirent *direntry;
 
1665
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1666
                           alphasort);
 
1667
    if(numhooks == -1){
 
1668
      perror_plus("scandir");
1715
1669
    } else {
1716
 
      struct stat st;
1717
 
      
1718
 
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1719
 
        int seckey_fd = open(seckey, O_RDONLY);
1720
 
        if(seckey_fd == -1){
1721
 
          perror_plus("open");
1722
 
        } else {
1723
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1724
 
          if(ret == -1){
1725
 
            perror_plus("fstat");
1726
 
          } else {
1727
 
            if(S_ISREG(st.st_mode)
1728
 
               and st.st_uid == 0 and st.st_gid == 0){
1729
 
              ret = fchown(seckey_fd, uid, gid);
1730
 
              if(ret == -1){
1731
 
                perror_plus("fchown");
1732
 
              }
1733
 
            }
1734
 
          }
1735
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
1736
 
        }
1737
 
      }
1738
 
    
1739
 
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1740
 
        int pubkey_fd = open(pubkey, O_RDONLY);
1741
 
        if(pubkey_fd == -1){
1742
 
          perror_plus("open");
1743
 
        } else {
1744
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1745
 
          if(ret == -1){
1746
 
            perror_plus("fstat");
1747
 
          } else {
1748
 
            if(S_ISREG(st.st_mode)
1749
 
               and st.st_uid == 0 and st.st_gid == 0){
1750
 
              ret = fchown(pubkey_fd, uid, gid);
1751
 
              if(ret == -1){
1752
 
                perror_plus("fchown");
1753
 
              }
1754
 
            }
1755
 
          }
1756
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
1757
 
        }
1758
 
      }
1759
 
    
1760
 
      /* Lower privileges */
1761
 
      errno = 0;
1762
 
      ret = seteuid(uid);
1763
 
      if(ret == -1){
1764
 
        perror_plus("seteuid");
1765
 
      }
 
1670
      int devnull = open("/dev/null", O_RDONLY);
 
1671
      for(int i = 0; i < numhooks; i++){
 
1672
        direntry = direntries[0];
 
1673
        char *fullname = NULL;
 
1674
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1675
        if(ret < 0){
 
1676
          perror_plus("asprintf");
 
1677
          continue;
 
1678
        }
 
1679
        pid_t hook_pid = fork();
 
1680
        if(hook_pid == 0){
 
1681
          /* Child */
 
1682
          dup2(devnull, STDIN_FILENO);
 
1683
          close(devnull);
 
1684
          dup2(STDERR_FILENO, STDOUT_FILENO);
 
1685
          ret = setenv("DEVICE", interface, 1);
 
1686
          if(ret == -1){
 
1687
            perror_plus("setenv");
 
1688
            exit(1);
 
1689
          }
 
1690
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1691
          if(ret == -1){
 
1692
            perror_plus("setenv");
 
1693
            exit(1);
 
1694
          }
 
1695
          ret = setenv("MODE", "start", 1);
 
1696
          if(ret == -1){
 
1697
            perror_plus("setenv");
 
1698
            exit(1);
 
1699
          }
 
1700
          char *delaystring;
 
1701
          ret = asprintf(&delaystring, "%f", delay);
 
1702
          if(ret == -1){
 
1703
            perror_plus("asprintf");
 
1704
            exit(1);
 
1705
          }
 
1706
          ret = setenv("DELAY", delaystring, 1);
 
1707
          if(ret == -1){
 
1708
            free(delaystring);
 
1709
            perror_plus("setenv");
 
1710
            exit(1);
 
1711
          }
 
1712
          free(delaystring);
 
1713
          ret = execl(fullname, direntry->d_name, "start", NULL);
 
1714
          perror_plus("execl");
 
1715
        } else {
 
1716
          int status;
 
1717
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1718
            perror_plus("waitpid");
 
1719
            free(fullname);
 
1720
            continue;
 
1721
          }
 
1722
          if(WIFEXITED(status)){
 
1723
            if(WEXITSTATUS(status) != 0){
 
1724
              fprintf(stderr, "Mandos plugin mandos-client: "
 
1725
                      "Warning: network hook \"%s\" exited"
 
1726
                      " with status %d\n", direntry->d_name,
 
1727
                      WEXITSTATUS(status));
 
1728
              free(fullname);
 
1729
              continue;
 
1730
            }
 
1731
          } else if(WIFSIGNALED(status)){
 
1732
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1733
                    "Warning: network hook \"%s\" died by"
 
1734
                    " signal %d\n", direntry->d_name,
 
1735
                    WTERMSIG(status));
 
1736
            free(fullname);
 
1737
            continue;
 
1738
          } else {
 
1739
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1740
                    "Warning: network hook \"%s\" crashed\n",
 
1741
                    direntry->d_name);
 
1742
            free(fullname);
 
1743
            continue;
 
1744
          }
 
1745
        }
 
1746
        free(fullname);
 
1747
        if(quit_now){
 
1748
          goto end;
 
1749
        }
 
1750
      }
 
1751
      close(devnull);
1766
1752
    }
1767
1753
  }
1768
1754
  
1769
 
  /* Run network hooks */
1770
 
  if(not run_network_hooks("start", interface, delay)){
1771
 
    goto end;
1772
 
  }
1773
 
  
1774
1755
  if(not debug){
1775
1756
    avahi_set_log_function(empty_log);
1776
1757
  }
1790
1771
      /* Pick the first interface returned */
1791
1772
      interface = strdup(direntries[0]->d_name);
1792
1773
      if(debug){
1793
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1774
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1775
                "Using interface \"%s\"\n", interface);
1794
1776
      }
1795
1777
      if(interface == NULL){
1796
1778
        perror_plus("malloc");
1801
1783
      free(direntries);
1802
1784
    } else {
1803
1785
      free(direntries);
1804
 
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1786
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1787
              "Could not find a network interface\n");
1805
1788
      exitcode = EXIT_FAILURE;
1806
1789
      goto end;
1807
1790
    }
1813
1796
  srand((unsigned int) time(NULL));
1814
1797
  mc.simple_poll = avahi_simple_poll_new();
1815
1798
  if(mc.simple_poll == NULL){
1816
 
    fprintf_plus(stderr,
1817
 
                 "Avahi: Failed to create simple poll object.\n");
 
1799
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1800
            "Avahi: Failed to create simple poll object.\n");
1818
1801
    exitcode = EX_UNAVAILABLE;
1819
1802
    goto end;
1820
1803
  }
1886
1869
  if(strcmp(interface, "none") != 0){
1887
1870
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1888
1871
    if(if_index == 0){
1889
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1872
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1873
              "No such interface: \"%s\"\n", interface);
1890
1874
      exitcode = EX_UNAVAILABLE;
1891
1875
      goto end;
1892
1876
    }
2012
1996
#endif  /* __linux__ */
2013
1997
    /* Lower privileges */
2014
1998
    errno = 0;
2015
 
    /* Lower privileges */
2016
 
    ret = seteuid(uid);
2017
 
    if(ret == -1){
2018
 
      perror_plus("seteuid");
 
1999
    if(take_down_interface){
 
2000
      /* Lower privileges */
 
2001
      ret = seteuid(uid);
 
2002
      if(ret == -1){
 
2003
        perror_plus("seteuid");
 
2004
      }
 
2005
    } else {
 
2006
      /* Lower privileges permanently */
 
2007
      ret = setuid(uid);
 
2008
      if(ret == -1){
 
2009
        perror_plus("setuid");
 
2010
      }
2019
2011
    }
2020
2012
  }
2021
2013
  
2025
2017
  
2026
2018
  ret = init_gnutls_global(pubkey, seckey);
2027
2019
  if(ret == -1){
2028
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
2020
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2021
            "init_gnutls_global failed\n");
2029
2022
    exitcode = EX_UNAVAILABLE;
2030
2023
    goto end;
2031
2024
  } else {
2047
2040
  }
2048
2041
  
2049
2042
  if(not init_gpgme(pubkey, seckey, tempdir)){
2050
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
2043
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2044
            "init_gpgme failed\n");
2051
2045
    exitcode = EX_UNAVAILABLE;
2052
2046
    goto end;
2053
2047
  } else {
2063
2057
    /* (Mainly meant for debugging) */
2064
2058
    char *address = strrchr(connect_to, ':');
2065
2059
    if(address == NULL){
2066
 
      fprintf_plus(stderr, "No colon in address\n");
 
2060
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2061
              "No colon in address\n");
2067
2062
      exitcode = EX_USAGE;
2068
2063
      goto end;
2069
2064
    }
2077
2072
    tmpmax = strtoimax(address+1, &tmp, 10);
2078
2073
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2079
2074
       or tmpmax != (uint16_t)tmpmax){
2080
 
      fprintf_plus(stderr, "Bad port number\n");
 
2075
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2076
              "Bad port number\n");
2081
2077
      exitcode = EX_USAGE;
2082
2078
      goto end;
2083
2079
    }
2113
2109
        break;
2114
2110
      }
2115
2111
      if(debug){
2116
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2117
 
                     (int)retry_interval);
 
2112
        fprintf(stderr, "Mandos plugin mandos-client: "
 
2113
                "Retrying in %d seconds\n", (int)retry_interval);
2118
2114
      }
2119
2115
      sleep((int)retry_interval);
2120
2116
    }
2150
2146
  
2151
2147
  /* Check if creating the Avahi server object succeeded */
2152
2148
  if(mc.server == NULL){
2153
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2154
 
                 avahi_strerror(error));
 
2149
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2150
            "Failed to create Avahi server: %s\n",
 
2151
            avahi_strerror(error));
2155
2152
    exitcode = EX_UNAVAILABLE;
2156
2153
    goto end;
2157
2154
  }
2165
2162
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2166
2163
                                   NULL, 0, browse_callback, NULL);
2167
2164
  if(sb == NULL){
2168
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2169
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
2165
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2166
            "Failed to create service browser: %s\n",
 
2167
            avahi_strerror(avahi_server_errno(mc.server)));
2170
2168
    exitcode = EX_UNAVAILABLE;
2171
2169
    goto end;
2172
2170
  }
2178
2176
  /* Run the main loop */
2179
2177
  
2180
2178
  if(debug){
2181
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
2179
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2180
            "Starting Avahi loop search\n");
2182
2181
  }
2183
2182
 
2184
2183
  ret = avahi_loop_with_timeout(mc.simple_poll,
2185
2184
                                (int)(retry_interval * 1000));
2186
2185
  if(debug){
2187
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2188
 
                 (ret == 0) ? "successfully" : "with error");
 
2186
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2187
            "avahi_loop_with_timeout exited %s\n",
 
2188
            (ret == 0) ? "successfully" : "with error");
2189
2189
  }
2190
2190
  
2191
2191
 end:
2192
2192
  
2193
2193
  if(debug){
2194
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2194
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2195
            "%s exiting\n", argv[0]);
2195
2196
  }
2196
2197
  
2197
2198
  /* Cleanup things */
2213
2214
  if(gpgme_initialized){
2214
2215
    gpgme_release(mc.ctx);
2215
2216
  }
2216
 
  
 
2217
 
2217
2218
  /* Cleans up the circular linked list of Mandos servers the client
2218
2219
     has seen */
2219
2220
  if(mc.current_server != NULL){
2225
2226
    }
2226
2227
  }
2227
2228
  
2228
 
  /* Run network hooks */
2229
 
  run_network_hooks("stop", interface, delay);
 
2229
  /* XXX run network hooks "stop" here  */
2230
2230
  
2231
 
  /* Re-raise priviliges */
2232
 
  {
 
2231
  /* Take down the network interface */
 
2232
  if(take_down_interface){
 
2233
    /* Re-raise priviliges */
2233
2234
    errno = 0;
2234
2235
    ret = seteuid(0);
2235
2236
    if(ret == -1){
2236
2237
      perror_plus("seteuid");
2237
2238
    }
2238
 
    
2239
 
    /* Take down the network interface */
2240
 
    if(take_down_interface and geteuid() == 0){
 
2239
    if(geteuid() == 0){
2241
2240
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2242
2241
      if(ret == -1){
2243
2242
        perror_plus("ioctl SIOCGIFFLAGS");
2252
2251
      if(ret == -1){
2253
2252
        perror_plus("close");
2254
2253
      }
 
2254
      /* Lower privileges permanently */
 
2255
      errno = 0;
 
2256
      ret = setuid(uid);
 
2257
      if(ret == -1){
 
2258
        perror_plus("setuid");
 
2259
      }
2255
2260
    }
2256
2261
  }
2257
 
  /* Lower privileges permanently */
2258
 
  errno = 0;
2259
 
  ret = setuid(uid);
2260
 
  if(ret == -1){
2261
 
    perror_plus("setuid");
2262
 
  }
2263
2262
  
2264
2263
  /* Removes the GPGME temp directory and all files inside */
2265
2264
  if(tempdir_created){
2279
2278
        }
2280
2279
        ret = remove(fullname);
2281
2280
        if(ret == -1){
2282
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2283
 
                       strerror(errno));
 
2281
          fprintf(stderr, "Mandos plugin mandos-client: "
 
2282
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
2284
2283
        }
2285
2284
        free(fullname);
2286
2285
      }