/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: New directory.
* network-hooks.d/bridge: New example hook.
* network-hooks.d/bridge.conf: Config file for bridge example hook.

Show diffs side-by-side

added added

removed removed

Lines of Context:
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open() */
 
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
85
85
                                   raise() */
86
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
89
                                   WEXITSTATUS(), WTERMSIG() */
88
90
 
89
91
#ifdef __linux__
90
92
#include <sys/klog.h>           /* klogctl() */
108
110
                                   init_gnutls_session(),
109
111
                                   GNUTLS_* */
110
112
#include <gnutls/openpgp.h>
111
 
                          /* gnutls_certificate_set_openpgp_key_file(),
112
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
113
                         /* gnutls_certificate_set_openpgp_key_file(),
 
114
                            GNUTLS_OPENPGP_FMT_BASE64 */
113
115
 
114
116
/* GPGME */
115
117
#include <gpgme.h>              /* All GPGME types, constants and
131
133
const char *argp_program_bug_address = "<mandos@recompile.se>";
132
134
static const char sys_class_net[] = "/sys/class/net";
133
135
char *connect_to = NULL;
 
136
const char *hookdir = HOOKDIR;
134
137
 
135
138
/* Doubly linked list that need to be circularly linked when used */
136
139
typedef struct server{
175
178
  va_list ap;
176
179
  va_start (ap, format);
177
180
  
178
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", program_invocation_short_name));
 
181
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
182
                             program_invocation_short_name));
179
183
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
180
184
}
181
185
 
185
189
 * "buffer_length" is how much is already used.
186
190
 */
187
191
size_t incbuffer(char **buffer, size_t buffer_length,
188
 
                  size_t buffer_capacity){
 
192
                 size_t buffer_capacity){
189
193
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
190
194
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
191
195
    if(buffer == NULL){
197
201
}
198
202
 
199
203
/* Add server to set of servers to retry periodically */
200
 
int add_server(const char *ip, uint16_t port,
201
 
                 AvahiIfIndex if_index,
202
 
                 int af){
 
204
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
205
               int af){
203
206
  int ret;
204
207
  server *new_server = malloc(sizeof(server));
205
208
  if(new_server == NULL){
207
210
    return -1;
208
211
  }
209
212
  *new_server = (server){ .ip = strdup(ip),
210
 
                         .port = port,
211
 
                         .if_index = if_index,
212
 
                         .af = af };
 
213
                          .port = port,
 
214
                          .if_index = if_index,
 
215
                          .af = af };
213
216
  if(new_server->ip == NULL){
214
217
    perror_plus("strdup");
215
218
    return -1;
237
240
/* 
238
241
 * Initialize GPGME.
239
242
 */
240
 
static bool init_gpgme(const char *seckey,
241
 
                       const char *pubkey, const char *tempdir){
 
243
static bool init_gpgme(const char *seckey, const char *pubkey,
 
244
                       const char *tempdir){
242
245
  gpgme_error_t rc;
243
246
  gpgme_engine_info_t engine_info;
244
247
  
259
262
    
260
263
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
261
264
    if(rc != GPG_ERR_NO_ERROR){
262
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
263
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
265
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
266
                   gpgme_strsource(rc), gpgme_strerror(rc));
264
267
      return false;
265
268
    }
266
269
    
267
270
    rc = gpgme_op_import(mc.ctx, pgp_data);
268
271
    if(rc != GPG_ERR_NO_ERROR){
269
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
270
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
272
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
273
                   gpgme_strsource(rc), gpgme_strerror(rc));
271
274
      return false;
272
275
    }
273
276
    
280
283
  }
281
284
  
282
285
  if(debug){
283
 
    fprintf(stderr, "Initializing GPGME\n");
 
286
    fprintf_plus(stderr, "Initializing GPGME\n");
284
287
  }
285
288
  
286
289
  /* Init GPGME */
287
290
  gpgme_check_version(NULL);
288
291
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
289
292
  if(rc != GPG_ERR_NO_ERROR){
290
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
291
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
293
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
294
                 gpgme_strsource(rc), gpgme_strerror(rc));
292
295
    return false;
293
296
  }
294
297
  
295
298
  /* Set GPGME home directory for the OpenPGP engine only */
296
299
  rc = gpgme_get_engine_info(&engine_info);
297
300
  if(rc != GPG_ERR_NO_ERROR){
298
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
299
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
301
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
302
                 gpgme_strsource(rc), gpgme_strerror(rc));
300
303
    return false;
301
304
  }
302
305
  while(engine_info != NULL){
308
311
    engine_info = engine_info->next;
309
312
  }
310
313
  if(engine_info == NULL){
311
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
314
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
315
                 tempdir);
312
316
    return false;
313
317
  }
314
318
  
315
319
  /* Create new GPGME "context" */
316
320
  rc = gpgme_new(&(mc.ctx));
317
321
  if(rc != GPG_ERR_NO_ERROR){
318
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
319
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
322
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
323
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
324
                 gpgme_strerror(rc));
320
325
    return false;
321
326
  }
322
327
  
341
346
  ssize_t plaintext_length = 0;
342
347
  
343
348
  if(debug){
344
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
349
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
345
350
  }
346
351
  
347
352
  /* Create new GPGME data buffer from memory cryptotext */
348
353
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
349
354
                               0);
350
355
  if(rc != GPG_ERR_NO_ERROR){
351
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
352
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
356
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
357
                 gpgme_strsource(rc), gpgme_strerror(rc));
353
358
    return -1;
354
359
  }
355
360
  
356
361
  /* Create new empty GPGME data buffer for the plaintext */
357
362
  rc = gpgme_data_new(&dh_plain);
