/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

Intermediate commit - this does *not* work yet.

* plugins.d/mandos-client.c (HOOKDIR): New.
  (up_interface): New.
  (runnable_hook): New.
  (main): Run network hooks with "start" argument.

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(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
85
85
                                   raise() */
86
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
90
88
 
91
89
#ifdef __linux__
92
90
#include <sys/klog.h>           /* klogctl() */
110
108
                                   init_gnutls_session(),
111
109
                                   GNUTLS_* */
112
110
#include <gnutls/openpgp.h>
113
 
                         /* gnutls_certificate_set_openpgp_key_file(),
114
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
111
                          /* gnutls_certificate_set_openpgp_key_file(),
 
112
                                   GNUTLS_OPENPGP_FMT_BASE64 */
115
113
 
116
114
/* GPGME */
117
115
#include <gpgme.h>              /* All GPGME types, constants and
133
131
const char *argp_program_bug_address = "<mandos@recompile.se>";
134
132
static const char sys_class_net[] = "/sys/class/net";
135
133
char *connect_to = NULL;
136
 
const char *hookdir = HOOKDIR;
137
134
 
138
135
/* Doubly linked list that need to be circularly linked when used */
139
136
typedef struct server{
174
171
  perror(print_text);
175
172
}
176
173
 
177
 
int fprintf_plus(FILE *stream, const char *format, ...){
178
 
  va_list ap;
179
 
  va_start (ap, format);
180
 
  
181
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
182
 
                             program_invocation_short_name));
183
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
184
 
}
185
 
 
186
174
/*
187
175
 * Make additional room in "buffer" for at least BUFFER_SIZE more
188
176
 * bytes. "buffer_capacity" is how much is currently allocated,
189
177
 * "buffer_length" is how much is already used.
190
178
 */
191
179
size_t incbuffer(char **buffer, size_t buffer_length,
192
 
                 size_t buffer_capacity){
 
180
                  size_t buffer_capacity){
193
181
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
194
182
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
195
183
    if(buffer == NULL){
201
189
}
202
190
 
203
191
/* Add server to set of servers to retry periodically */
204
 
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
205
 
               int af){
 
192
int add_server(const char *ip, uint16_t port,
 
193
                 AvahiIfIndex if_index,
 
194
                 int af){
206
195
  int ret;
207
196
  server *new_server = malloc(sizeof(server));
208
197
  if(new_server == NULL){
210
199
    return -1;
211
200
  }
212
201
  *new_server = (server){ .ip = strdup(ip),
213
 
                          .port = port,
214
 
                          .if_index = if_index,
215
 
                          .af = af };
 
202
                         .port = port,
 
203
                         .if_index = if_index,
 
204
                         .af = af };
216
205
  if(new_server->ip == NULL){
217
206
    perror_plus("strdup");
218
207
    return -1;
240
229
/* 
241
230
 * Initialize GPGME.
242
231
 */
243
 
static bool init_gpgme(const char *seckey, const char *pubkey,
244
 
                       const char *tempdir){
 
232
static bool init_gpgme(const char *seckey,
 
233
                       const char *pubkey, const char *tempdir){
245
234
  gpgme_error_t rc;
246
235
  gpgme_engine_info_t engine_info;
247
236
  
262
251
    
263
252
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
264
253
    if(rc != GPG_ERR_NO_ERROR){
265
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
266
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
254
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
255
              gpgme_strsource(rc), gpgme_strerror(rc));
267
256
      return false;
268
257
    }
269
258
    
270
259
    rc = gpgme_op_import(mc.ctx, pgp_data);
271
260
    if(rc != GPG_ERR_NO_ERROR){
272
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
273
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
261
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
262
              gpgme_strsource(rc), gpgme_strerror(rc));
274
263
      return false;
275
264
    }
276
265
    
283
272
  }
284
273
  
285
274
  if(debug){
286
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
275
    fprintf(stderr, "Initializing GPGME\n");
287
276
  }
288
277
  
289
278
  /* Init GPGME */
290
279
  gpgme_check_version(NULL);
291
280
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
292
281
  if(rc != GPG_ERR_NO_ERROR){
293
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
294
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
282
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
283
            gpgme_strsource(rc), gpgme_strerror(rc));
295
284
    return false;
296
285
  }
297
286
  
298
287
  /* Set GPGME home directory for the OpenPGP engine only */
299
288
  rc = gpgme_get_engine_info(&engine_info);
300
289
  if(rc != GPG_ERR_NO_ERROR){
301
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
302
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
290
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
291
            gpgme_strsource(rc), gpgme_strerror(rc));
303
292
    return false;
304
293
  }
305
294
  while(engine_info != NULL){
311
300
    engine_info = engine_info->next;
312
301
  }
313
302
  if(engine_info == NULL){
314
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
315
 
                 tempdir);
 
303
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
316
304
    return false;
317
305
  }
318
306
  
