/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

* initramfs-tools-hook: Set DEVICE for network hooks.

Show diffs side-by-side

added added

removed removed

Lines of Context:
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
 
76
                                   setgid(), pause(), _exit() */
77
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
78
#include <iso646.h>             /* not, or, and */
79
79
#include <argp.h>               /* struct argp_option, error_t, struct
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
#include <grp.h>                /* setgroups() */
88
91
 
89
92
#ifdef __linux__
90
93
#include <sys/klog.h>           /* klogctl() */
108
111
                                   init_gnutls_session(),
109
112
                                   GNUTLS_* */
110
113
#include <gnutls/openpgp.h>
111
 
                          /* gnutls_certificate_set_openpgp_key_file(),
112
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
114
                         /* gnutls_certificate_set_openpgp_key_file(),
 
115
                            GNUTLS_OPENPGP_FMT_BASE64 */
113
116
 
114
117
/* GPGME */
115
118
#include <gpgme.h>              /* All GPGME types, constants and
131
134
const char *argp_program_bug_address = "<mandos@recompile.se>";
132
135
static const char sys_class_net[] = "/sys/class/net";
133
136
char *connect_to = NULL;
 
137
const char *hookdir = HOOKDIR;
134
138
 
135
139
/* Doubly linked list that need to be circularly linked when used */
136
140
typedef struct server{
171
175
  perror(print_text);
172
176
}
173
177
 
 
178
int fprintf_plus(FILE *stream, const char *format, ...){
 
179
  va_list ap;
 
180
  va_start (ap, format);
 
181
  
 
182
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
183
                             program_invocation_short_name));
 
184
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
185
}
 
186
 
174
187
/*
175
188
 * Make additional room in "buffer" for at least BUFFER_SIZE more
176
189
 * bytes. "buffer_capacity" is how much is currently allocated,
177
190
 * "buffer_length" is how much is already used.
178
191
 */
179
192
size_t incbuffer(char **buffer, size_t buffer_length,
180
 
                  size_t buffer_capacity){
 
193
                 size_t buffer_capacity){
181
194
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
182
195
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
183
196
    if(buffer == NULL){
189
202
}
190
203
 
191
204
/* Add server to set of servers to retry periodically */
192
 
int add_server(const char *ip, uint16_t port,
193
 
                 AvahiIfIndex if_index,
194
 
                 int af){
 
205
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
206
               int af){
195
207
  int ret;
196
208
  server *new_server = malloc(sizeof(server));
197
209
  if(new_server == NULL){
199
211
    return -1;
200
212
  }
201
213
  *new_server = (server){ .ip = strdup(ip),
202
 
                         .port = port,
203
 
                         .if_index = if_index,
204
 
                         .af = af };
 
214
                          .port = port,
 
215
                          .if_index = if_index,
 
216
                          .af = af };
205
217
  if(new_server->ip == NULL){
206
218
    perror_plus("strdup");
207
219
    return -1;
229
241
/* 
230
242
 * Initialize GPGME.
231
243
 */
232
 
static bool init_gpgme(const char *seckey,
233
 
                       const char *pubkey, const char *tempdir){
 
244
static bool init_gpgme(const char *seckey, const char *pubkey,
 
245
                       const char *tempdir){
234
246
  gpgme_error_t rc;
235
247
  gpgme_engine_info_t engine_info;
236
248
  
251
263
    
252
264
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
253
265
    if(rc != GPG_ERR_NO_ERROR){
254
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
255
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
266
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
267
                   gpgme_strsource(rc), gpgme_strerror(rc));
256
268
      return false;
257
269
    }
258
270
    
259
271
    rc = gpgme_op_import(mc.ctx, pgp_data);
260
272
    if(rc != GPG_ERR_NO_ERROR){
261
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
262
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
273
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
274
                   gpgme_strsource(rc), gpgme_strerror(rc));
263
275
      return false;
264
276
    }
265
277
    
272
284
  }
273
285
  
274
286
  if(debug){
275
 
    fprintf(stderr, "Initializing GPGME\n");
 
287
    fprintf_plus(stderr, "Initializing GPGME\n");
276
288
  }
277
289
  
278
290
  /* Init GPGME */
279
291
  gpgme_check_version(NULL);
280
292
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
281
293
  if(rc != GPG_ERR_NO_ERROR){
282
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
283
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
294
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
295
                 gpgme_strsource(rc), gpgme_strerror(rc));
284
296
    return false;
285
297
  }
286
298
  
287
299
  /* Set GPGME home directory for the OpenPGP engine only */
288
300
  rc = gpgme_get_engine_info(&engine_info);
289
301
  if(rc != GPG_ERR_NO_ERROR){
290
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
291
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
302
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
303
                 gpgme_strsource(rc), gpgme_strerror(rc));
292
304
    return false;
293
305
  }
294
306
  while(engine_info != NULL){
300
312
    engine_info = engine_info->next;
301
313
  }
302
314
  if(engine_info == NULL){
303
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
315
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
316
                 tempdir);
304
317
    return false;
305
318
  }
306
319
  
307
320
  /* Create new GPGME "context" */
308
321
  rc = gpgme_new(&(mc.ctx));
309
322
  if(rc != GPG_ERR_NO_ERROR){
310
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
311
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
323
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
324
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
325
                 gpgme_strerror(rc));
312
326
    return false;
313
327
  }
314
328
  