358
363
  if(rc != GPG_ERR_NO_ERROR){
359
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
360
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
364
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
365
                 "bad gpgme_data_new: %s: %s\n",
 
366
                 gpgme_strsource(rc), gpgme_strerror(rc));
361
367
    gpgme_data_release(dh_crypto);
362
368
    return -1;
363
369
  }
366
372
     data buffer */
367
373
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
368
374
  if(rc != GPG_ERR_NO_ERROR){
369
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
370
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
375
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
376
                 gpgme_strsource(rc), gpgme_strerror(rc));
371
377
    plaintext_length = -1;
372
378
    if(debug){
373
379
      gpgme_decrypt_result_t result;
374
380
      result = gpgme_op_decrypt_result(mc.ctx);
375
381
      if(result == NULL){
376
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
382
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
377
383
      } else {
378
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
379
 
                result->unsupported_algorithm);
380
 
        fprintf(stderr, "Wrong key usage: %u\n",
381
 
                result->wrong_key_usage);
 
384
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
385
                     result->unsupported_algorithm);
 
386
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
387
                     result->wrong_key_usage);
382
388
        if(result->file_name != NULL){
383
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
389
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
384
390
        }
385
391
        gpgme_recipient_t recipient;
386
392
        recipient = result->recipients;
387
393
        while(recipient != NULL){
388
 
          fprintf(stderr, "Public key algorithm: %s\n",
389
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
390
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
391
 
          fprintf(stderr, "Secret key available: %s\n",
392
 
                  recipient->status == GPG_ERR_NO_SECKEY
393
 
                  ? "No" : "Yes");
 
394
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
395
                       gpgme_pubkey_algo_name
 
396
                       (recipient->pubkey_algo));
 
397
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
398
          fprintf_plus(stderr, "Secret key available: %s\n",
 
399
                       recipient->status == GPG_ERR_NO_SECKEY
 
400
                       ? "No" : "Yes");
394
401
          recipient = recipient->next;
395
402
        }
396
403
      }
399
406
  }
400
407
  
401
408
  if(debug){
402
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
409
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
403
410
  }
404
411
  
405
412
  /* Seek back to the beginning of the GPGME plaintext data buffer */
412
419
  *plaintext = NULL;
413
420
  while(true){
414
421
    plaintext_capacity = incbuffer(plaintext,
415
 
                                      (size_t)plaintext_length,
416
 
                                      plaintext_capacity);
 
422
                                   (size_t)plaintext_length,
 
423
                                   plaintext_capacity);
417
424
    if(plaintext_capacity == 0){
418
 
        perror_plus("incbuffer");
419
 
        plaintext_length = -1;
420
 
        goto decrypt_end;
 
425
      perror_plus("incbuffer");
 
426
      plaintext_length = -1;
 
427
      goto decrypt_end;
421
428
    }
422
429
    
423
430
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
436
443
  }
437
444
  
438
445
  if(debug){
439
 
    fprintf(stderr, "Decrypted password is: ");
 
446
    fprintf_plus(stderr, "Decrypted password is: ");
440
447
    for(ssize_t i = 0; i < plaintext_length; i++){
441
448
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
442
449
    }
464
471
/* GnuTLS log function callback */
465
472
static void debuggnutls(__attribute__((unused)) int level,
466
473
                        const char* string){
467
 
  fprintf(stderr, "GnuTLS: %s", string);
 
474
  fprintf_plus(stderr, "GnuTLS: %s", string);
468
475
}
469
476
 
470
477
static int init_gnutls_global(const char *pubkeyfilename,
472
479
  int ret;
473
480
  
474
481
  if(debug){
475
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
482
    fprintf_plus(stderr, "Initializing GnuTLS\n");
476
483
  }
477
484
  
478
485
  ret = gnutls_global_init();
479
486
  if(ret != GNUTLS_E_SUCCESS){
480
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
481
 
            safer_gnutls_strerror(ret));
 
487
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
488
                 safer_gnutls_strerror(ret));
482
489
    return -1;
483
490
  }
484
491
  
493
500
  /* OpenPGP credentials */
494
501
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
495
502
  if(ret != GNUTLS_E_SUCCESS){
496
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
497
 
            safer_gnutls_strerror(ret));
 
503
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
504
                 safer_gnutls_strerror(ret));
498
505
    gnutls_global_deinit();
499
506
    return -1;
500
507
  }
501
508
  
502
509
  if(debug){
503
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
504
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
505
 
            seckeyfilename);
 
510
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
511
                 " secret key %s as GnuTLS credentials\n",
 
512
                 pubkeyfilename,
 
513
                 seckeyfilename);
506
514
  }
507
515
  
508
516
  ret = gnutls_certificate_set_openpgp_key_file
509
517
    (mc.cred, pubkeyfilename, seckeyfilename,
510
518
     GNUTLS_OPENPGP_FMT_BASE64);
511
519
  if(ret != GNUTLS_E_SUCCESS){
512
 
    fprintf(stderr,
513
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
514
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
515
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
516
 
            safer_gnutls_strerror(ret));
 
520
    fprintf_plus(stderr,
 
521
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
522
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
523
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
524
                 safer_gnutls_strerror(ret));
517
525
    goto globalfail;
518
526
  }
519
527
  
520
528
  /* GnuTLS server initialization */
521
529
  ret = gnutls_dh_params_init(&mc.dh_params);
522
530
  if(ret != GNUTLS_E_SUCCESS){
523
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
524
 
            " %s\n", safer_gnutls_strerror(ret));
 
531
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
532
                 " initialization: %s\n",
 
533
                 safer_gnutls_strerror(ret));
525
534
    goto globalfail;
526
535
  }