319
307
  /* Create new GPGME "context" */
320
308
  rc = gpgme_new(&(mc.ctx));
321
309
  if(rc != GPG_ERR_NO_ERROR){
322
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
323
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
324
 
                 gpgme_strerror(rc));
 
310
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
311
            gpgme_strsource(rc), gpgme_strerror(rc));
325
312
    return false;
326
313
  }
327
314
  
346
333
  ssize_t plaintext_length = 0;
347
334
  
348
335
  if(debug){
349
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
336
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
350
337
  }
351
338
  
352
339
  /* Create new GPGME data buffer from memory cryptotext */
353
340
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
354
341
                               0);
355
342
  if(rc != GPG_ERR_NO_ERROR){
356
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
357
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
343
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
344
            gpgme_strsource(rc), gpgme_strerror(rc));
358
345
    return -1;
359
346
  }
360
347
  
361
348
  /* Create new empty GPGME data buffer for the plaintext */
362
349
  rc = gpgme_data_new(&dh_plain);
363
350
  if(rc != GPG_ERR_NO_ERROR){
364
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
365
 
                 "bad gpgme_data_new: %s: %s\n",
366
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
351
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
352
            gpgme_strsource(rc), gpgme_strerror(rc));
367
353
    gpgme_data_release(dh_crypto);
368
354
    return -1;
369
355
  }
372
358
     data buffer */
373
359
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
374
360
  if(rc != GPG_ERR_NO_ERROR){
375
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
376
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
361
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
362
            gpgme_strsource(rc), gpgme_strerror(rc));
377
363
    plaintext_length = -1;
378
364
    if(debug){
379
365
      gpgme_decrypt_result_t result;
380
366
      result = gpgme_op_decrypt_result(mc.ctx);
381
367
      if(result == NULL){
382
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
368
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
383
369
      } else {
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);
 
370
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
371
                result->unsupported_algorithm);
 
372
        fprintf(stderr, "Wrong key usage: %u\n",
 
373
                result->wrong_key_usage);
388
374
        if(result->file_name != NULL){
389
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
375
          fprintf(stderr, "File name: %s\n", result->file_name);
390
376
        }
391
377
        gpgme_recipient_t recipient;
392
378
        recipient = result->recipients;
393
379
        while(recipient != NULL){
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");
 
380
          fprintf(stderr, "Public key algorithm: %s\n",
 
381
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
382
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
383
          fprintf(stderr, "Secret key available: %s\n",
 
384
                  recipient->status == GPG_ERR_NO_SECKEY
 
385
                  ? "No" : "Yes");
401
386
          recipient = recipient->next;
402
387
        }
403
388
      }
406
391
  }
407
392
  
408
393
  if(debug){
409
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
394
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
410
395
  }
411
396
  
412
397
  /* Seek back to the beginning of the GPGME plaintext data buffer */
419
404
  *plaintext = NULL;
420
405
  while(true){
421
406
    plaintext_capacity = incbuffer(plaintext,
422
 
                                   (size_t)plaintext_length,
423
 
                                   plaintext_capacity);
 
407
                                      (size_t)plaintext_length,
 
408
                                      plaintext_capacity);
424
409
    if(plaintext_capacity == 0){
425
 
      perror_plus("incbuffer");
426
 
      plaintext_length = -1;
427
 
      goto decrypt_end;
 
410
        perror_plus("incbuffer");
 
411
        plaintext_length = -1;
 
412
        goto decrypt_end;
428
413
    }
429
414
    
430
415
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
443
428
  }
444
429
  
445
430
  if(debug){
446
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
431
    fprintf(stderr, "Decrypted password is: ");
447
432
    for(ssize_t i = 0; i < plaintext_length; i++){
448
433
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
449
434
    }
471
456
/* GnuTLS log function callback */
472
457
static void debuggnutls(__attribute__((unused)) int level,
473
458
                        const char* string){
474
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
459
  fprintf(stderr, "GnuTLS: %s", string);
475
460
}
476
461
 
477
462
static int init_gnutls_global(const char *pubkeyfilename,
479
464
  int ret;
480
465
  
481
466
  if(debug){
482
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
467
    fprintf(stderr, "Initializing GnuTLS\n");
483
468
  }
484
469
  
485
470
  ret = gnutls_global_init();
486
471
  if(ret != GNUTLS_E_SUCCESS){
487
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
488
 
                 safer_gnutls_strerror(ret));
 
472
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
473
            safer_gnutls_strerror(ret));
489
474
    return -1;
490
475
  }
491
476
  
500
485
  /* OpenPGP credentials */
501
486
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
502
487
  if(ret != GNUTLS_E_SUCCESS){
503
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
504
 
                 safer_gnutls_strerror(ret));
 
488
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
489
            safer_gnutls_strerror(ret));
505
490
    gnutls_global_deinit();
506
491
    return -1;
507
492
  }
508
493
  
