/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
123
125
#define PATHDIR "/conf/conf.d/mandos"
124
126
#define SECKEY "seckey.txt"
125
127
#define PUBKEY "pubkey.txt"
 
128
#define HOOKDIR "/lib/mandos/network-hooks.d"
126
129
 
127
130
bool debug = false;
128
131
static const char mandos_protocol_version[] = "1";
130
133
const char *argp_program_bug_address = "<mandos@recompile.se>";
131
134
static const char sys_class_net[] = "/sys/class/net";
132
135
char *connect_to = NULL;
 
136
const char *hookdir = HOOKDIR;
133
137
 
134
138
/* Doubly linked list that need to be circularly linked when used */
135
139
typedef struct server{
170
174
  perror(print_text);
171
175
}
172
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
 
173
186
/*
174
187
 * Make additional room in "buffer" for at least BUFFER_SIZE more
175
188
 * bytes. "buffer_capacity" is how much is currently allocated,
176
189
 * "buffer_length" is how much is already used.
177
190
 */
178
191
size_t incbuffer(char **buffer, size_t buffer_length,
179
 
                  size_t buffer_capacity){
 
192
                 size_t buffer_capacity){
180
193
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
181
194
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
182
195
    if(buffer == NULL){
188
201
}
189
202
 
190
203
/* Add server to set of servers to retry periodically */
191
 
int add_server(const char *ip, uint16_t port,
192
 
                 AvahiIfIndex if_index,
193
 
                 int af){
 
204
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
205
               int af){
194
206
  int ret;
195
207
  server *new_server = malloc(sizeof(server));
196
208
  if(new_server == NULL){
198
210
    return -1;
199
211
  }
200
212
  *new_server = (server){ .ip = strdup(ip),
201
 
                         .port = port,
202
 
                         .if_index = if_index,
203
 
                         .af = af };
 
213
                          .port = port,
 
214
                          .if_index = if_index,
 
215
                          .af = af };
204
216
  if(new_server->ip == NULL){
205
217
    perror_plus("strdup");
206
218
    return -1;
228
240
/* 
229
241
 * Initialize GPGME.
230
242
 */
231
 
static bool init_gpgme(const char *seckey,
232
 
                       const char *pubkey, const char *tempdir){
 
243
static bool init_gpgme(const char *seckey, const char *pubkey,
 
244
                       const char *tempdir){
233
245
  gpgme_error_t rc;
234
246
  gpgme_engine_info_t engine_info;
235
247
  
250
262
    
251
263
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
252
264
    if(rc != GPG_ERR_NO_ERROR){
253
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
254
 
              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));
255
267
      return false;
256
268
    }
257
269
    
258
270
    rc = gpgme_op_import(mc.ctx, pgp_data);
259
271
    if(rc != GPG_ERR_NO_ERROR){
260
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
261
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
272
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
273
                   gpgme_strsource(rc), gpgme_strerror(rc));
262
274
      return false;
263
275
    }
264
276
    
271
283
  }
272
284
  
273
285
  if(debug){
274
 
    fprintf(stderr, "Initializing GPGME\n");
 
286
    fprintf_plus(stderr, "Initializing GPGME\n");
275
287
  }
276
288
  
277
289
  /* Init GPGME */
278
290
  gpgme_check_version(NULL);
279
291
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
280
292
  if(rc != GPG_ERR_NO_ERROR){
281
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
282
 
            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));
283
295
    return false;
284
296
  }
285
297
  
286
298
  /* Set GPGME home directory for the OpenPGP engine only */
287
299
  rc = gpgme_get_engine_info(&engine_info);
288
300
  if(rc != GPG_ERR_NO_ERROR){
289
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
290
 
            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));
291
303
    return false;
292
304
  }
293
305
  while(engine_info != NULL){
299
311
    engine_info = engine_info->next;
300
312
  }
301
313
  if(engine_info == NULL){
302
 
    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);
303
316
    return false;
304
317
  }
305
318
  
306
319
  /* Create new GPGME "context" */