527
536
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
528
537
  if(ret != GNUTLS_E_SUCCESS){
529
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
530
 
            safer_gnutls_strerror(ret));
 
538
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
539
                 safer_gnutls_strerror(ret));
531
540
    goto globalfail;
532
541
  }
533
542
  
553
562
    }
554
563
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
555
564
  if(ret != GNUTLS_E_SUCCESS){
556
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
557
 
            safer_gnutls_strerror(ret));
 
565
    fprintf_plus(stderr,
 
566
                 "Error in GnuTLS session initialization: %s\n",
 
567
                 safer_gnutls_strerror(ret));
558
568
  }
559
569
  
560
570
  {
567
577
      }
568
578
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
569
579
    if(ret != GNUTLS_E_SUCCESS){
570
 
      fprintf(stderr, "Syntax error at: %s\n", err);
571
 
      fprintf(stderr, "GnuTLS error: %s\n",
572
 
              safer_gnutls_strerror(ret));
 
580
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
581
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
582
                   safer_gnutls_strerror(ret));
573
583
      gnutls_deinit(*session);
574
584
      return -1;
575
585
    }
584
594
    }
585
595
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
586
596
  if(ret != GNUTLS_E_SUCCESS){
587
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
588
 
            safer_gnutls_strerror(ret));
 
597
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
598
                 safer_gnutls_strerror(ret));
589
599
    gnutls_deinit(*session);
590
600
    return -1;
591
601
  }
636
646
    pf = PF_INET;
637
647
    break;
638
648
  default:
639
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
649
    fprintf_plus(stderr, "Bad address family: %d\n", af);
640
650
    errno = EINVAL;
641
651
    return -1;
642
652
  }
647
657
  }
648
658
  
649
659
  if(debug){
650
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
651
 
            "\n", ip, port);
 
660
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
661
                 PRIu16 "\n", ip, port);
652
662
  }
653
663
  
654
664
  tcp_sd = socket(pf, SOCK_STREAM, 0);
680
690
  }
681
691
  if(ret == 0){
682
692
    int e = errno;
683
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
693
    fprintf_plus(stderr, "Bad address: %s\n", ip);
684
694
    errno = e;
685
695
    goto mandos_end;
686
696
  }
691
701
    
692
702
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
693
703
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
694
 
                              -Wunreachable-code*/
 
704
                                -Wunreachable-code*/
695
705
      if(if_index == AVAHI_IF_UNSPEC){
696
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
697
 
                " without a network interface\n");
 
706
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
707
                     " incomplete without a network interface\n");
698
708
        errno = EINVAL;
699
709
        goto mandos_end;
700
710
      }
718
728
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
719
729
        perror_plus("if_indextoname");
720
730
      } else {
721
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
722
 
                ip, interface, port);
 
731
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
732
                     "\n", ip, interface, port);
723
733
      }
724
734
    } else {
725
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
726
 
              port);
 
735
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
736
                   ip, port);
727
737
    }
728
738
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
729
739
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
739
749
      perror_plus("inet_ntop");
740
750
    } else {
741
751
      if(strcmp(addrstr, ip) != 0){
742
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
752
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
743
753
      }
744
754
    }
745
755
  }
773
783
  while(true){
774
784
    size_t out_size = strlen(out);
775
785
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
776
 
                                   out_size - written));
 
786
                                        out_size - written));
777
787
    if(ret == -1){
778
788
      int e = errno;
779
789
      perror_plus("write");
799
809
  }
800
810
  
801
811
  if(debug){
802
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
812
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
803
813
  }
804
814
  
805
815
  if(quit_now){
825
835
  
826
836
  if(ret != GNUTLS_E_SUCCESS){
827
837
    if(debug){
828
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
838
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
829
839
      gnutls_perror(ret);
830
840
    }
831
841
    errno = EPROTO;
835
845
  /* Read OpenPGP packet that contains the wanted password */
836
846
  
837
847
  if(debug){
838
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
839
 
            ip);
 
848
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
849
                 " %s\n", ip);
840
850
  }
841
851
  
842
852
  while(true){
847
857
    }
848
858
    
849
859
    buffer_capacity = incbuffer(&buffer, buffer_length,
850
 
                                   buffer_capacity);
 
860
                                buffer_capacity);
851
861
    if(buffer_capacity == 0){
852
862
      int e = errno;
853
863
      perror_plus("incbuffer");
880
890
          }
881
891
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
882
892
        if(ret < 0){
883
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
893
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
894
                       "***\n");
884
895
          gnutls_perror(ret);
885
896
          errno = EPROTO;
886
897
          goto mandos_end;
887
898
        }
888
899
        break;
889
900
      default:
890
 
        fprintf(stderr, "Unknown error while reading data from"
891
 
                " encrypted session with Mandos server\n");
 
901
        fprintf_plus(stderr, "Unknown error while reading data from"
 
902
                     " encrypted session with Mandos server\n");
892
903
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
893
904
        errno = EIO;
894
905
        goto mandos_end;
899
910
  }
900
911
  
901
912
  if(debug){
902
 
    fprintf(stderr, "Closing TLS session\n");
 
913
    fprintf_plus(stderr, "Closing TLS session\n");
903
914
  }
904
915
  