333
347
  ssize_t plaintext_length = 0;
334
348
  
335
349
  if(debug){
336
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
350
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
337
351
  }
338
352
  
339
353
  /* Create new GPGME data buffer from memory cryptotext */
340
354
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
341
355
                               0);
342
356
  if(rc != GPG_ERR_NO_ERROR){
343
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
344
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
357
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
358
                 gpgme_strsource(rc), gpgme_strerror(rc));
345
359
    return -1;
346
360
  }
347
361
  
348
362
  /* Create new empty GPGME data buffer for the plaintext */
349
363
  rc = gpgme_data_new(&dh_plain);
350
364
  if(rc != GPG_ERR_NO_ERROR){
351
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
352
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
365
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
366
                 "bad gpgme_data_new: %s: %s\n",
 
367
                 gpgme_strsource(rc), gpgme_strerror(rc));
353
368
    gpgme_data_release(dh_crypto);
354
369
    return -1;
355
370
  }
358
373
     data buffer */
359
374
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
360
375
  if(rc != GPG_ERR_NO_ERROR){
361
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
362
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
376
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
377
                 gpgme_strsource(rc), gpgme_strerror(rc));
363
378
    plaintext_length = -1;
364
379
    if(debug){
365
380
      gpgme_decrypt_result_t result;
366
381
      result = gpgme_op_decrypt_result(mc.ctx);
367
382
      if(result == NULL){
368
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
383
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
369
384
      } else {
370
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
371
 
                result->unsupported_algorithm);
372
 
        fprintf(stderr, "Wrong key usage: %u\n",
373
 
                result->wrong_key_usage);
 
385
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
386
                     result->unsupported_algorithm);
 
387
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
388
                     result->wrong_key_usage);
374
389
        if(result->file_name != NULL){
375
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
390
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
376
391
        }
377
392
        gpgme_recipient_t recipient;
378
393
        recipient = result->recipients;
379
394
        while(recipient != NULL){
380
 
          fprintf(stderr, "Public key algorithm: %s\n",
381
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
382
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
383
 
          fprintf(stderr, "Secret key available: %s\n",
384
 
                  recipient->status == GPG_ERR_NO_SECKEY
385
 
                  ? "No" : "Yes");
 
395
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
396
                       gpgme_pubkey_algo_name
 
397
                       (recipient->pubkey_algo));
 
398
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
399
          fprintf_plus(stderr, "Secret key available: %s\n",
 
400
                       recipient->status == GPG_ERR_NO_SECKEY
 
401
                       ? "No" : "Yes");
386
402
          recipient = recipient->next;
387
403
        }
388
404
      }
391
407
  }
392
408
  
393
409
  if(debug){
394
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
410
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
395
411
  }
396
412
  
397
413
  /* Seek back to the beginning of the GPGME plaintext data buffer */
404
420
  *plaintext = NULL;
405
421
  while(true){
406
422
    plaintext_capacity = incbuffer(plaintext,
407
 
                                      (size_t)plaintext_length,
408
 
                                      plaintext_capacity);
 
423
                                   (size_t)plaintext_length,
 
424
                                   plaintext_capacity);
409
425
    if(plaintext_capacity == 0){
410
 
        perror_plus("incbuffer");
411
 
        plaintext_length = -1;
412
 
        goto decrypt_end;
 
426
      perror_plus("incbuffer");
 
427
      plaintext_length = -1;
 
428
      goto decrypt_end;
413
429
    }
414
430
    
415
431
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
428
444
  }
429
445
  
430
446
  if(debug){
431
 
    fprintf(stderr, "Decrypted password is: ");
 
447
    fprintf_plus(stderr, "Decrypted password is: ");
432
448
    for(ssize_t i = 0; i < plaintext_length; i++){
433
449
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
434
450
    }
456
472
/* GnuTLS log function callback */
457
473
static void debuggnutls(__attribute__((unused)) int level,
458
474
                        const char* string){
459
 
  fprintf(stderr, "GnuTLS: %s", string);
 
475
  fprintf_plus(stderr, "GnuTLS: %s", string);
460
476
}
461
477
 
462
478
static int init_gnutls_global(const char *pubkeyfilename,
464
480
  int ret;
465
481
  
466
482
  if(debug){
467
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
483
    fprintf_plus(stderr, "Initializing GnuTLS\n");
468
484
  }
469
485
  
470
486
  ret = gnutls_global_init();
471
487
  if(ret != GNUTLS_E_SUCCESS){
472
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
473
 
            safer_gnutls_strerror(ret));
 
488
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
489
                 safer_gnutls_strerror(ret));
474
490
    return -1;
475
491
  }
476
492
  
485
501
  /* OpenPGP credentials */
486
502
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
487
503
  if(ret != GNUTLS_E_SUCCESS){
488
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
489
 
            safer_gnutls_strerror(ret));
 
504
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
505
                 safer_gnutls_strerror(ret));
490
506
    gnutls_global_deinit();
491
507
    return -1;
492
508
  }
493
509
  
494
510
  if(debug){
495
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
496
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
497
 
            seckeyfilename);
 
511
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
512
                 " secret key %s as GnuTLS credentials\n",
 
513
                 pubkeyfilename,
 
514
                 seckeyfilename);
498
515
  }
499
516
  
500
517
  ret = gnutls_certificate_set_openpgp_key_file