307
320
  rc = gpgme_new(&(mc.ctx));
308
321
  if(rc != GPG_ERR_NO_ERROR){
309
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
310
 
            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));
311
325
    return false;
312
326
  }
313
327
  
332
346
  ssize_t plaintext_length = 0;
333
347
  
334
348
  if(debug){
335
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
349
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
336
350
  }
337
351
  
338
352
  /* Create new GPGME data buffer from memory cryptotext */
339
353
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
340
354
                               0);
341
355
  if(rc != GPG_ERR_NO_ERROR){
342
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
343
 
            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));
344
358
    return -1;
345
359
  }
346
360
  
347
361
  /* Create new empty GPGME data buffer for the plaintext */
348
362
  rc = gpgme_data_new(&dh_plain);
349
363
  if(rc != GPG_ERR_NO_ERROR){
350
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
351
 
            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));
352
367
    gpgme_data_release(dh_crypto);
353
368
    return -1;
354
369
  }
357
372
     data buffer */
358
373
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
359
374
  if(rc != GPG_ERR_NO_ERROR){
360
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
361
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
375
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
376
                 gpgme_strsource(rc), gpgme_strerror(rc));
362
377
    plaintext_length = -1;
363
378
    if(debug){
364
379
      gpgme_decrypt_result_t result;
365
380
      result = gpgme_op_decrypt_result(mc.ctx);
366
381
      if(result == NULL){
367
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
382
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
368
383
      } else {
369
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
370
 
                result->unsupported_algorithm);
371
 
        fprintf(stderr, "Wrong key usage: %u\n",
372
 
                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);
373
388
        if(result->file_name != NULL){
374
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
389
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
375
390
        }
376
391
        gpgme_recipient_t recipient;
377
392
        recipient = result->recipients;
378
393
        while(recipient != NULL){
379
 
          fprintf(stderr, "Public key algorithm: %s\n",
380
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
381
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
382
 
          fprintf(stderr, "Secret key available: %s\n",
383
 
                  recipient->status == GPG_ERR_NO_SECKEY
384
 
                  ? "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");
385
401
          recipient = recipient->next;
386
402
        }
387
403
      }
390
406
  }
391
407
  
392
408
  if(debug){
393
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
409
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
394
410
  }
395
411
  
396
412
  /* Seek back to the beginning of the GPGME plaintext data buffer */
403
419
  *plaintext = NULL;
404
420
  while(true){
405
421
    plaintext_capacity = incbuffer(plaintext,
406
 
                                      (size_t)plaintext_length,
407
 
                                      plaintext_capacity);
 
422
                                   (size_t)plaintext_length,
 
423
                                   plaintext_capacity);
408
424
    if(plaintext_capacity == 0){
409
 
        perror_plus("incbuffer");
410
 
        plaintext_length = -1;
411
 
        goto decrypt_end;
 
425
      perror_plus("incbuffer");
 
426
      plaintext_length = -1;
 
427
      goto decrypt_end;
412
428
    }
413
429
    
414
430
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
427
443
  }
428
444
  
429
445
  if(debug){
430
 
    fprintf(stderr, "Decrypted password is: ");
 
446
    fprintf_plus(stderr, "Decrypted password is: ");
431
447
    for(ssize_t i = 0; i < plaintext_length; i++){
432
448
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
433
449
    }
455
471
/* GnuTLS log function callback */
456
472
static void debuggnutls(__attribute__((unused)) int level,
457
473
                        const char* string){
458
 
  fprintf(stderr, "GnuTLS: %s", string);
 
474
  fprintf_plus(stderr, "GnuTLS: %s", string);
459
475
}
460
476
 
461
477
static int init_gnutls_global(const char *pubkeyfilename,
463
479
  int ret;
464
480
  
465
481
  if(debug){
466
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
482
    fprintf_plus(stderr, "Initializing GnuTLS\n");
467
483
  }
468
484
  
469
485
  ret = gnutls_global_init();
470
486
  if(ret != GNUTLS_E_SUCCESS){
471
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
472
 
            safer_gnutls_strerror(ret));
 
487
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
488
                 safer_gnutls_strerror(ret));
473
489
    return -1;
474
490
  }