509
494
  if(debug){
510
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
511
 
                 " secret key %s as GnuTLS credentials\n",
512
 
                 pubkeyfilename,
513
 
                 seckeyfilename);
 
495
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
496
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
497
            seckeyfilename);
514
498
  }
515
499
  
516
500
  ret = gnutls_certificate_set_openpgp_key_file
517
501
    (mc.cred, pubkeyfilename, seckeyfilename,
518
502
     GNUTLS_OPENPGP_FMT_BASE64);
519
503
  if(ret != GNUTLS_E_SUCCESS){
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));
 
504
    fprintf(stderr,
 
505
            "Error[%d] while reading the OpenPGP key pair ('%s',"
 
506
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
507
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
508
            safer_gnutls_strerror(ret));
525
509
    goto globalfail;
526
510
  }
527
511
  
528
512
  /* GnuTLS server initialization */
529
513
  ret = gnutls_dh_params_init(&mc.dh_params);
530
514
  if(ret != GNUTLS_E_SUCCESS){
531
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
532
 
                 " initialization: %s\n",
533
 
                 safer_gnutls_strerror(ret));
 
515
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
516
            " %s\n", safer_gnutls_strerror(ret));
534
517
    goto globalfail;
535
518
  }
536
519
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
537
520
  if(ret != GNUTLS_E_SUCCESS){
538
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
539
 
                 safer_gnutls_strerror(ret));
 
521
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
522
            safer_gnutls_strerror(ret));
540
523
    goto globalfail;
541
524
  }
542
525
  
562
545
    }
563
546
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
564
547
  if(ret != GNUTLS_E_SUCCESS){
565
 
    fprintf_plus(stderr,
566
 
                 "Error in GnuTLS session initialization: %s\n",
567
 
                 safer_gnutls_strerror(ret));
 
548
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
549
            safer_gnutls_strerror(ret));
568
550
  }
569
551
  
570
552
  {
577
559
      }
578
560
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
579
561
    if(ret != GNUTLS_E_SUCCESS){
580
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
581
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
582
 
                   safer_gnutls_strerror(ret));
 
562
      fprintf(stderr, "Syntax error at: %s\n", err);
 
563
      fprintf(stderr, "GnuTLS error: %s\n",
 
564
              safer_gnutls_strerror(ret));
583
565
      gnutls_deinit(*session);
584
566
      return -1;
585
567
    }
594
576
    }
595
577
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
596
578
  if(ret != GNUTLS_E_SUCCESS){
597
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
598
 
                 safer_gnutls_strerror(ret));
 
579
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
580
            safer_gnutls_strerror(ret));
599
581
    gnutls_deinit(*session);
600
582
    return -1;
601
583
  }
646
628
    pf = PF_INET;
647
629
    break;
648
630
  default:
649
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
631
    fprintf(stderr, "Bad address family: %d\n", af);
650
632
    errno = EINVAL;
651
633
    return -1;
652
634
  }
657
639
  }
658
640
  
659
641
  if(debug){
660
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
661
 
                 PRIu16 "\n", ip, port);
 
642
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
643
            "\n", ip, port);
662
644
  }
663
645
  
664
646
  tcp_sd = socket(pf, SOCK_STREAM, 0);
690
672
  }
691
673
  if(ret == 0){
692
674
    int e = errno;
693
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
675
    fprintf(stderr, "Bad address: %s\n", ip);
694
676
    errno = e;
695
677
    goto mandos_end;
696
678
  }
701
683
    
702
684
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
703
685
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
704
 
                                -Wunreachable-code*/
 
686
                              -Wunreachable-code*/
705
687
      if(if_index == AVAHI_IF_UNSPEC){
706
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
707
 
                     " incomplete without a network interface\n");
 
688
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
689
                " without a network interface\n");
708
690
        errno = EINVAL;
709
691
        goto mandos_end;
710
692
      }
728
710
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
729
711
        perror_plus("if_indextoname");
730
712
      } else {
731
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
732
 
                     "\n", ip, interface, port);
 
713
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
714
                ip, interface, port);
733
715
      }
734
716
    } else {
735
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
736
 
                   ip, port);
 
717
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
718
              port);
737
719
    }
738
720
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
739
721
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
749
731
      perror_plus("inet_ntop");
750
732
    } else {
751
733
      if(strcmp(addrstr, ip) != 0){
752
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
734
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
753
735
      }
754
736
    }
755
737
  }
783
765
  while(true){
784
766
    size_t out_size = strlen(out);
785
767
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
786
 
                                        out_size - written));
 
768
                                   out_size - written));
787
769
    if(ret == -1){
788
770
      int e = errno;
789
771
      perror_plus("write");
809
791
  }
810
792
  
811
793
  if(debug){
812
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
794
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
813
795
  }
814
796
  