501
518
    (mc.cred, pubkeyfilename, seckeyfilename,
502
519
     GNUTLS_OPENPGP_FMT_BASE64);
503
520
  if(ret != GNUTLS_E_SUCCESS){
504
 
    fprintf(stderr,
505
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
506
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
507
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
508
 
            safer_gnutls_strerror(ret));
 
521
    fprintf_plus(stderr,
 
522
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
523
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
524
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
525
                 safer_gnutls_strerror(ret));
509
526
    goto globalfail;
510
527
  }
511
528
  
512
529
  /* GnuTLS server initialization */
513
530
  ret = gnutls_dh_params_init(&mc.dh_params);
514
531
  if(ret != GNUTLS_E_SUCCESS){
515
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
516
 
            " %s\n", safer_gnutls_strerror(ret));
 
532
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
533
                 " initialization: %s\n",
 
534
                 safer_gnutls_strerror(ret));
517
535
    goto globalfail;
518
536
  }
519
537
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
520
538
  if(ret != GNUTLS_E_SUCCESS){
521
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
522
 
            safer_gnutls_strerror(ret));
 
539
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
540
                 safer_gnutls_strerror(ret));
523
541
    goto globalfail;
524
542
  }
525
543
  
545
563
    }
546
564
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
547
565
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
549
 
            safer_gnutls_strerror(ret));
 
566
    fprintf_plus(stderr,
 
567
                 "Error in GnuTLS session initialization: %s\n",
 
568
                 safer_gnutls_strerror(ret));
550
569
  }
551
570
  
552
571
  {
559
578
      }
560
579
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
561
580
    if(ret != GNUTLS_E_SUCCESS){
562
 
      fprintf(stderr, "Syntax error at: %s\n", err);
563
 
      fprintf(stderr, "GnuTLS error: %s\n",
564
 
              safer_gnutls_strerror(ret));
 
581
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
582
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
583
                   safer_gnutls_strerror(ret));
565
584
      gnutls_deinit(*session);
566
585
      return -1;
567
586
    }
576
595
    }
577
596
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
578
597
  if(ret != GNUTLS_E_SUCCESS){
579
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
580
 
            safer_gnutls_strerror(ret));
 
598
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
599
                 safer_gnutls_strerror(ret));
581
600
    gnutls_deinit(*session);
582
601
    return -1;
583
602
  }
628
647
    pf = PF_INET;
629
648
    break;
630
649
  default:
631
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
650
    fprintf_plus(stderr, "Bad address family: %d\n", af);
632
651
    errno = EINVAL;
633
652
    return -1;
634
653
  }
639
658
  }
640
659
  
641
660
  if(debug){
642
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
643
 
            "\n", ip, port);
 
661
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
662
                 PRIu16 "\n", ip, port);
644
663
  }
645
664
  
646
665
  tcp_sd = socket(pf, SOCK_STREAM, 0);
672
691
  }
673
692
  if(ret == 0){
674
693
    int e = errno;
675
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
694
    fprintf_plus(stderr, "Bad address: %s\n", ip);
676
695
    errno = e;
677
696
    goto mandos_end;
678
697
  }
683
702
    
684
703
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
685
704
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
686
 
                              -Wunreachable-code*/
 
705
                                -Wunreachable-code*/
687
706
      if(if_index == AVAHI_IF_UNSPEC){
688
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
689
 
                " without a network interface\n");
 
707
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
708
                     " incomplete without a network interface\n");
690
709
        errno = EINVAL;
691
710
        goto mandos_end;
692
711
      }
710
729
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
711
730
        perror_plus("if_indextoname");
712
731
      } else {
713
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
714
 
                ip, interface, port);
 
732
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
733
                     "\n", ip, interface, port);
715
734
      }
716
735
    } else {
717
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
718
 
              port);
 
736
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
737
                   ip, port);
719
738
    }
720
739
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
721
740
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
731
750
      perror_plus("inet_ntop");
732
751
    } else {
733
752
      if(strcmp(addrstr, ip) != 0){
734
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
753
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
735
754
      }
736
755
    }
737
756
  }
765
784
  while(true){
766
785
    size_t out_size = strlen(out);
767
786
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
768
 
                                   out_size - written));
 
787
                                        out_size - written));
769
788
    if(ret == -1){
770
789
      int e = errno;
771
790
      perror_plus("write");
791
810
  }
792
811
  
793
812
  if(debug){
794
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
813
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
795
814
  }
796
815
  
797
816
  if(quit_now){
817
836
  
818
837
  if(ret != GNUTLS_E_SUCCESS){
819
838
    if(debug){
820
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
839
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
821
840
      gnutls_perror(ret);
822
841
    }
823
842
    errno = EPROTO;
827
846
  /* Read OpenPGP packet that contains the wanted password */
828
847
  
829
848
  if(debug){
830
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
831
 
            ip);
 
849
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
850
                 " %s\n", ip);
832
851
  }
833
852
  
834
853
  while(true){
839
858
    }
840
859
    
841
860
    buffer_capacity = incbuffer(&buffer, buffer_length,
842
 
                                   buffer_capacity);
 
861
                                buffer_capacity);
843
862
    if(buffer_capacity == 0){
844
863
      int e = errno;
845
864
      perror_plus("incbuffer");
872
891
          }
873
892
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
874
893
        if(ret < 0){
875
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
894
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
895
                       "***\n");