475
491
  
484
500
  /* OpenPGP credentials */
485
501
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
486
502
  if(ret != GNUTLS_E_SUCCESS){
487
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
488
 
            safer_gnutls_strerror(ret));
 
503
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
504
                 safer_gnutls_strerror(ret));
489
505
    gnutls_global_deinit();
490
506
    return -1;
491
507
  }
492
508
  
493
509
  if(debug){
494
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
495
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
496
 
            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);
497
514
  }
498
515
  
499
516
  ret = gnutls_certificate_set_openpgp_key_file
500
517
    (mc.cred, pubkeyfilename, seckeyfilename,
501
518
     GNUTLS_OPENPGP_FMT_BASE64);
502
519
  if(ret != GNUTLS_E_SUCCESS){
503
 
    fprintf(stderr,
504
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
505
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
506
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
507
 
            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));
508
525
    goto globalfail;
509
526
  }
510
527
  
511
528
  /* GnuTLS server initialization */
512
529
  ret = gnutls_dh_params_init(&mc.dh_params);
513
530
  if(ret != GNUTLS_E_SUCCESS){
514
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
515
 
            " %s\n", safer_gnutls_strerror(ret));
 
531
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
532
                 " initialization: %s\n",
 
533
                 safer_gnutls_strerror(ret));
516
534
    goto globalfail;
517
535
  }
518
536
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
519
537
  if(ret != GNUTLS_E_SUCCESS){
520
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
521
 
            safer_gnutls_strerror(ret));
 
538
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
539
                 safer_gnutls_strerror(ret));
522
540
    goto globalfail;
523
541
  }
524
542
  
544
562
    }
545
563
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
546
564
  if(ret != GNUTLS_E_SUCCESS){
547
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
548
 
            safer_gnutls_strerror(ret));
 
565
    fprintf_plus(stderr,
 
566
                 "Error in GnuTLS session initialization: %s\n",
 
567
                 safer_gnutls_strerror(ret));
549
568
  }
550
569
  
551
570
  {
558
577
      }
559
578
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
560
579
    if(ret != GNUTLS_E_SUCCESS){
561
 
      fprintf(stderr, "Syntax error at: %s\n", err);
562
 
      fprintf(stderr, "GnuTLS error: %s\n",
563
 
              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));
564
583
      gnutls_deinit(*session);
565
584
      return -1;
566
585
    }
575
594
    }
576
595
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
577
596
  if(ret != GNUTLS_E_SUCCESS){
578
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
579
 
            safer_gnutls_strerror(ret));
 
597
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
598
                 safer_gnutls_strerror(ret));
580
599
    gnutls_deinit(*session);
581
600
    return -1;
582
601
  }
627
646
    pf = PF_INET;
628
647
    break;
629
648
  default:
630
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
649
    fprintf_plus(stderr, "Bad address family: %d\n", af);
631
650
    errno = EINVAL;
632
651
    return -1;
633
652
  }
638
657
  }
639
658
  
640
659
  if(debug){
641
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
642
 
            "\n", ip, port);
 
660
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
661
                 PRIu16 "\n", ip, port);
643
662
  }
644
663
  
645
664
  tcp_sd = socket(pf, SOCK_STREAM, 0);
671
690
  }
672
691
  if(ret == 0){
673
692
    int e = errno;
674
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
693
    fprintf_plus(stderr, "Bad address: %s\n", ip);
675
694
    errno = e;
676
695
    goto mandos_end;
677
696
  }
682
701
    
683
702
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
684
703
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
685
 
                              -Wunreachable-code*/
 
704
                                -Wunreachable-code*/
686
705
      if(if_index == AVAHI_IF_UNSPEC){
687
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
688
 
                " without a network interface\n");
 
706
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
707
                     " incomplete without a network interface\n");
689
708
        errno = EINVAL;
690
709
        goto mandos_end;
691
710
      }