905
916
  if(quit_now){
917
928
  
918
929
  if(buffer_length > 0){
919
930
    ssize_t decrypted_buffer_size;
920
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
921
 
                                               buffer_length,
 
931
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
922
932
                                               &decrypted_buffer);
923
933
    if(decrypted_buffer_size >= 0){
924
934
      
935
945
        if(ret == 0 and ferror(stdout)){
936
946
          int e = errno;
937
947
          if(debug){
938
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
939
 
                    strerror(errno));
 
948
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
949
                         strerror(errno));
940
950
          }
941
951
          errno = e;
942
952
          goto mandos_end;
999
1009
  switch(event){
1000
1010
  default:
1001
1011
  case AVAHI_RESOLVER_FAILURE:
1002
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
1003
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1004
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1012
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1013
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1014
                 domain,
 
1015
                 avahi_strerror(avahi_server_errno(mc.server)));
1005
1016
    break;
1006
1017
    
1007
1018
  case AVAHI_RESOLVER_FOUND:
1009
1020
      char ip[AVAHI_ADDRESS_STR_MAX];
1010
1021
      avahi_address_snprint(ip, sizeof(ip), address);
1011
1022
      if(debug){
1012
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1013
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1014
 
                ip, (intmax_t)interface, port);
 
1023
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1024
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1025
                     host_name, ip, (intmax_t)interface, port);
1015
1026
      }
1016
1027
      int ret = start_mandos_communication(ip, port, interface,
1017
1028
                                           avahi_proto_to_af(proto));
1049
1060
  default:
1050
1061
  case AVAHI_BROWSER_FAILURE:
1051
1062
    
1052
 
    fprintf(stderr, "(Avahi browser) %s\n",
1053
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1063
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1064
                 avahi_strerror(avahi_server_errno(mc.server)));
1054
1065
    avahi_simple_poll_quit(mc.simple_poll);
1055
1066
    return;
1056
1067
    
1063
1074
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1064
1075
                                    name, type, domain, protocol, 0,
1065
1076
                                    resolve_callback, NULL) == NULL)
1066
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1067
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1077
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1078
                   " %s\n", name,
 
1079
                   avahi_strerror(avahi_server_errno(mc.server)));
1068
1080
    break;
1069
1081
    
1070
1082
  case AVAHI_BROWSER_REMOVE:
1073
1085
  case AVAHI_BROWSER_ALL_FOR_NOW:
1074
1086
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1075
1087
    if(debug){
1076
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1088
      fprintf_plus(stderr, "No Mandos server found, still"
 
1089
                   " searching...\n");
1077
1090
    }
1078
1091
    break;
1079
1092
  }
1118
1131
  /* Reject the loopback device */
1119
1132
  if(ifr->ifr_flags & IFF_LOOPBACK){
1120
1133
    if(debug){
1121
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1122
 
              ifname);
 
1134
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1135
                   ifname);
1123
1136
    }
1124
1137
    return false;
1125
1138
  }
1126
1139
  /* Accept point-to-point devices only if connect_to is specified */
1127
1140
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1128
1141
    if(debug){
1129
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1130
 
              ifname);
 
1142
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1143
                   " \"%s\"\n", ifname);
1131
1144
    }
1132
1145
    return true;
1133
1146
  }
1134
1147
  /* Otherwise, reject non-broadcast-capable devices */
1135
1148
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1136
1149
    if(debug){
1137
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1138
 
              ifname);
 
1150
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1151
                   " \"%s\"\n", ifname);
1139
1152
    }
1140
1153
    return false;
1141
1154
  }
1142
1155
  /* Reject non-ARP interfaces (including dummy interfaces) */
1143
1156
  if(ifr->ifr_flags & IFF_NOARP){
1144
1157
    if(debug){
1145
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1158
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1159
                   ifname);
1146
1160
    }
1147
1161
    return false;
1148
1162
  }
1149
1163
  
1150
1164
  /* Accept this device */
1151
1165
  if(debug){
1152
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
 
1166
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1153
1167
  }
1154
1168
  return true;
1155
1169
}
1160
1174
 * (This function is passed to scandir(3) as a filter function.)
1161
1175
 */
1162
1176
int good_interface(const struct dirent *if_entry){
1163
 
  int ret;
1164
1177
  if(if_entry->d_name[0] == '.'){
1165
1178
    return 0;
1166
1179
  }
 
1180
  
1167
1181
  struct ifreq ifr;
1168
 
 
1169
1182
  if(not get_flags(if_entry->d_name, &ifr)){
 
1183
    if(debug){
 
1184
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1185
                   "\"%s\"\n", if_entry->d_name);
 
1186
    }
1170
1187
    return 0;
1171
1188
  }
1172
1189
  
1182
1199
 * (This function is passed to scandir(3) as a filter function.)
1183
1200
 */
1184
1201
int up_interface(const struct dirent *if_entry){
1185
 
  ssize_t ssret;
1186
 
  char *flagname = NULL;
1187
1202
  if(if_entry->d_name[0] == '.'){
1188
1203
    return 0;
1189
1204
  }
1190
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1191
 
                     if_entry->d_name);
1192
 
  if(ret < 0){
1193
 
    perror_plus("asprintf");
1194
 
    return 0;
1195
 
  }
1196
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1197
 
  if(flags_fd == -1){
1198
 
    perror_plus("open");
1199
 
    free(flagname);
1200
 
    return 0;
1201
 
  }
1202
 
  free(flagname);
1203
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1204
 
  /* read line from flags_fd */
1205
 
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
1206
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1207
 
  flagstring[(size_t)to_read] = '\0';
1208
 
  if(flagstring == NULL){
1209
 
    perror_plus("malloc");
1210
 
    close(flags_fd);
1211
 
    return 0;
1212
 
  }
1213
 
  while(to_read > 0){
1214
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1215
 
                                             (size_t)to_read));
1216
 
    if(ssret == -1){
1217
 
      perror_plus("read");
1218
 
      free(flagstring);
1219
 
      close(flags_fd);
1220
 
      return 0;
1221
 
    }
1222
 
    to_read -= ssret;
