/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

* plugins.d/mandos-client.c (main): Add "DELAY" environment variable.
                                    Check return value from setenv().

Show diffs side-by-side

added added

removed removed

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