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