1223
 
    if(ssret == 0){
1224
 
      break;
1225
 
    }
1226
 
  }
1227
 
  close(flags_fd);
1228
 
  intmax_t tmpmax;
1229
 
  char *tmp;
1230
 
  errno = 0;
1231
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1232
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1233
 
                                         and not (isspace(*tmp)))
1234
 
     or tmpmax != (ifreq_flags)tmpmax){
1235
 
    if(debug){
1236
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1237
 
              flagstring, if_entry->d_name);
1238
 
    }
1239
 
    free(flagstring);
1240
 
    return 0;
1241
 
  }
1242
 
  free(flagstring);
1243
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
1244
 
  /* Reject the loopback device */
1245
 
  if(flags & IFF_LOOPBACK){
1246
 
    if(debug){
1247
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1248
 
              if_entry->d_name);
1249
 
    }
1250
 
    return 0;
1251
 
  }
1252
 
 
 
1205
  
 
1206
  struct ifreq ifr;
 
1207
  if(not get_flags(if_entry->d_name, &ifr)){
 
1208
    if(debug){
 
1209
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1210
                   "\"%s\"\n", if_entry->d_name);
 
1211
    }
 
1212
    return 0;
 
1213
  }
 
1214
  
1253
1215
  /* Reject down interfaces */
1254
 
  if(not (flags & IFF_UP)){
1255
 
    return 0;
1256
 
  }
1257
 
  
1258
 
  /* Accept point-to-point devices only if connect_to is specified */
1259
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1260
 
    if(debug){
1261
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1262
 
              if_entry->d_name);
1263
 
    }
1264
 
    return 1;
1265
 
  }
1266
 
  /* Otherwise, reject non-broadcast-capable devices */
1267
 
  if(not (flags & IFF_BROADCAST)){
1268
 
    if(debug){
1269
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1270
 
              if_entry->d_name);
1271
 
    }
1272
 
    return 0;
1273
 
  }
1274
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1275
 
  if(flags & IFF_NOARP){
1276
 
    if(debug){
1277
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1278
 
              if_entry->d_name);
1279
 
    }
1280
 
    return 0;
1281
 
  }
1282
 
  /* Accept this device */
1283
 
  if(debug){
1284
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1285
 
            if_entry->d_name);
 
1216
  if(not (ifr.ifr_flags & IFF_UP)){
 
1217
    if(debug){
 
1218
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1219
                   if_entry->d_name);
 
1220
    }
 
1221
    return 0;
 
1222
  }
 
1223
  
 
1224
  /* Reject non-running interfaces */
 
1225
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1226
    if(debug){
 
1227
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1228
                   if_entry->d_name);
 
1229
    }
 
1230
    return 0;
 
1231
  }
 
1232
  
 
1233
  if(not good_flags(if_entry->d_name, &ifr)){
 
1234
    return 0;
1286
1235
  }
1287
1236
  return 1;
1288
1237
}
1301
1250
/* Is this directory entry a runnable program? */
1302
1251
int runnable_hook(const struct dirent *direntry){
1303
1252
  int ret;
 
1253
  size_t sret;
1304
1254
  struct stat st;
1305
1255
  
1306
1256
  if((direntry->d_name)[0] == '\0'){
1308
1258
    return 0;
1309
1259
  }
1310
1260
  
1311
 
  /* Save pointer to last character */
1312
 
  char *end = strchr(direntry->d_name, '\0')-1;
1313
 
  
1314
 
  if(*end == '~'){
1315
 
    /* Backup name~ */
1316
 
    return 0;
1317
 
  }
1318
 
  
1319
 
  if(((direntry->d_name)[0] == '#')
1320
 
     and (*end == '#')){
1321
 
    /* Temporary #name# */
1322
 
    return 0;
1323
 
  }
1324
 
  
1325
 
  /* XXX more rules here */
1326
 
  
1327
 
  ret = stat(direntry->d_name, &st);
 
1261
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1262
                "abcdefghijklmnopqrstuvwxyz"
 
1263
                "0123456789"
 
1264
                "_-");
 
1265
  if((direntry->d_name)[sret] != '\0'){
 
1266
    /* Contains non-allowed characters */
 
1267
    if(debug){
 
1268
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1269
                   direntry->d_name);
 
1270
    }
 
1271
    return 0;
 
1272
  }
 
1273
  
 
1274
  char *fullname = NULL;
 
1275
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1276
  if(ret < 0){
 
1277
    perror_plus("asprintf");
 
1278
    return 0;
 
1279
  }
 
1280
  
 
1281
  ret = stat(fullname, &st);
1328
1282
  if(ret == -1){
1329
1283
    if(debug){
1330
 
      perror_plus("Could not stat plugin");
 
1284
      perror_plus("Could not stat hook");
1331
1285
    }
1332
1286
    return 0;
1333
1287
  }
1334
 
  if(not (st.st_mode & S_ISREG)){
 
1288
  if(not (S_ISREG(st.st_mode))){
1335
1289
    /* Not a regular file */
 
1290
    if(debug){
 
1291
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1292
                   direntry->d_name);
 
1293
    }
1336
1294
    return 0;
1337
1295
  }
1338
1296
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1339
1297
    /* Not executable */
 
1298
    if(debug){
 
1299
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1300
                   direntry->d_name);
 
1301
    }
1340
1302
    return 0;
1341
1303
  }
1342
1304
  return 1;