709
728
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
710
729
        perror_plus("if_indextoname");
711
730
      } else {
712
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
713
 
                ip, interface, port);
 
731
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
732
                     "\n", ip, interface, port);
714
733
      }
715
734
    } else {
716
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
717
 
              port);
 
735
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
736
                   ip, port);
718
737
    }
719
738
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
720
739
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
730
749
      perror_plus("inet_ntop");
731
750
    } else {
732
751
      if(strcmp(addrstr, ip) != 0){
733
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
752
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
734
753
      }
735
754
    }
736
755
  }
764
783
  while(true){
765
784
    size_t out_size = strlen(out);
766
785
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
767
 
                                   out_size - written));
 
786
                                        out_size - written));
768
787
    if(ret == -1){
769
788
      int e = errno;
770
789
      perror_plus("write");
790
809
  }
791
810
  
792
811
  if(debug){
793
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
812
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
794
813
  }
795
814
  
796
815
  if(quit_now){
816
835
  
817
836
  if(ret != GNUTLS_E_SUCCESS){
818
837
    if(debug){
819
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
838
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
820
839
      gnutls_perror(ret);
821
840
    }
822
841
    errno = EPROTO;
826
845
  /* Read OpenPGP packet that contains the wanted password */
827
846
  
828
847
  if(debug){
829
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
830
 
            ip);
 
848
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
849
                 " %s\n", ip);
831
850
  }
832
851
  
833
852
  while(true){
838
857
    }
839
858
    
840
859
    buffer_capacity = incbuffer(&buffer, buffer_length,
841
 
                                   buffer_capacity);
 
860
                                buffer_capacity);
842
861
    if(buffer_capacity == 0){
843
862
      int e = errno;
844
863
      perror_plus("incbuffer");
871
890
          }
872
891
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
873
892
        if(ret < 0){
874
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
893
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
894
                       "***\n");
875
895
          gnutls_perror(ret);
876
896
          errno = EPROTO;
877
897
          goto mandos_end;
878
898
        }
879
899
        break;
880
900
      default:
881
 
        fprintf(stderr, "Unknown error while reading data from"
882
 
                " encrypted session with Mandos server\n");
 
901
        fprintf_plus(stderr, "Unknown error while reading data from"
 
902
                     " encrypted session with Mandos server\n");
883
903
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
884
904
        errno = EIO;
885
905
        goto mandos_end;
890
910
  }
891
911
  
892
912
  if(debug){
893
 
    fprintf(stderr, "Closing TLS session\n");
 
913
    fprintf_plus(stderr, "Closing TLS session\n");
894
914
  }
895
915
  
896
916
  if(quit_now){
908
928
  
909
929
  if(buffer_length > 0){
910
930
    ssize_t decrypted_buffer_size;
911
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
912
 
                                               buffer_length,
 
931
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
913
932
                                               &decrypted_buffer);
914
933
    if(decrypted_buffer_size >= 0){
915
934
      
926
945
        if(ret == 0 and ferror(stdout)){
927
946
          int e = errno;
928
947
          if(debug){
929
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
930
 
                    strerror(errno));
 
948
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
949
                         strerror(errno));
931
950
          }
932
951
          errno = e;
933
952
          goto mandos_end;
990
1009
  switch(event){
991
1010
  default:
992
1011
  case AVAHI_RESOLVER_FAILURE:
993
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
994
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
995
 
            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)));
996
1016
    break;
997
1017
    
998
1018
  case AVAHI_RESOLVER_FOUND:
1000
1020
      char ip[AVAHI_ADDRESS_STR_MAX];
1001
1021
      avahi_address_snprint(ip, sizeof(ip), address);
1002
1022
      if(debug){
1003
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1004
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1005
 
                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);
1006
1026
      }
1007
1027
      int ret = start_mandos_communication(ip, port, interface,
1008
1028
                                           avahi_proto_to_af(proto));
1040
1060
  default:
1041
1061
  case AVAHI_BROWSER_FAILURE:
1042
1062
    