876
896
          gnutls_perror(ret);
877
897
          errno = EPROTO;
878
898
          goto mandos_end;
879
899
        }
880
900
        break;
881
901
      default:
882
 
        fprintf(stderr, "Unknown error while reading data from"
883
 
                " encrypted session with Mandos server\n");
 
902
        fprintf_plus(stderr, "Unknown error while reading data from"
 
903
                     " encrypted session with Mandos server\n");
884
904
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
885
905
        errno = EIO;
886
906
        goto mandos_end;
891
911
  }
892
912
  
893
913
  if(debug){
894
 
    fprintf(stderr, "Closing TLS session\n");
 
914
    fprintf_plus(stderr, "Closing TLS session\n");
895
915
  }
896
916
  
897
917
  if(quit_now){
909
929
  
910
930
  if(buffer_length > 0){
911
931
    ssize_t decrypted_buffer_size;
912
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
913
 
                                               buffer_length,
 
932
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
914
933
                                               &decrypted_buffer);
915
934
    if(decrypted_buffer_size >= 0){
916
935
      
927
946
        if(ret == 0 and ferror(stdout)){
928
947
          int e = errno;
929
948
          if(debug){
930
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
931
 
                    strerror(errno));
 
949
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
950
                         strerror(errno));
932
951
          }
933
952
          errno = e;
934
953
          goto mandos_end;
991
1010
  switch(event){
992
1011
  default:
993
1012
  case AVAHI_RESOLVER_FAILURE:
994
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
995
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
996
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1013
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1014
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1015
                 domain,
 
1016
                 avahi_strerror(avahi_server_errno(mc.server)));
997
1017
    break;
998
1018
    
999
1019
  case AVAHI_RESOLVER_FOUND:
1001
1021
      char ip[AVAHI_ADDRESS_STR_MAX];
1002
1022
      avahi_address_snprint(ip, sizeof(ip), address);
1003
1023
      if(debug){
1004
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1005
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1006
 
                ip, (intmax_t)interface, port);
 
1024
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1025
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1026
                     host_name, ip, (intmax_t)interface, port);
1007
1027
      }
1008
1028
      int ret = start_mandos_communication(ip, port, interface,
1009
1029
                                           avahi_proto_to_af(proto));
1041
1061
  default:
1042
1062
  case AVAHI_BROWSER_FAILURE:
1043
1063
    
1044
 
    fprintf(stderr, "(Avahi browser) %s\n",
1045
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1064
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1065
                 avahi_strerror(avahi_server_errno(mc.server)));
1046
1066
    avahi_simple_poll_quit(mc.simple_poll);
1047
1067
    return;
1048
1068
    
1055
1075
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1056
1076
                                    name, type, domain, protocol, 0,
1057
1077
                                    resolve_callback, NULL) == NULL)
1058
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1059
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1078
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1079
                   " %s\n", name,
 
1080
                   avahi_strerror(avahi_server_errno(mc.server)));
1060
1081
    break;
1061
1082
    
1062
1083
  case AVAHI_BROWSER_REMOVE:
1065
1086
  case AVAHI_BROWSER_ALL_FOR_NOW:
1066
1087
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1067
1088
    if(debug){
1068
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1089
      fprintf_plus(stderr, "No Mandos server found, still"
 
1090
                   " searching...\n");
1069
1091
    }
1070
1092
    break;
1071
1093
  }
1110
1132
  /* Reject the loopback device */
1111
1133
  if(ifr->ifr_flags & IFF_LOOPBACK){
1112
1134
    if(debug){
1113
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1114
 
              ifname);
 
1135
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1136
                   ifname);
1115
1137
    }
1116
1138
    return false;
1117
1139
  }
1118
1140
  /* Accept point-to-point devices only if connect_to is specified */
1119
1141
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1120
1142
    if(debug){
1121
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1122
 
              ifname);
 
1143
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1144
                   " \"%s\"\n", ifname);
1123
1145
    }
1124
1146
    return true;
1125
1147
  }
1126
1148
  /* Otherwise, reject non-broadcast-capable devices */
1127
1149
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1128
1150
    if(debug){
1129
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1130
 
              ifname);
 
1151
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1152
                   " \"%s\"\n", ifname);
1131
1153
    }
1132
1154
    return false;
1133
1155
  }
1134
1156
  /* Reject non-ARP interfaces (including dummy interfaces) */
1135
1157
  if(ifr->ifr_flags & IFF_NOARP){
1136
1158
    if(debug){
1137
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1159
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1160
                   ifname);
1138
1161
    }
1139
1162
    return false;
1140
1163
  }
1141
1164
  
1142
1165
  /* Accept this device */
1143
1166
  if(debug){
1144
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
 
1167
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1145
1168
  }
1146
1169
  return true;
1147
1170
}
1159
1182
  struct ifreq ifr;
1160
1183
  if(not get_flags(if_entry->d_name, &ifr)){
1161
1184
    if(debug){
1162
 
      fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1163
 
              if_entry->d_name);
 
1185
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1186
                   "\"%s\"\n", if_entry->d_name);
1164
1187
    }
1165
1188
    return 0;
1166
1189
  }
1184
1207
  struct ifreq ifr;
1185
1208
  if(not get_flags(if_entry->d_name, &ifr)){
1186
1209
    if(debug){
1187
 
      fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1188
 
              if_entry->d_name);
 
1210
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1211
                   "\"%s\"\n", if_entry->d_name);