1351
1313
  while(true){
1352
1314
    if(mc.current_server == NULL){
1353
1315
      if (debug){
1354
 
        fprintf(stderr,
1355
 
                "Wait until first server is found. No timeout!\n");
 
1316
        fprintf_plus(stderr, "Wait until first server is found."
 
1317
                     " No timeout!\n");
1356
1318
      }
1357
1319
      ret = avahi_simple_poll_iterate(s, -1);
1358
1320
    } else {
1359
1321
      if (debug){
1360
 
        fprintf(stderr, "Check current_server if we should run it,"
1361
 
                " or wait\n");
 
1322
        fprintf_plus(stderr, "Check current_server if we should run"
 
1323
                     " it, or wait\n");
1362
1324
      }
1363
1325
      /* the current time */
1364
1326
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1380
1342
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1381
1343
      
1382
1344
      if (debug){
1383
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1345
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1346
                     block_time);
1384
1347
      }
1385
1348
      
1386
1349
      if(block_time <= 0){
1406
1369
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1407
1370
    }
1408
1371
    if(ret != 0){
1409
 
      if (ret > 0 or errno != EINTR) {
 
1372
      if (ret > 0 or errno != EINTR){
1410
1373
        return (ret != 1) ? ret : 0;
1411
1374
      }
1412
1375
    }
1413
1376
  }
1414
1377
}
1415
1378
 
 
1379
bool run_network_hooks(const char *mode, const char *interface,
 
1380
                       const float delay){
 
1381
  struct dirent **direntries;
 
1382
  struct dirent *direntry;
 
1383
  int ret;
 
1384
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1385
                         alphasort);
 
1386
  if(numhooks == -1){
 
1387
    perror_plus("scandir");
 
1388
  } else {
 
1389
    int devnull = open("/dev/null", O_RDONLY);
 
1390
    for(int i = 0; i < numhooks; i++){
 
1391
      direntry = direntries[0];
 
1392
      char *fullname = NULL;
 
1393
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1394
      if(ret < 0){
 
1395
        perror_plus("asprintf");
 
1396
        continue;
 
1397
      }
 
1398
      pid_t hook_pid = fork();
 
1399
      if(hook_pid == 0){
 
1400
        /* Child */
 
1401
        dup2(devnull, STDIN_FILENO);
 
1402
        close(devnull);
 
1403
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1404
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1405
        if(ret == -1){
 
1406
          perror_plus("setenv");
 
1407
          return false;
 
1408
        }
 
1409
        ret = setenv("DEVICE", interface, 1);
 
1410
        if(ret == -1){
 
1411
          perror_plus("setenv");
 
1412
          return false;
 
1413
        }
 
1414
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1415
        if(ret == -1){
 
1416
          perror_plus("setenv");
 
1417
          return false;
 
1418
        }
 
1419
        ret = setenv("MODE", mode, 1);
 
1420
        if(ret == -1){
 
1421
          perror_plus("setenv");
 
1422
          return false;
 
1423
        }
 
1424
        char *delaystring;
 
1425
        ret = asprintf(&delaystring, "%f", delay);
 
1426
        if(ret == -1){
 
1427
          perror_plus("asprintf");
 
1428
          return false;
 
1429
        }
 
1430
        ret = setenv("DELAY", delaystring, 1);
 
1431
        if(ret == -1){
 
1432
          free(delaystring);
 
1433
          perror_plus("setenv");
 
1434
          return false;
 
1435
        }
 
1436
        free(delaystring);
 
1437
        ret = execl(fullname, direntry->d_name, mode, NULL);
 
1438
        perror_plus("execl");
 
1439
      } else {
 
1440
        int status;
 
1441
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1442
          perror_plus("waitpid");
 
1443
          free(fullname);
 
1444
          continue;
 
1445
        }
 
1446
        if(WIFEXITED(status)){
 
1447
          if(WEXITSTATUS(status) != 0){
 
1448
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1449
                         " with status %d\n", direntry->d_name,
 
1450
                         WEXITSTATUS(status));
 
1451
            free(fullname);
 
1452
            continue;
 
1453
          }
 
1454
        } else if(WIFSIGNALED(status)){
 
1455
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1456
                       " signal %d\n", direntry->d_name,
 
1457
                       WTERMSIG(status));
 
1458
          free(fullname);
 
1459
          continue;
 
1460
        } else {
 
1461
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1462
                       " crashed\n", direntry->d_name);
 
1463
          free(fullname);
 
1464
          continue;
 
1465
        }
 
1466
      }
 
1467
      free(fullname);
 
1468
      if(quit_now){
 
1469
        break;
 
1470
      }
 
1471
    }
 
1472
    close(devnull);
 
1473
  }
 
1474
  return true;
 
1475
}
 
1476
 
1416
1477
int main(int argc, char *argv[]){
1417
1478
  AvahiSServiceBrowser *sb = NULL;
1418
1479
  int error;
1500
1561
        .arg = "SECONDS",
1501
1562
        .doc = "Retry interval used when denied by the mandos server",
1502
1563
        .group = 2 },
 
1564
      { .name = "network-hook-dir", .key = 133,
 
1565
        .arg = "DIR",
 
1566
        .doc = "Directory where network hooks are located",
 
1567
        .group = 2 },
1503
1568
      /*
1504
1569
       * These reproduce what we would get without ARGP_NO_HELP
1505
1570
       */
1558
1623
          argp_error(state, "Bad retry interval");
1559
1624
        }
1560
1625
        break;
 
1626
      case 133:                 /* --network-hook-dir */
 
1627
        hookdir = arg;
 
1628
        break;
1561
1629
        /*
1562
1630
         * These reproduce what we would get without ARGP_NO_HELP
1563
1631
         */