815
797
  if(quit_now){
835
817
  
836
818
  if(ret != GNUTLS_E_SUCCESS){
837
819
    if(debug){
838
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
820
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
839
821
      gnutls_perror(ret);
840
822
    }
841
823
    errno = EPROTO;
845
827
  /* Read OpenPGP packet that contains the wanted password */
846
828
  
847
829
  if(debug){
848
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
849
 
                 " %s\n", ip);
 
830
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
831
            ip);
850
832
  }
851
833
  
852
834
  while(true){
857
839
    }
858
840
    
859
841
    buffer_capacity = incbuffer(&buffer, buffer_length,
860
 
                                buffer_capacity);
 
842
                                   buffer_capacity);
861
843
    if(buffer_capacity == 0){
862
844
      int e = errno;
863
845
      perror_plus("incbuffer");
890
872
          }
891
873
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
892
874
        if(ret < 0){
893
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
894
 
                       "***\n");
 
875
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
895
876
          gnutls_perror(ret);
896
877
          errno = EPROTO;
897
878
          goto mandos_end;
898
879
        }
899
880
        break;
900
881
      default:
901
 
        fprintf_plus(stderr, "Unknown error while reading data from"
902
 
                     " encrypted session with Mandos server\n");
 
882
        fprintf(stderr, "Unknown error while reading data from"
 
883
                " encrypted session with Mandos server\n");
903
884
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
904
885
        errno = EIO;
905
886
        goto mandos_end;
910
891
  }
911
892
  
912
893
  if(debug){
913
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
894
    fprintf(stderr, "Closing TLS session\n");
914
895
  }
915
896
  
916
897
  if(quit_now){
928
909
  
929
910
  if(buffer_length > 0){
930
911
    ssize_t decrypted_buffer_size;
931
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
912
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
913
                                               buffer_length,
932
914
                                               &decrypted_buffer);
933
915
    if(decrypted_buffer_size >= 0){
934
916
      
945
927
        if(ret == 0 and ferror(stdout)){
946
928
          int e = errno;
947
929
          if(debug){
948
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
949
 
                         strerror(errno));
 
930
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
931
                    strerror(errno));
950
932
          }
951
933
          errno = e;
952
934
          goto mandos_end;
1009
991
  switch(event){
1010
992
  default:
1011
993
  case AVAHI_RESOLVER_FAILURE:
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)));
 
994
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
995
            " of type '%s' in domain '%s': %s\n", name, type, domain,
 
996
            avahi_strerror(avahi_server_errno(mc.server)));
1016
997
    break;
1017
998
    
1018
999
  case AVAHI_RESOLVER_FOUND:
1020
1001
      char ip[AVAHI_ADDRESS_STR_MAX];
1021
1002
      avahi_address_snprint(ip, sizeof(ip), address);
1022
1003
      if(debug){
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);
 
1004
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1005
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
1006
                ip, (intmax_t)interface, port);
1026
1007
      }
1027
1008
      int ret = start_mandos_communication(ip, port, interface,
1028
1009
                                           avahi_proto_to_af(proto));
1060
1041
  default:
1061
1042
  case AVAHI_BROWSER_FAILURE:
1062
1043
    
1063
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1064
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1044
    fprintf(stderr, "(Avahi browser) %s\n",
 
1045
            avahi_strerror(avahi_server_errno(mc.server)));
1065
1046
    avahi_simple_poll_quit(mc.simple_poll);
1066
1047
    return;
1067
1048
    
1074
1055
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1075
1056
                                    name, type, domain, protocol, 0,
1076
1057
                                    resolve_callback, NULL) == NULL)
1077
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1078
 
                   " %s\n", name,
1079
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1058
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1059
              name, avahi_strerror(avahi_server_errno(mc.server)));
1080
1060
    break;
1081
1061
    
1082
1062
  case AVAHI_BROWSER_REMOVE:
1085
1065
  case AVAHI_BROWSER_ALL_FOR_NOW:
1086
1066
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1087
1067
    if(debug){
1088
 
      fprintf_plus(stderr, "No Mandos server found, still"
1089
 
                   " searching...\n");
 
1068
      fprintf(stderr, "No Mandos server found, still searching...\n");
1090
1069
    }
1091
1070
    break;
1092
1071
  }
1131
1110
  /* Reject the loopback device */
1132
1111
  if(ifr->ifr_flags & IFF_LOOPBACK){
1133
1112
    if(debug){
1134
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1135
 
                   ifname);
 
1113
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1114
              ifname);
1136
1115
    }
1137
1116
    return false;
1138
1117
  }
1139
1118
  /* Accept point-to-point devices only if connect_to is specified */
1140
1119
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1141
1120
    if(debug){
1142
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1143
 
                   " \"%s\"\n", ifname);
 
1121
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1122
              ifname);
1144
1123
    }
1145
1124
    return true;
1146
1125
  }
1147
1126
  /* Otherwise, reject non-broadcast-capable devices */