1043
 
    fprintf(stderr, "(Avahi browser) %s\n",
1044
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1063
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1064
                 avahi_strerror(avahi_server_errno(mc.server)));
1045
1065
    avahi_simple_poll_quit(mc.simple_poll);
1046
1066
    return;
1047
1067
    
1054
1074
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1055
1075
                                    name, type, domain, protocol, 0,
1056
1076
                                    resolve_callback, NULL) == NULL)
1057
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1058
 
              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)));
1059
1080
    break;
1060
1081
    
1061
1082
  case AVAHI_BROWSER_REMOVE:
1064
1085
  case AVAHI_BROWSER_ALL_FOR_NOW:
1065
1086
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1066
1087
    if(debug){
1067
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1088
      fprintf_plus(stderr, "No Mandos server found, still"
 
1089
                   " searching...\n");
1068
1090
    }
1069
1091
    break;
1070
1092
  }
1109
1131
  /* Reject the loopback device */
1110
1132
  if(ifr->ifr_flags & IFF_LOOPBACK){
1111
1133
    if(debug){
1112
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1113
 
              ifname);
 
1134
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1135
                   ifname);
1114
1136
    }
1115
1137
    return false;
1116
1138
  }
1117
1139
  /* Accept point-to-point devices only if connect_to is specified */
1118
1140
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1119
1141
    if(debug){
1120
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1121
 
              ifname);
 
1142
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1143
                   " \"%s\"\n", ifname);
1122
1144
    }
1123
1145
    return true;
1124
1146
  }
1125
1147
  /* Otherwise, reject non-broadcast-capable devices */
1126
1148
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1127
1149
    if(debug){
1128
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1129
 
              ifname);
 
1150
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1151
                   " \"%s\"\n", ifname);
1130
1152
    }
1131
1153
    return false;
1132
1154
  }
1133
1155
  /* Reject non-ARP interfaces (including dummy interfaces) */
1134
1156
  if(ifr->ifr_flags & IFF_NOARP){
1135
1157
    if(debug){
1136
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1158
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1159
                   ifname);
1137
1160
    }
1138
1161
    return false;
1139
1162
  }
1140
1163
  
1141
1164
  /* Accept this device */
1142
1165
  if(debug){
1143
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
 
1166
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1144
1167
  }
1145
1168
  return true;
1146
1169
}
1151
1174
 * (This function is passed to scandir(3) as a filter function.)
1152
1175
 */
1153
1176
int good_interface(const struct dirent *if_entry){
1154
 
  int ret;
1155
1177
  if(if_entry->d_name[0] == '.'){
1156
1178
    return 0;
1157
1179
  }
 
1180
  
1158
1181
  struct ifreq ifr;
 
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
    }
 
1187
    return 0;
 
1188
  }
 
1189
  
 
1190
  if(not good_flags(if_entry->d_name, &ifr)){
 
1191
    return 0;
 
1192
  }
 
1193
  return 1;
 
1194
}
1159
1195
 
 
1196
/* 
 
1197
 * This function determines if a directory entry in /sys/class/net
 
1198
 * corresponds to an acceptable network device which is up.
 
1199
 * (This function is passed to scandir(3) as a filter function.)
 
1200
 */
 
1201
int up_interface(const struct dirent *if_entry){
 
1202
  if(if_entry->d_name[0] == '.'){
 
1203
    return 0;
 
1204
  }
 
1205
  
 
1206
  struct ifreq ifr;
1160
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
  
 
1215
  /* 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
    }
1161
1230
    return 0;
1162
1231
  }
1163
1232
  
1178
1247
  return 1;
1179
1248
}
1180
1249
 
 
1250
/* Is this directory entry a runnable program? */
 
1251
int runnable_hook(const struct dirent *direntry){
 
1252
  int ret;
 
1253
  size_t sret;
 
1254
  struct stat st;
 
1255
  
 
1256
  if((direntry->d_name)[0] == '\0'){
 
1257
    /* Empty name? */
 
1258
    return 0;
 
1259
  }
 
1260
  
 
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);
 
1282
  if(ret == -1){
 
1283
    if(debug){
 
1284
      perror_plus("Could not stat hook");
 
1285
    }
 
1286
    return 0;
 
1287
  }
 
1288
  if(not (S_ISREG(st.st_mode))){
 
1289
    /* Not a regular file */
 
1290
    if(debug){
 
1291
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1292
                   direntry->d_name);
 
1293
    }
 
1294
    return 0;
 
1295
  }
 