1569
1637
        argp_state_help(state, state->out_stream,
1570
1638
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1571
1639
      case 'V':                 /* --version */
1572
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1640
        fprintf_plus(state->out_stream,
 
1641
                     "Mandos plugin mandos-client: ");
 
1642
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1573
1643
        exit(argp_err_exit_status);
1574
1644
        break;
1575
1645
      default:
1620
1690
        if(ret == -1){
1621
1691
          perror_plus("fstat");
1622
1692
        } else {
1623
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1693
          if(S_ISREG(st.st_mode)
 
1694
             and st.st_uid == 0 and st.st_gid == 0){
1624
1695
            ret = fchown(seckey_fd, uid, gid);
1625
1696
            if(ret == -1){
1626
1697
              perror_plus("fchown");
1640
1711
        if(ret == -1){
1641
1712
          perror_plus("fstat");
1642
1713
        } else {
1643
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1714
          if(S_ISREG(st.st_mode)
 
1715
             and st.st_uid == 0 and st.st_gid == 0){
1644
1716
            ret = fchown(pubkey_fd, uid, gid);
1645
1717
            if(ret == -1){
1646
1718
              perror_plus("fchown");
1659
1731
    }
1660
1732
  }
1661
1733
  
1662
 
  /* Find network hooks and run them */
 
1734
  /* Run network hooks */
1663
1735
  {
1664
 
    struct dirent **direntries;
1665
 
    struct dirent *direntry;
1666
 
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
1667
 
                           alphasort);
1668
 
    int devnull = open("/dev/null", O_RDONLY);
1669
 
    for(int i = 0; i < numhooks; i++){
1670
 
      direntry = direntries[0];
1671
 
      char *fullname = NULL;
1672
 
      ret = asprintf(&fullname, "%s/%s", tempdir,
1673
 
                     direntry->d_name);
1674
 
      if(ret < 0){
1675
 
        perror_plus("asprintf");
1676
 
        continue;
1677
 
      }
1678
 
      pid_t hook_pid = fork();
1679
 
      if(hook_pid == 0){
1680
 
        /* Child */
1681
 
        dup2(devnull, STDIN_FILENO);
1682
 
        close(devnull);
1683
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1684
 
        setenv("DEVICE", interface, 1);
1685
 
        setenv("VERBOSE", debug ? "1" : "0", 1);
1686
 
        setenv("MODE", "start", 1);
1687
 
        /* setenv( XXX more here */
1688
 
        ret = execl(fullname, direntry->d_name, "start");
1689
 
        perror_plus("execl");
1690
 
      }
1691
 
      free(fullname);
1692
 
      if(quit_now){
1693
 
        goto end;
1694
 
      }
1695
 
    }
1696
 
    close(devnull);
 
1736
    /* Re-raise priviliges */
 
1737
    errno = 0;
 
1738
    ret = seteuid(0);
 
1739
    if(ret == -1){
 
1740
      perror_plus("seteuid");
 
1741
    }
 
1742
    if(not run_network_hooks("start", interface, delay)){
 
1743
      goto end;
 
1744
    }
 
1745
    /* Lower privileges */
 
1746
    errno = 0;
 
1747
    ret = seteuid(uid);
 
1748
    if(ret == -1){
 
1749
      perror_plus("seteuid");
 
1750
    }
1697
1751
  }
1698
1752
  
1699
1753
  if(not debug){
1702
1756
  
1703
1757
  if(interface[0] == '\0'){
1704
1758
    struct dirent **direntries;
1705
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1759
    /* First look for interfaces that are up */
 
1760
    ret = scandir(sys_class_net, &direntries, up_interface,
1706
1761
                  alphasort);
 
1762
    if(ret == 0){
 
1763
      /* No up interfaces, look for any good interfaces */
 
1764
      free(direntries);
 
1765
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1766
                    alphasort);
 
1767
    }
1707
1768
    if(ret >= 1){
1708
 
      /* Pick the first good interface */
 
1769
      /* Pick the first interface returned */
1709
1770
      interface = strdup(direntries[0]->d_name);
1710
1771
      if(debug){
1711
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1772
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1712
1773
      }
1713
1774
      if(interface == NULL){
1714
1775
        perror_plus("malloc");
1719
1780
      free(direntries);
1720
1781
    } else {
1721
1782
      free(direntries);
1722
 
      fprintf(stderr, "Could not find a network interface\n");
 
1783
      fprintf_plus(stderr, "Could not find a network interface\n");
1723
1784
      exitcode = EXIT_FAILURE;
1724
1785
      goto end;
1725
1786
    }
1731
1792
  srand((unsigned int) time(NULL));
1732
1793
  mc.simple_poll = avahi_simple_poll_new();
1733
1794
  if(mc.simple_poll == NULL){
1734
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1795
    fprintf_plus(stderr,
 
1796
                 "Avahi: Failed to create simple poll object.\n");
1735
1797
    exitcode = EX_UNAVAILABLE;
1736
1798
    goto end;
1737
1799
  }
1803
1865
  if(strcmp(interface, "none") != 0){
1804
1866
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1805
1867
    if(if_index == 0){
1806
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1868
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1807
1869
      exitcode = EX_UNAVAILABLE;
1808
1870
      goto end;
1809
1871
    }
1929
1991
#endif  /* __linux__ */
1930
1992
    /* Lower privileges */
1931
1993
    errno = 0;
1932
 
    if(take_down_interface){
1933
 
      /* Lower privileges */
1934
 
      ret = seteuid(uid);
1935
 
      if(ret == -1){
1936
 
        perror_plus("seteuid");
1937
 
      }
1938
 
    } else {
1939
 
      /* Lower privileges permanently */
1940
 
      ret = setuid(uid);
1941
 
      if(ret == -1){
1942
 
        perror_plus("setuid");
1943
 
      }
 
1994
    /* Lower privileges */
 
1995
    ret = seteuid(uid);
 
1996
    if(ret == -1){
 
1997
      perror_plus("seteuid");
1944
1998
    }
1945
1999
  }
1946
2000
  
1950
2004
  
1951
2005
  ret = init_gnutls_global(pubkey, seckey);
1952
2006
  if(ret == -1){
1953
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2007
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1954
2008
    exitcode = EX_UNAVAILABLE;
1955
2009
    goto end;
1956
2010
  } else {
1972
2026
  }
1973
2027
  
1974
2028
  if(not init_gpgme(pubkey, seckey, tempdir)){
1975
 
    fprintf(stderr, "init_gpgme failed\n");
 
2029
    fprintf_plus(stderr, "init_gpgme failed\n");
1976
2030
    exitcode = EX_UNAVAILABLE;
1977
2031
    goto end;
1978
2032
  } else {
1988
2042
    /* (Mainly meant for debugging) */
1989
2043
    char *address = strrchr(connect_to, ':');
1990
2044
    if(address == NULL){
1991
 
      fprintf(stderr, "No colon in address\n");
 
2045
      fprintf_plus(stderr, "No colon in address\n");
1992
2046
      exitcode = EX_USAGE;
1993
2047
      goto end;
1994
2048
    }
2002
2056
    tmpmax = strtoimax(address+1, &tmp, 10);
2003
2057
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2004
2058
       or tmpmax != (uint16_t)tmpmax){
2005
 
      fprintf(stderr, "Bad port number\n");
 
2059
      fprintf_plus(stderr, "Bad port number\n");
2006
2060
      exitcode = EX_USAGE;
2007
2061
      goto end;
2008
2062
    }
2038
2092
        break;
2039
2093
      }
2040
2094
      if(debug){
2041
 
        fprintf(stderr, "Retrying in %d seconds\n",
2042
 
                (int)retry_interval);
 
2095
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2096
                     (int)retry_interval);
2043
2097
      }
2044
2098
      sleep((int)retry_interval);
2045
2099
    }
2075
2129
  
2076
2130
  /* Check if creating the Avahi server object succeeded */
2077
2131
  if(mc.server == NULL){
2078
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2079
 
            avahi_strerror(error));
 
2132
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2133
                 avahi_strerror(error));
2080
2134
    exitcode = EX_UNAVAILABLE;
2081
2135
    goto end;
2082
2136
  }
2090
2144
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2091
2145
                                   NULL, 0, browse_callback, NULL);
2092
2146
  if(sb == NULL){
2093
 
    fprintf(stderr, "Failed to create service browser: %s\n",
2094
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2147
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2148
                 avahi_strerror(avahi_server_errno(mc.server)));
2095
2149
    exitcode = EX_UNAVAILABLE;
2096
2150
    goto end;
2097
2151
  }
2103
2157
  /* Run the main loop */
2104
2158
  
2105
2159
  if(debug){
2106
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2160
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2107
2161
  }
2108
2162
 
2109
2163
  ret = avahi_loop_with_timeout(mc.simple_poll,
2110
2164
                                (int)(retry_interval * 1000));
2111
2165
  if(debug){
2112
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2113
 
            (ret == 0) ? "successfully" : "with error");
 
2166
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2167
                 (ret == 0) ? "successfully" : "with error");