1189
1212
    }
1190
1213
    return 0;
1191
1214
  }
1193
1216
  /* Reject down interfaces */
1194
1217
  if(not (ifr.ifr_flags & IFF_UP)){
1195
1218
    if(debug){
1196
 
      fprintf(stderr, "Rejecting down interface \"%s\"\n",
1197
 
              if_entry->d_name);
 
1219
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1220
                   if_entry->d_name);
1198
1221
    }
1199
1222
    return 0;
1200
1223
  }
1202
1225
  /* Reject non-running interfaces */
1203
1226
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1204
1227
    if(debug){
1205
 
      fprintf(stderr, "Rejecting non-running interface \"%s\"\n",
1206
 
              if_entry->d_name);
 
1228
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1229
                   if_entry->d_name);
1207
1230
    }
1208
1231
    return 0;
1209
1232
  }
1228
1251
/* Is this directory entry a runnable program? */
1229
1252
int runnable_hook(const struct dirent *direntry){
1230
1253
  int ret;
 
1254
  size_t sret;
1231
1255
  struct stat st;
1232
1256
  
1233
1257
  if((direntry->d_name)[0] == '\0'){
1235
1259
    return 0;
1236
1260
  }
1237
1261
  
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);
 
1262
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1263
                "abcdefghijklmnopqrstuvwxyz"
 
1264
                "0123456789"
 
1265
                "_-");
 
1266
  if((direntry->d_name)[sret] != '\0'){
 
1267
    /* Contains non-allowed characters */
 
1268
    if(debug){
 
1269
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1270
                   direntry->d_name);
 
1271
    }
 
1272
    return 0;
 
1273
  }
 
1274
  
 
1275
  char *fullname = NULL;
 
1276
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1277
  if(ret < 0){
 
1278
    perror_plus("asprintf");
 
1279
    return 0;
 
1280
  }
 
1281
  
 
1282
  ret = stat(fullname, &st);
1255
1283
  if(ret == -1){
1256
1284
    if(debug){
1257
 
      perror_plus("Could not stat plugin");
 
1285
      perror_plus("Could not stat hook");
1258
1286
    }
1259
1287
    return 0;
1260
1288
  }
1261
1289
  if(not (S_ISREG(st.st_mode))){
1262
1290
    /* Not a regular file */
 
1291
    if(debug){
 
1292
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1293
                   direntry->d_name);
 
1294
    }
1263
1295
    return 0;
1264
1296
  }
1265
1297
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1266
1298
    /* Not executable */
 
1299
    if(debug){
 
1300
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1301
                   direntry->d_name);
 
1302
    }
1267
1303
    return 0;
1268
1304
  }
 
1305
  if(debug){
 
1306
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1307
                 direntry->d_name);
 
1308
  }
1269
1309
  return 1;
1270
1310
}
1271
1311
 
1278
1318
  while(true){
1279
1319
    if(mc.current_server == NULL){
1280
1320
      if (debug){
1281
 
        fprintf(stderr,
1282
 
                "Wait until first server is found. No timeout!\n");
 
1321
        fprintf_plus(stderr, "Wait until first server is found."
 
1322
                     " No timeout!\n");
1283
1323
      }
1284
1324
      ret = avahi_simple_poll_iterate(s, -1);
1285
1325
    } else {
1286
1326
      if (debug){
1287
 
        fprintf(stderr, "Check current_server if we should run it,"
1288
 
                " or wait\n");
 
1327
        fprintf_plus(stderr, "Check current_server if we should run"
 
1328
                     " it, or wait\n");
1289
1329
      }
1290
1330
      /* the current time */
1291
1331
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1307
1347
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1308
1348
      
1309
1349
      if (debug){
1310
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1350
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1351
                     block_time);
1311
1352
      }
1312
1353
      
1313
1354
      if(block_time <= 0){
1333
1374
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1334
1375
    }
1335
1376
    if(ret != 0){
1336
 
      if (ret > 0 or errno != EINTR) {
 
1377
      if (ret > 0 or errno != EINTR){
1337
1378
        return (ret != 1) ? ret : 0;
1338
1379
      }
1339
1380
    }
1340
1381
  }
1341
1382
}
1342
1383
 
 
1384
bool run_network_hooks(const char *mode, const char *interface,
 
1385
                       const float delay){
 
1386
  struct dirent **direntries;
 
1387
  struct dirent *direntry;
 
1388
  int ret;
 
1389
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1390
                         alphasort);
 
