/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

* network-hooks.d/bridge: Bug fix - really find brctl.

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