1296
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1297
    /* Not executable */
 
1298
    if(debug){
 
1299
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1300
                   direntry->d_name);
 
1301
    }
 
1302
    return 0;
 
1303
  }
 
1304
  return 1;
 
1305
}
 
1306
 
1181
1307
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1182
1308
  int ret;
1183
1309
  struct timespec now;
1187
1313
  while(true){
1188
1314
    if(mc.current_server == NULL){
1189
1315
      if (debug){
1190
 
        fprintf(stderr,
1191
 
                "Wait until first server is found. No timeout!\n");
 
1316
        fprintf_plus(stderr, "Wait until first server is found."
 
1317
                     " No timeout!\n");
1192
1318
      }
1193
1319
      ret = avahi_simple_poll_iterate(s, -1);
1194
1320
    } else {
1195
1321
      if (debug){
1196
 
        fprintf(stderr, "Check current_server if we should run it,"
1197
 
                " or wait\n");
 
1322
        fprintf_plus(stderr, "Check current_server if we should run"
 
1323
                     " it, or wait\n");
1198
1324
      }
1199
1325
      /* the current time */
1200
1326
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1216
1342
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1217
1343
      
1218
1344
      if (debug){
1219
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1345
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1346
                     block_time);
1220
1347
      }
1221
1348
      
1222
1349
      if(block_time <= 0){
1242
1369
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1243
1370
    }
1244
1371
    if(ret != 0){
1245
 
      if (ret > 0 or errno != EINTR) {
 
1372
      if (ret > 0 or errno != EINTR){
1246
1373
        return (ret != 1) ? ret : 0;
1247
1374
      }
1248
1375
    }
1249
1376
  }
1250
1377
}
1251
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
 
1252
1477
int main(int argc, char *argv[]){
1253
1478
  AvahiSServiceBrowser *sb = NULL;
1254
1479
  int error;
1336
1561
        .arg = "SECONDS",
1337
1562
        .doc = "Retry interval used when denied by the mandos server",
1338
1563
        .group = 2 },
 
1564
      { .name = "network-hook-dir", .key = 133,
 
1565
        .arg = "DIR",
 
1566
        .doc = "Directory where network hooks are located",
 
1567
        .group = 2 },
1339
1568
      /*
1340
1569
       * These reproduce what we would get without ARGP_NO_HELP
1341
1570
       */
1394
1623
          argp_error(state, "Bad retry interval");
1395
1624
        }
1396
1625
        break;
 
1626
      case 133:                 /* --network-hook-dir */
 
1627
        hookdir = arg;
 
1628
        break;
1397
1629
        /*
1398
1630
         * These reproduce what we would get without ARGP_NO_HELP
1399
1631
         */
1405
1637
        argp_state_help(state, state->out_stream,
1406
1638
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1407
1639
      case 'V':                 /* --version */
1408
 
        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);
1409
1643
        exit(argp_err_exit_status);
1410
1644
        break;
1411
1645
      default:
1456
1690
        if(ret == -1){
1457
1691
          perror_plus("fstat");
1458
1692
        } else {
1459
 
          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){
1460
1695
            ret = fchown(seckey_fd, uid, gid);
1461
1696
            if(ret == -1){
1462
1697
              perror_plus("fchown");
1476
1711
        if(ret == -1){
1477
1712
          perror_plus("fstat");
1478
1713
        } else {
1479
 
          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){
1480
1716
            ret = fchown(pubkey_fd, uid, gid);
1481
1717
            if(ret == -1){
1482
1718
              perror_plus("fchown");
1495
1731
    }
1496
1732
  }
1497
1733
  
 
1734
  /* Run network hooks */
 
1735
  {
 
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
    }
 
1751
  }
 
1752
  
1498
1753
  if(not debug){
1499
1754
    avahi_set_log_function(empty_log);
1500
1755
  }
1501
 
 
 
1756
  
1502
1757
  if(interface[0] == '\0'){
1503
1758
    struct dirent **direntries;
1504
 
    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,
1505
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
    }
1506
1768
    if(ret >= 1){
1507
 
      /* Pick the first good interface */
 
1769
      /* Pick the first interface returned */
1508
1770
      interface = strdup(direntries[0]->d_name);
1509
1771
      if(debug){
1510
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1772
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1511
1773
      }
1512
1774
      if(interface == NULL){
1513
1775
        perror_plus("malloc");
1518
1780
      free(direntries);
1519
1781
    } else {
1520
1782
      free(direntries);
1521
 
      fprintf(stderr, "Could not find a network interface\n");
 
1783
      fprintf_plus(stderr, "Could not find a network interface\n");
1522
1784
      exitcode = EXIT_FAILURE;
1523
1785
      goto end;
1524
1786
    }
1530
1792
  srand((unsigned int) time(NULL));
1531
1793
  mc.simple_poll = avahi_simple_poll_new();
1532
1794
  if(mc.simple_poll == NULL){
1533
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1795
    fprintf_plus(stderr,
 
1796
                 "Avahi: Failed to create simple poll object.\n");
1534
1797
    exitcode = EX_UNAVAILABLE;
1535
1798
    goto end;
1536
1799
  }
1602
1865
  if(strcmp(interface, "none") != 0){
1603
1866
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1604
1867
    if(if_index == 0){
1605
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1868
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1606
1869
      exitcode = EX_UNAVAILABLE;
1607
1870
      goto end;
1608
1871
    }
1728
1991
#endif  /* __linux__ */
1729
1992
    /* Lower privileges */
1730
1993
    errno = 0;
1731
 
    if(take_down_interface){
1732
 
      /* Lower privileges */
1733
 
      ret = seteuid(uid);
1734
 
      if(ret == -1){
1735
 
        perror_plus("seteuid");
1736
 
      }
1737
 
    } else {
1738
 
      /* Lower privileges permanently */
1739
 
      ret = setuid(uid);
1740
 
      if(ret == -1){
1741
 
        perror_plus("setuid");
1742
 
      }
 
1994
    /* Lower privileges */
 
1995
    ret = seteuid(uid);
 
1996
    if(ret == -1){
 
1997
      perror_plus("seteuid");
1743
1998
    }
1744
1999
  }
1745
2000
  
1749
2004
  
1750
2005
  ret = init_gnutls_global(pubkey, seckey);
1751
2006
  if(ret == -1){
1752
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2007
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1753
2008
    exitcode = EX_UNAVAILABLE;
1754
2009
    goto end;
1755
2010
  } else {
1771
2026
  }
1772
2027
  
1773
2028
  if(not init_gpgme(pubkey, seckey, tempdir)){
1774
 
    fprintf(stderr, "init_gpgme failed\n");
 
2029
    fprintf_plus(stderr, "init_gpgme failed\n");
1775
2030
    exitcode = EX_UNAVAILABLE;
1776
2031
    goto end;
1777
2032
  } else {
1787
2042
    /* (Mainly meant for debugging) */
1788
2043
    char *address = strrchr(connect_to, ':');
1789
2044
    if(address == NULL){
1790
 
      fprintf(stderr, "No colon in address\n");
 
2045
      fprintf_plus(stderr, "No colon in address\n");
1791
2046
      exitcode = EX_USAGE;
1792
2047
      goto end;
1793
2048
    }
1801
2056
    tmpmax = strtoimax(address+1, &tmp, 10);
1802
2057
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1803
2058
       or tmpmax != (uint16_t)tmpmax){
1804
 
      fprintf(stderr, "Bad port number\n");
 
2059
      fprintf_plus(stderr, "Bad port number\n");
1805
2060
      exitcode = EX_USAGE;
1806
2061
      goto end;
1807
2062
    }
1837
2092
        break;
1838
2093
      }
1839
2094
      if(debug){
1840
 
        fprintf(stderr, "Retrying in %d seconds\n",
1841
 
                (int)retry_interval);
 
2095
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2096
                     (int)retry_interval);
1842
2097
      }
1843
2098
      sleep((int)retry_interval);
1844
2099
    }