1148
1127
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1149
1128
    if(debug){
1150
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1151
 
                   " \"%s\"\n", ifname);
 
1129
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1130
              ifname);
1152
1131
    }
1153
1132
    return false;
1154
1133
  }
1155
1134
  /* Reject non-ARP interfaces (including dummy interfaces) */
1156
1135
  if(ifr->ifr_flags & IFF_NOARP){
1157
1136
    if(debug){
1158
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1159
 
                   ifname);
 
1137
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
1160
1138
    }
1161
1139
    return false;
1162
1140
  }
1163
1141
  
1164
1142
  /* Accept this device */
1165
1143
  if(debug){
1166
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1144
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
1167
1145
  }
1168
1146
  return true;
1169
1147
}
1174
1152
 * (This function is passed to scandir(3) as a filter function.)
1175
1153
 */
1176
1154
int good_interface(const struct dirent *if_entry){
 
1155
  int ret;
1177
1156
  if(if_entry->d_name[0] == '.'){
1178
1157
    return 0;
1179
1158
  }
1180
 
  
1181
1159
  struct ifreq ifr;
 
1160
 
1182
1161
  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
 
    }
1187
1162
    return 0;
1188
1163
  }
1189
1164
  
1199
1174
 * (This function is passed to scandir(3) as a filter function.)
1200
1175
 */
1201
1176
int up_interface(const struct dirent *if_entry){
 
1177
  ssize_t ssret;
 
1178
  char *flagname = NULL;
1202
1179
  if(if_entry->d_name[0] == '.'){
1203
1180
    return 0;
1204
1181
  }
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
 
  
 
1182
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1183
                     if_entry->d_name);
 
1184
  if(ret < 0){
 
1185
    perror_plus("asprintf");
 
1186
    return 0;
 
1187
  }
 
1188
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1189
  if(flags_fd == -1){
 
1190
    perror_plus("open");
 
1191
    free(flagname);
 
1192
    return 0;
 
1193
  }
 
1194
  free(flagname);
 
1195
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1196
  /* read line from flags_fd */
 
1197
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
 
1198
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1199
  flagstring[(size_t)to_read] = '\0';
 
1200
  if(flagstring == NULL){
 
1201
    perror_plus("malloc");
 
1202
    close(flags_fd);
 
1203
    return 0;
 
1204
  }
 
1205
  while(to_read > 0){
 
1206
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1207
                                             (size_t)to_read));
 
1208
    if(ssret == -1){
 
1209
      perror_plus("read");
 
1210
      free(flagstring);
 
1211
      close(flags_fd);
 
1212
      return 0;
 
1213
    }
 
1214
    to_read -= ssret;
 
1215
    if(ssret == 0){
 
1216
      break;
 
1217
    }
 
1218
  }
 
1219
  close(flags_fd);
 
1220
  intmax_t tmpmax;
 
1221
  char *tmp;
 
1222
  errno = 0;
 
1223
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1224
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1225
                                         and not (isspace(*tmp)))
 
1226
     or tmpmax != (ifreq_flags)tmpmax){
 
1227
    if(debug){
 
1228
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1229
              flagstring, if_entry->d_name);
 
1230
    }
 
1231
    free(flagstring);
 
1232
    return 0;
 
1233
  }
 
1234
  free(flagstring);
 
1235
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1236
  /* Reject the loopback device */
 
1237
  if(flags & IFF_LOOPBACK){
 
1238
    if(debug){
 
1239
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1240
              if_entry->d_name);
 
1241
    }
 
1242
    return 0;
 
1243
  }
 
1244
 
1215
1245
  /* Reject down interfaces */
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;
 
1246
  if(not (flags & IFF_UP)){
 
1247
    return 0;
 
1248
  }
 
1249
  
 
1250
  /* Accept point-to-point devices only if connect_to is specified */
 
1251
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1252
    if(debug){
 
1253
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1254
              if_entry->d_name);
 
1255
    }
 
1256
    return 1;
 
1257
  }
 
1258
  /* Otherwise, reject non-broadcast-capable devices */
 
1259
  if(not (flags & IFF_BROADCAST)){
 
1260
    if(debug){
 
1261
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1262
              if_entry->d_name);
 
1263
    }
 
1264
    return 0;
 
1265
  }
 
1266
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1267
  if(flags & IFF_NOARP){
 
1268
    if(debug){
 
1269
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1270
              if_entry->d_name);
 
1271
    }
 
1272
    return 0;
 
1273
  }
 
1274
  /* Accept this device */
 
1275
  if(debug){
 
1276
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1277
            if_entry->d_name);
1235
1278
  }
1236
1279
  return 1;
1237
1280
}
1250
1293
/* Is this directory entry a runnable program? */
1251
1294
int runnable_hook(const struct dirent *direntry){
1252
1295
  int ret;
1253
 
  size_t sret;
1254
1296
  struct stat st;
1255
1297
  
1256
1298
  if((direntry->d_name)[0] == '\0'){
1258
1300
    return 0;
1259
1301
  }
1260
1302
  
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);
 