2114
2168
  }
2115
2169
  
2116
2170
 end:
2117
2171
  
2118
2172
  if(debug){
2119
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2173
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2120
2174
  }
2121
2175
  
2122
2176
  /* Cleanup things */
2150
2204
    }
2151
2205
  }
2152
2206
  
2153
 
  /* XXX run network hooks "stop" here  */
2154
 
  
2155
 
  /* Take down the network interface */
2156
 
  if(take_down_interface){
2157
 
    /* Re-raise priviliges */
 
2207
  /* Re-raise priviliges */
 
2208
  {
2158
2209
    errno = 0;
2159
2210
    ret = seteuid(0);
2160
2211
    if(ret == -1){
2161
2212
      perror_plus("seteuid");
2162
2213
    }
2163
 
    if(geteuid() == 0){
 
2214
    /* Run network hooks */
 
2215
    if(not run_network_hooks("stop", interface, delay)){
 
2216
      goto end;
 
2217
    }
 
2218
    
 
2219
    /* Take down the network interface */
 
2220
    if(take_down_interface and geteuid() == 0){
2164
2221
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2165
2222
      if(ret == -1){
2166
2223
        perror_plus("ioctl SIOCGIFFLAGS");
2167
 
      } else if(network.ifr_flags & IFF_UP) {
 
2224
      } else if(network.ifr_flags & IFF_UP){
2168
2225
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2169
2226
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2170
2227
        if(ret == -1){
2175
2232
      if(ret == -1){
2176
2233
        perror_plus("close");
2177
2234
      }
2178
 
      /* Lower privileges permanently */
2179
 
      errno = 0;
2180
 
      ret = setuid(uid);
2181
 
      if(ret == -1){
2182
 
        perror_plus("setuid");
2183
 
      }
2184
2235
    }
2185
2236
  }
 
2237
  /* Lower privileges permanently */
 
2238
  errno = 0;
 
2239
  ret = setuid(uid);
 
2240
  if(ret == -1){
 
2241
    perror_plus("setuid");
 
2242
  }
2186
2243
  
2187
2244
  /* Removes the GPGME temp directory and all files inside */
2188
2245
  if(tempdir_created){
2202
2259
        }
2203
2260
        ret = remove(fullname);
2204
2261
        if(ret == -1){
2205
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2206
 
                  strerror(errno));
 
2262
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2263
                       strerror(errno));
2207
2264
        }
2208
2265
        free(fullname);
2209
2266
      }