1391
  if(numhooks == -1){
 
1392
    perror_plus("scandir");
 
1393
  } else {
 
1394
    int devnull = open("/dev/null", O_RDONLY);
 
1395
    for(int i = 0; i < numhooks; i++){
 
1396
      direntry = direntries[i];
 
1397
      char *fullname = NULL;
 
1398
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1399
      if(ret < 0){
 
1400
        perror_plus("asprintf");
 
1401
        continue;
 
1402
      }
 
1403
      if(debug){
 
1404
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1405
                     direntry->d_name);
 
1406
      }
 
1407
      pid_t hook_pid = fork();
 
1408
      if(hook_pid == 0){
 
1409
        /* Child */
 
1410
        /* Raise privileges */
 
1411
        errno = 0;
 
1412
        ret = seteuid(0);
 
1413
        if(ret == -1){
 
1414
          perror_plus("seteuid");
 
1415
        }
 
1416
        /* Raise privileges even more */
 
1417
        errno = 0;
 
1418
        ret = setuid(0);
 
1419
        if(ret == -1){
 
1420
          perror_plus("setuid");
 
1421
        }
 
1422
        /* Set group */
 
1423
        errno = 0;
 
1424
        ret = setgid(0);
 
1425
        if(ret == -1){
 
1426
          perror_plus("setgid");
 
1427
        }
 
1428
        /* Reset supplementary groups */
 
1429
        errno = 0;
 
1430
        ret = setgroups(0, NULL);
 
1431
        if(ret == -1){
 
1432
          perror_plus("setgroups");
 
1433
        }
 
1434
        dup2(devnull, STDIN_FILENO);
 
1435
        close(devnull);
 
1436
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1437
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1438
        if(ret == -1){
 
1439
          perror_plus("setenv");
 
1440
          _exit(EX_OSERR);
 
1441
        }
 
1442
        ret = setenv("DEVICE", interface, 1);
 
1443
        if(ret == -1){
 
1444
          perror_plus("setenv");
 
1445
          _exit(EX_OSERR);
 
1446
        }
 
1447
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1448
        if(ret == -1){
 
1449
          perror_plus("setenv");
 
1450
          _exit(EX_OSERR);
 
1451
        }
 
1452
        ret = setenv("MODE", mode, 1);
 
1453
        if(ret == -1){
 
1454
          perror_plus("setenv");
 
1455
          _exit(EX_OSERR);
 
1456
        }
 
1457
        char *delaystring;
 
1458
        ret = asprintf(&delaystring, "%f", delay);
 
1459
        if(ret == -1){
 
1460
          perror_plus("asprintf");
 
1461
          _exit(EX_OSERR);
 
1462
        }
 
1463
        ret = setenv("DELAY", delaystring, 1);
 
1464
        if(ret == -1){
 
1465
          free(delaystring);
 
1466
          perror_plus("setenv");
 
1467
          _exit(EX_OSERR);
 
1468
        }
 
1469
        free(delaystring);
 
1470
        ret = execl(fullname, direntry->d_name, mode, NULL);
 
1471
        perror_plus("execl");
 
1472
      } else {
 
1473
        int status;
 
1474
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1475
          perror_plus("waitpid");
 
1476
          free(fullname);
 
1477
          continue;
 
1478
        }
 
1479
        if(WIFEXITED(status)){
 
1480
          if(WEXITSTATUS(status) != 0){
 
1481
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1482
                         " with status %d\n", direntry->d_name,
 
1483
                         WEXITSTATUS(status));
 
1484
            free(fullname);
 
1485
            continue;
 
1486
          }
 
1487
        } else if(WIFSIGNALED(status)){
 
1488
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1489
                       " signal %d\n", direntry->d_name,
 
1490
                       WTERMSIG(status));
 
1491
          free(fullname);
 
1492
          continue;
 
1493
        } else {
 
1494
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1495
                       " crashed\n", direntry->d_name);
 
1496
          free(fullname);
 
1497
          continue;
 
1498
        }
 
1499
      }
 
1500
      free(fullname);
 
1501
      if(debug){
 
1502
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1503
                     direntry->d_name);
 
1504
      }
 
1505
    }
 
1506
    close(devnull);
 
1507
  }
 
1508
  return true;
 
1509
}
 
1510
 
1343
1511
int main(int argc, char *argv[]){
1344
1512
  AvahiSServiceBrowser *sb = NULL;
1345
1513
  int error;
1427
1595
        .arg = "SECONDS",
1428
1596
        .doc = "Retry interval used when denied by the mandos server",
1429
1597
        .group = 2 },
 
1598
      { .name = "network-hook-dir", .key = 133,
 
1599
        .arg = "DIR",
 
1600
        .doc = "Directory where network hooks are located",
 
1601
        .group = 2 },
1430
1602
      /*
1431
1603
       * These reproduce what we would get without ARGP_NO_HELP
1432
1604
       */
1485
1657
          argp_error(state, "Bad retry interval");
1486
1658
        }
1487
1659
        break;
 
1660
      case 133:                 /* --network-hook-dir */
 
1661
        hookdir = arg;
 
1662
        break;
1488
1663
        /*
1489
1664
         * These reproduce what we would get without ARGP_NO_HELP
1490
1665
         */
1496
1671
        argp_state_help(state, state->out_stream,
1497
1672
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1498
1673
      case 'V':                 /* --version */
1499
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1674
        fprintf_plus(state->out_stream,
 
1675
                     "Mandos plugin mandos-client: ");
 
1676
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1500
1677
        exit(argp_err_exit_status);
1501
1678
        break;
1502
1679
      default:
1529
1706
  {
1530
1707
    /* Work around Debian bug #633582:
1531
1708
       <http://bugs.debian.org/633582> */
1532
 
    struct stat st;
1533
1709
    
1534
1710
    /* Re-raise priviliges */
1535
1711
    errno = 0;
1536
1712
    ret = seteuid(0);
1537
1713
    if(ret == -1){
1538
1714
      perror_plus("seteuid");
1539
 
    }
1540
 
    
1541
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1542
 
      int seckey_fd = open(seckey, O_RDONLY);
1543
 
      if(seckey_fd == -1){
1544
 
        perror_plus("open");
1545
 
      } else {
1546
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1547
 
        if(ret == -1){
1548
 
          perror_plus("fstat");
1549
 
        } else {
1550
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1551
 
            ret = fchown(seckey_fd, uid, gid);
1552
 
            if(ret == -1){
1553
 
              perror_plus("fchown");
1554
 
            }
1555
 
          }
1556
 
        }
1557
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1558
 
      }
1559
 
    }