1303
  /* Save pointer to last character */
 
1304
  char *end = strchr(direntry->d_name, '\0')-1;
 
1305
  
 
1306
  if(*end == '~'){
 
1307
    /* Backup name~ */
 
1308
    return 0;
 
1309
  }
 
1310
  
 
1311
  if(((direntry->d_name)[0] == '#')
 
1312
     and (*end == '#')){
 
1313
    /* Temporary #name# */
 
1314
    return 0;
 
1315
  }
 
1316
  
 
1317
  /* XXX more rules here */
 
1318
  
 
1319
  ret = stat(direntry->d_name, &st);
1282
1320
  if(ret == -1){
1283
1321
    if(debug){
1284
 
      perror_plus("Could not stat hook");
 
1322
      perror_plus("Could not stat plugin");
1285
1323
    }
1286
1324
    return 0;
1287
1325
  }
1288
 
  if(not (S_ISREG(st.st_mode))){
 
1326
  if(not (st.st_mode & S_ISREG)){
1289
1327
    /* Not a regular file */
1290
 
    if(debug){
1291
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1292
 
                   direntry->d_name);
1293
 
    }
1294
1328
    return 0;
1295
1329
  }
1296
1330
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1297
1331
    /* Not executable */
1298
 
    if(debug){
1299
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1300
 
                   direntry->d_name);
1301
 
    }
1302
1332
    return 0;
1303
1333
  }
1304
1334
  return 1;
1313
1343
  while(true){
1314
1344
    if(mc.current_server == NULL){
1315
1345
      if (debug){
1316
 
        fprintf_plus(stderr, "Wait until first server is found."
1317
 
                     " No timeout!\n");
 
1346
        fprintf(stderr,
 
1347
                "Wait until first server is found. No timeout!\n");
1318
1348
      }
1319
1349
      ret = avahi_simple_poll_iterate(s, -1);
1320
1350
    } else {
1321
1351
      if (debug){
1322
 
        fprintf_plus(stderr, "Check current_server if we should run"
1323
 
                     " it, or wait\n");
 
1352
        fprintf(stderr, "Check current_server if we should run it,"
 
1353
                " or wait\n");
1324
1354
      }
1325
1355
      /* the current time */
1326
1356
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1342
1372
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1343
1373
      
1344
1374
      if (debug){
1345
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1346
 
                     block_time);
 
1375
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1347
1376
      }
1348
1377
      
1349
1378
      if(block_time <= 0){
1369
1398
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1370
1399
    }
1371
1400
    if(ret != 0){
1372
 
      if (ret > 0 or errno != EINTR){
 
1401
      if (ret > 0 or errno != EINTR) {
1373
1402
        return (ret != 1) ? ret : 0;
1374
1403
      }
1375
1404
    }
1376
1405
  }
1377
1406
}
1378
1407
 
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
 
 
1477
1408
int main(int argc, char *argv[]){
1478
1409
  AvahiSServiceBrowser *sb = NULL;
1479
1410
  int error;
1561
1492
        .arg = "SECONDS",
1562
1493
        .doc = "Retry interval used when denied by the mandos server",
1563
1494
        .group = 2 },
1564
 
      { .name = "network-hook-dir", .key = 133,
1565
 
        .arg = "DIR",
1566
 
        .doc = "Directory where network hooks are located",
1567
 
        .group = 2 },
1568
1495
      /*
1569
1496
       * These reproduce what we would get without ARGP_NO_HELP
1570
1497
       */
1623
1550
          argp_error(state, "Bad retry interval");
1624
1551
        }
1625
1552
        break;
1626
 
      case 133:                 /* --network-hook-dir */
1627
 
        hookdir = arg;
1628
 
        break;
1629
1553
        /*
1630
1554
         * These reproduce what we would get without ARGP_NO_HELP
1631
1555
         */