1846
2101
    if (not quit_now){
1847
2102
      exitcode = EXIT_SUCCESS;
1848
2103
    }
1849
 
 
 
2104
    
1850
2105
    goto end;
1851
2106
  }
1852
2107
  
1874
2129
  
1875
2130
  /* Check if creating the Avahi server object succeeded */
1876
2131
  if(mc.server == NULL){
1877
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1878
 
            avahi_strerror(error));
 
2132
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2133
                 avahi_strerror(error));
1879
2134
    exitcode = EX_UNAVAILABLE;
1880
2135
    goto end;
1881
2136
  }
1889
2144
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1890
2145
                                   NULL, 0, browse_callback, NULL);
1891
2146
  if(sb == NULL){
1892
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1893
 
            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)));
1894
2149
    exitcode = EX_UNAVAILABLE;
1895
2150
    goto end;
1896
2151
  }
1902
2157
  /* Run the main loop */
1903
2158
  
1904
2159
  if(debug){
1905
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2160
    fprintf_plus(stderr, "Starting Avahi loop search\n");
1906
2161
  }
1907
2162
 
1908
2163
  ret = avahi_loop_with_timeout(mc.simple_poll,
1909
2164
                                (int)(retry_interval * 1000));
1910
2165
  if(debug){
1911
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
1912
 
            (ret == 0) ? "successfully" : "with error");
 
2166
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2167
                 (ret == 0) ? "successfully" : "with error");
1913
2168
  }
1914
2169
  
1915
2170
 end:
1916
2171
  
1917
2172
  if(debug){
1918
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2173
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1919
2174
  }
1920
2175
  
1921
2176
  /* Cleanup things */
1949
2204
    }
1950
2205
  }
1951
2206
  
1952
 
  /* Take down the network interface */
1953
 
  if(take_down_interface){
1954
 
    /* Re-raise priviliges */
 
2207
  /* Re-raise priviliges */
 
2208
  {
1955
2209
    errno = 0;
1956
2210
    ret = seteuid(0);
1957
2211
    if(ret == -1){
1958
2212
      perror_plus("seteuid");
1959
2213
    }
1960
 
    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){
1961
2221
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1962
2222
      if(ret == -1){
1963
2223
        perror_plus("ioctl SIOCGIFFLAGS");
1964
 
      } else if(network.ifr_flags & IFF_UP) {
 
2224
      } else if(network.ifr_flags & IFF_UP){
1965
2225
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1966
2226
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1967
2227
        if(ret == -1){
1972
2232
      if(ret == -1){
1973
2233
        perror_plus("close");
1974
2234
      }
1975
 
      /* Lower privileges permanently */
1976
 
      errno = 0;
1977
 
      ret = setuid(uid);
1978
 
      if(ret == -1){
1979
 
        perror_plus("setuid");
1980
 
      }
1981
2235
    }
1982
2236
  }
 
2237
  /* Lower privileges permanently */
 
2238
  errno = 0;
 
2239
  ret = setuid(uid);
 
2240
  if(ret == -1){
 
2241
    perror_plus("setuid");
 
2242
  }
1983
2243
  
1984
2244
  /* Removes the GPGME temp directory and all files inside */
1985
2245
  if(tempdir_created){
1999
2259
        }
2000
2260
        ret = remove(fullname);
2001
2261
        if(ret == -1){
2002
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2003
 
                  strerror(errno));
 
2262
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2263
                       strerror(errno));
2004
2264
        }
2005
2265
        free(fullname);
2006
2266
      }