1560
 
    
1561
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1562
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1563
 
      if(pubkey_fd == -1){
1564
 
        perror_plus("open");
1565
 
      } else {
1566
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1567
 
        if(ret == -1){
1568
 
          perror_plus("fstat");
1569
 
        } else {
1570
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1571
 
            ret = fchown(pubkey_fd, uid, gid);
1572
 
            if(ret == -1){
1573
 
              perror_plus("fchown");
1574
 
            }
1575
 
          }
1576
 
        }
1577
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1578
 
      }
1579
 
    }
1580
 
    
1581
 
    /* Lower privileges */
1582
 
    errno = 0;
1583
 
    ret = seteuid(uid);
1584
 
    if(ret == -1){
1585
 
      perror_plus("seteuid");
 
1715
    } else {
 
1716
      struct stat st;
 
1717
      
 
1718
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1719
        int seckey_fd = open(seckey, O_RDONLY);
 
1720
        if(seckey_fd == -1){
 
1721
          perror_plus("open");
 
1722
        } else {
 
1723
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1724
          if(ret == -1){
 
1725
            perror_plus("fstat");
 
1726
          } else {
 
1727
            if(S_ISREG(st.st_mode)
 
1728
               and st.st_uid == 0 and st.st_gid == 0){
 
1729
              ret = fchown(seckey_fd, uid, gid);
 
1730
              if(ret == -1){
 
1731
                perror_plus("fchown");
 
1732
              }
 
1733
            }
 
1734
          }
 
1735
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
1736
        }
 
1737
      }
 
1738
    
 
1739
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1740
        int pubkey_fd = open(pubkey, O_RDONLY);
 
1741
        if(pubkey_fd == -1){
 
1742
          perror_plus("open");
 
1743
        } else {
 
1744
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1745
          if(ret == -1){
 
1746
            perror_plus("fstat");
 
1747
          } else {
 
1748
            if(S_ISREG(st.st_mode)
 
1749
               and st.st_uid == 0 and st.st_gid == 0){
 
1750
              ret = fchown(pubkey_fd, uid, gid);
 
1751
              if(ret == -1){
 
1752
                perror_plus("fchown");
 
1753
              }
 
1754
            }
 
1755
          }
 
1756
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1757
        }
 
1758
      }
 
1759
    
 
1760
      /* Lower privileges */
 
1761
      errno = 0;
 
1762
      ret = seteuid(uid);
 
1763
      if(ret == -1){
 
1764
        perror_plus("seteuid");
 
1765
      }
1586
1766
    }
1587
1767
  }
1588
1768
  
1589
 
  /* Find network hooks and run them */
1590
 
  {
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);
 
1769
  /* Run network hooks */
 
1770
  if(not run_network_hooks("start", interface, delay)){
 
1771
    goto end;
1648
1772
  }
1649
1773
  
1650
1774
  if(not debug){
1666
1790
      /* Pick the first interface returned */
1667
1791
      interface = strdup(direntries[0]->d_name);
1668
1792
      if(debug){
1669
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1793
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1670
1794
      }
1671
1795
      if(interface == NULL){
1672
1796
        perror_plus("malloc");
1677
1801
      free(direntries);
1678
1802
    } else {
1679
1803
      free(direntries);
1680
 
      fprintf(stderr, "Could not find a network interface\n");
 
1804
      fprintf_plus(stderr, "Could not find a network interface\n");
1681
1805
      exitcode = EXIT_FAILURE;
1682
1806
      goto end;
1683
1807
    }
1689
1813
  srand((unsigned int) time(NULL));
1690
1814
  mc.simple_poll = avahi_simple_poll_new();
1691
1815
  if(mc.simple_poll == NULL){
1692
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1816
    fprintf_plus(stderr,
 
1817
                 "Avahi: Failed to create simple poll object.\n");
1693
1818
    exitcode = EX_UNAVAILABLE;
1694
1819
    goto end;
1695
1820
  }
1761
1886
  if(strcmp(interface, "none") != 0){
1762
1887
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1763
1888
    if(if_index == 0){
1764
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1889
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1765
1890
      exitcode = EX_UNAVAILABLE;
1766
1891
      goto end;
1767
1892
    }
1887
2012
#endif  /* __linux__ */
1888
2013
    /* Lower privileges */
1889
2014
    errno = 0;
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
 
      }
 
2015
    /* Lower privileges */
 
2016
    ret = seteuid(uid);
 
2017
    if(ret == -1){
 
2018
      perror_plus("seteuid");
1902
2019
    }
1903
2020
  }
1904
2021
  
1908
2025
  
1909
2026
  ret = init_gnutls_global(pubkey, seckey);
1910
2027
  if(ret == -1){
1911
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2028
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1912
2029
    exitcode = EX_UNAVAILABLE;
1913
2030
    goto end;
1914
2031
  } else {
1930
2047
  }
1931
2048
  