1637
1561
        argp_state_help(state, state->out_stream,
1638
1562
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1639
1563
      case 'V':                 /* --version */
1640
 
        fprintf_plus(state->out_stream,
1641
 
                     "Mandos plugin mandos-client: ");
1642
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1564
        fprintf(state->out_stream, "%s\n", argp_program_version);
1643
1565
        exit(argp_err_exit_status);
1644
1566
        break;
1645
1567
      default:
1690
1612
        if(ret == -1){
1691
1613
          perror_plus("fstat");
1692
1614
        } else {
1693
 
          if(S_ISREG(st.st_mode)
1694
 
             and st.st_uid == 0 and st.st_gid == 0){
 
1615
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1695
1616
            ret = fchown(seckey_fd, uid, gid);
1696
1617
            if(ret == -1){
1697
1618
              perror_plus("fchown");
1711
1632
        if(ret == -1){
1712
1633
          perror_plus("fstat");
1713
1634
        } else {
1714
 
          if(S_ISREG(st.st_mode)
1715
 
             and st.st_uid == 0 and st.st_gid == 0){
 
1635
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1716
1636
            ret = fchown(pubkey_fd, uid, gid);
1717
1637
            if(ret == -1){
1718
1638
              perror_plus("fchown");
1731
1651
    }
1732
1652
  }
1733
1653
  
1734
 
  /* Run network hooks */
 
1654
  /* Find network hooks and run them */
1735
1655
  {
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
 
    }
 
1656
    struct dirent **direntries;
 
1657
    struct dirent *direntry;
 
1658
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
 
1659
                           alphasort);
 
1660
    int devnull = open("/dev/null", O_RDONLY);
 
1661
    for(int i = 0; i < numhooks; i++){
 
1662
      direntry = direntries[0];
 
1663
      char *fullname = NULL;
 
1664
      ret = asprintf(&fullname, "%s/%s", tempdir,
 
1665
                     direntry->d_name);
 
1666
      if(ret < 0){
 
1667
        perror_plus("asprintf");
 
1668
        continue;
 
1669
      }
 
1670
      pid_t hook_pid = fork();
 
1671
      if(hook_pid == 0){
 
1672
        /* Child */
 
1673
        dup2(devnull, STDIN_FILENO);
 
1674
        close(devnull);
 
1675
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1676
        setenv("DEVICE", interface, 1);
 
1677
        setenv("VERBOSE", debug ? "1" : "0", 1);
 
1678
        setenv("MODE", "start", 1);
 
1679
        /* setenv( XXX more here */
 
1680
        ret = execl(fullname, direntry->d_name, "start");
 
1681
        perror_plus("execl");
 
1682
      }
 
1683
      free(fullname);
 
1684
      if(quit_now){
 
1685
        goto end;
 
1686
      }
 
1687
    }
 
1688
    close(devnull);
1751
1689
  }
1752
1690
  
1753
1691
  if(not debug){
1756
1694
  
1757
1695
  if(interface[0] == '\0'){
1758
1696
    struct dirent **direntries;
1759
 
    /* First look for interfaces that are up */
1760
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1697
    ret = scandir(sys_class_net, &direntries, good_interface,
1761
1698
                  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
 
    }
1768
1699
    if(ret >= 1){
1769
 
      /* Pick the first interface returned */
 
1700
      /* Pick the first good interface */
1770
1701
      interface = strdup(direntries[0]->d_name);
1771
1702
      if(debug){
1772
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1703
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1773
1704
      }
1774
1705
      if(interface == NULL){
1775
1706
        perror_plus("malloc");
1780
1711
      free(direntries);
1781
1712
    } else {
1782
1713
      free(direntries);
1783
 
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1714
      fprintf(stderr, "Could not find a network interface\n");
1784
1715
      exitcode = EXIT_FAILURE;
1785
1716
      goto end;
1786
1717
    }
1792
1723
  srand((unsigned int) time(NULL));
1793
1724
  mc.simple_poll = avahi_simple_poll_new();
1794
1725
  if(mc.simple_poll == NULL){
1795
 
    fprintf_plus(stderr,
1796
 
                 "Avahi: Failed to create simple poll object.\n");
 
1726
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1797
1727
    exitcode = EX_UNAVAILABLE;
1798
1728
    goto end;
1799
1729
  }
1865
1795
  if(strcmp(interface, "none") != 0){
1866
1796
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1867
1797
    if(if_index == 0){
1868
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1798
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1869
1799
      exitcode = EX_UNAVAILABLE;
1870
1800
      goto end;
1871
1801
    }
1991
1921
#endif  /* __linux__ */
1992
1922
    /* Lower privileges */
1993
1923
    errno = 0;
1994
 
    /* Lower privileges */
1995
 
    ret = seteuid(uid);
1996
 
    if(ret == -1){
1997
 
      perror_plus("seteuid");
 
1924
    if(take_down_interface){
 
1925
      /* Lower privileges */
 
1926
      ret = seteuid(uid);
 
1927
      if(ret == -1){
 
1928
        perror_plus("seteuid");
 
1929
      }
 
1930
    } else {
 
1931
      /* Lower privileges permanently */
 
1932
      ret = setuid(uid);
 
1933
      if(ret == -1){
 
1934
        perror_plus("setuid");
 
1935
      }
1998
1936
    }
1999
1937
  }
2000
1938
  
2004
1942
  
2005
1943
  ret = init_gnutls_global(pubkey, seckey);
2006
1944
  if(ret == -1){
2007
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1945
    fprintf(stderr, "init_gnutls_global failed\n");
2008
1946
    exitcode = EX_UNAVAILABLE;
2009
1947
    goto end;
2010
1948
  } else {
2026
1964
  }
2027
1965
  
2028
1966
  if(not init_gpgme(pubkey, seckey, tempdir)){
2029
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1967
    fprintf(stderr, "init_gpgme failed\n");
2030
1968
    exitcode = EX_UNAVAILABLE;
2031
1969
    goto end;
2032
1970
  } else {
2042
1980
    /* (Mainly meant for debugging) */
2043
1981
    char *address = strrchr(connect_to, ':');
2044
1982
    if(address == NULL){
2045
 
      fprintf_plus(stderr, "No colon in address\n");
 
1983
      fprintf(stderr, "No colon in address\n");
2046
1984
      exitcode = EX_USAGE;
2047
1985
      goto end;
2048
1986
    }
2056
1994
    tmpmax = strtoimax(address+1, &tmp, 10);
2057
1995
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2058
1996
       or tmpmax != (uint16_t)tmpmax){
2059
 
      fprintf_plus(stderr, "Bad port number\n");
 
1997
      fprintf(stderr, "Bad port number\n");
2060
1998
      exitcode = EX_USAGE;
2061
1999
      goto end;
2062
2000
    }
2092
2030
        break;
2093
2031
      }
2094
2032
      if(debug){
2095
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2096
 
                     (int)retry_interval);
 
2033
        fprintf(stderr, "Retrying in %d seconds\n",
 
2034
                (int)retry_interval);
2097
2035
      }
2098
2036
      sleep((int)retry_interval);
2099
2037
    }
2129
2067
  
2130
2068
  /* Check if creating the Avahi server object succeeded */
2131
2069
  if(mc.server == NULL){
2132
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2133
 
                 avahi_strerror(error));
 
2070
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2071
            avahi_strerror(error));
2134
2072
    exitcode = EX_UNAVAILABLE;
2135
2073
    goto end;
2136
2074
  }
2144
2082
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2145
2083
                                   NULL, 0, browse_callback, NULL);
2146
2084
  if(sb == NULL){
2147
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2148
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
2085
    fprintf(stderr, "Failed to create service browser: %s\n",
 
2086
            avahi_strerror(avahi_server_errno(mc.server)));
2149
2087
    exitcode = EX_UNAVAILABLE;
2150
2088
    goto end;
2151
2089
  }
2157
2095
  /* Run the main loop */
2158
2096
  
2159
2097
  if(debug){
2160
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
2098
    fprintf(stderr, "Starting Avahi loop search\n");
2161
2099
  }
2162
2100
 
2163
2101
  ret = avahi_loop_with_timeout(mc.simple_poll,
2164
2102
                                (int)(retry_interval * 1000));
2165
2103
  if(debug){
2166
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2167
 
                 (ret == 0) ? "successfully" : "with error");
 
2104
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
2105
            (ret == 0) ? "successfully" : "with error");
2168
2106
  }
2169
2107
  
2170
2108
 end:
2171
2109
  
2172
2110
  if(debug){
2173
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2111
    fprintf(stderr, "%s exiting\n", argv[0]);
2174
2112
  }
2175
2113
  
2176
2114
  /* Cleanup things */
2204
2142
    }
2205
2143
  }
2206
2144
  
2207
 
  /* Re-raise priviliges */
2208
 
  {
 
2145
  /* XXX run network hooks "stop" here  */
 
2146
  
 
2147
  /* Take down the network interface */
 
2148
  if(take_down_interface){
 
2149
    /* Re-raise priviliges */
2209
2150
    errno = 0;
2210
2151
    ret = seteuid(0);
2211
2152
    if(ret == -1){
2212
2153
      perror_plus("seteuid");
2213
2154
    }
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){
 
2155
    if(geteuid() == 0){
2221
2156
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2222
2157
      if(ret == -1){
2223
2158
        perror_plus("ioctl SIOCGIFFLAGS");
2224
 
      } else if(network.ifr_flags & IFF_UP){
 
2159
      } else if(network.ifr_flags & IFF_UP) {
2225
2160
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2226
2161
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2227
2162
        if(ret == -1){
2232
2167
      if(ret == -1){
2233
2168
        perror_plus("close");
2234
2169
      }
 
2170
      /* Lower privileges permanently */
 
2171
      errno = 0;
 
2172
      ret = setuid(uid);
 
2173
      if(ret == -1){
 
2174
        perror_plus("setuid");
 
2175
      }
2235
2176
    }
2236
2177
  }
2237
 
  /* Lower privileges permanently */
2238
 
  errno = 0;
2239
 
  ret = setuid(uid);
2240
 
  if(ret == -1){
2241
 
    perror_plus("setuid");
2242
 
  }
2243
2178
  
2244
2179
  /* Removes the GPGME temp directory and all files inside */
2245
2180
  if(tempdir_created){
2259
2194
        }
2260
2195
        ret = remove(fullname);
2261
2196
        if(ret == -1){
2262
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2263
 
                       strerror(errno));
 
2197
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
2198
                  strerror(errno));
2264
2199
        }
2265
2200
        free(fullname);
2266
2201
      }