1932
2049
  if(not init_gpgme(pubkey, seckey, tempdir)){
1933
 
    fprintf(stderr, "init_gpgme failed\n");
 
2050
    fprintf_plus(stderr, "init_gpgme failed\n");
1934
2051
    exitcode = EX_UNAVAILABLE;
1935
2052
    goto end;
1936
2053
  } else {
1946
2063
    /* (Mainly meant for debugging) */
1947
2064
    char *address = strrchr(connect_to, ':');
1948
2065
    if(address == NULL){
1949
 
      fprintf(stderr, "No colon in address\n");
 
2066
      fprintf_plus(stderr, "No colon in address\n");
1950
2067
      exitcode = EX_USAGE;
1951
2068
      goto end;
1952
2069
    }
1960
2077
    tmpmax = strtoimax(address+1, &tmp, 10);
1961
2078
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1962
2079
       or tmpmax != (uint16_t)tmpmax){
1963
 
      fprintf(stderr, "Bad port number\n");
 
2080
      fprintf_plus(stderr, "Bad port number\n");
1964
2081
      exitcode = EX_USAGE;
1965
2082
      goto end;
1966
2083
    }
1996
2113
        break;
1997
2114
      }
1998
2115
      if(debug){
1999
 
        fprintf(stderr, "Retrying in %d seconds\n",
2000
 
                (int)retry_interval);
 
2116
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2117
                     (int)retry_interval);
2001
2118
      }
2002
2119
      sleep((int)retry_interval);
2003
2120
    }
2033
2150
  
2034
2151
  /* Check if creating the Avahi server object succeeded */
2035
2152
  if(mc.server == NULL){
2036
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2037
 
            avahi_strerror(error));
 
2153
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2154
                 avahi_strerror(error));
2038
2155
    exitcode = EX_UNAVAILABLE;
2039
2156
    goto end;
2040
2157
  }
2048
2165
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2049
2166
                                   NULL, 0, browse_callback, NULL);
2050
2167
  if(sb == NULL){
2051
 
    fprintf(stderr, "Failed to create service browser: %s\n",
2052
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2168
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2169
                 avahi_strerror(avahi_server_errno(mc.server)));
2053
2170
    exitcode = EX_UNAVAILABLE;
2054
2171
    goto end;
2055
2172
  }
2061
2178
  /* Run the main loop */
2062
2179
  
2063
2180
  if(debug){
2064
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2181
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2065
2182
  }
2066
2183
 
2067
2184
  ret = avahi_loop_with_timeout(mc.simple_poll,
2068
2185
                                (int)(retry_interval * 1000));
2069
2186
  if(debug){
2070
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2071
 
            (ret == 0) ? "successfully" : "with error");
 
2187
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2188
                 (ret == 0) ? "successfully" : "with error");
2072
2189
  }
2073
2190
  
2074
2191
 end:
2075
2192
  
2076
2193
  if(debug){
2077
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2194
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2078
2195
  }
2079
2196
  
2080
2197
  /* Cleanup things */
2096
2213
  if(gpgme_initialized){
2097
2214
    gpgme_release(mc.ctx);
2098
2215
  }
2099
 
 
 
2216
  
2100
2217
  /* Cleans up the circular linked list of Mandos servers the client
2101
2218
     has seen */
2102
2219
  if(mc.current_server != NULL){
2108
2225
    }
2109
2226
  }
2110
2227
  
2111
 
  /* XXX run network hooks "stop" here  */
 
2228
  /* Run network hooks */
 
2229
  run_network_hooks("stop", interface, delay);
2112
2230
  
2113
 
  /* Take down the network interface */
2114
 
  if(take_down_interface){
2115
 
    /* Re-raise priviliges */
 
2231
  /* Re-raise priviliges */
 
2232
  {
2116
2233
    errno = 0;
2117
2234
    ret = seteuid(0);
2118
2235
    if(ret == -1){
2119
2236
      perror_plus("seteuid");
2120
2237
    }
2121
 
    if(geteuid() == 0){
 
2238
    
 
2239
    /* Take down the network interface */
 
2240
    if(take_down_interface and geteuid() == 0){
2122
2241
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2123
2242
      if(ret == -1){
2124
2243
        perror_plus("ioctl SIOCGIFFLAGS");
2125
 
      } else if(network.ifr_flags & IFF_UP) {
 
2244
      } else if(network.ifr_flags & IFF_UP){
2126
2245
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2127
2246
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2128
2247
        if(ret == -1){
2133
2252
      if(ret == -1){
2134
2253
        perror_plus("close");
2135
2254
      }
2136
 
      /* Lower privileges permanently */
2137
 
      errno = 0;
2138
 
      ret = setuid(uid);
2139
 
      if(ret == -1){
2140
 
        perror_plus("setuid");
2141
 
      }
2142
2255
    }
2143
2256
  }
 
2257
  /* Lower privileges permanently */
 
2258
  errno = 0;
 
2259
  ret = setuid(uid);
 
2260
  if(ret == -1){
 
2261
    perror_plus("setuid");
 
2262
  }
2144
2263
  
2145
2264
  /* Removes the GPGME temp directory and all files inside */
2146
2265
  if(tempdir_created){
2160
2279
        }
2161
2280
        ret = remove(fullname);
2162
2281
        if(ret == -1){
2163
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2164
 
                  strerror(errno));
 
2282
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2283
                       strerror(errno));
2165
2284
        }
2166
2285
        free(fullname);
2167
2286
      }