/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

  • Committer: teddy at bsnet
  • Date: 2011-12-24 23:17:02 UTC
  • Revision ID: teddy@fukt.bsnet.se-20111224231702-1ffgu6r02p0bz9co
* plugins.d/splashy.c (error_plus): Check format string.
* plugins.d/askpass-fifo.c (error_plus): - '' -
* plugins.d/plymouth.c (error_plus): - '' -
* plugins.d/password-prompt.c (error_plus): - '' -
* plugins.d/usplash.c (error_plus): - '' -

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
__attribute__((format (gnu_printf, 2, 3)))
 
179
int fprintf_plus(FILE *stream, const char *format, ...){
 
180
  va_list ap;
 
181
  va_start (ap, format);
 
182
  
 
183
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
184
                             program_invocation_short_name));
 
185
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
186
}
 
187
 
174
188
/*
175
189
 * Make additional room in "buffer" for at least BUFFER_SIZE more
176
190
 * bytes. "buffer_capacity" is how much is currently allocated,
177
191
 * "buffer_length" is how much is already used.
178
192
 */
179
193
size_t incbuffer(char **buffer, size_t buffer_length,
180
 
                  size_t buffer_capacity){
 
194
                 size_t buffer_capacity){
181
195
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
182
196
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
183
197
    if(buffer == NULL){
189
203
}
190
204
 
191
205
/* 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){
 
206
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
207
                int af){
195
208
  int ret;
196
209
  server *new_server = malloc(sizeof(server));
197
210
  if(new_server == NULL){
198
211
    perror_plus("malloc");
199
 
    return -1;
 
212
    return false;
200
213
  }
201
214
  *new_server = (server){ .ip = strdup(ip),
202
 
                         .port = port,
203
 
                         .if_index = if_index,
204
 
                         .af = af };
 
215
                          .port = port,
 
216
                          .if_index = if_index,
 
217
                          .af = af };
205
218
  if(new_server->ip == NULL){
206
219
    perror_plus("strdup");
207
 
    return -1;
 
220
    return false;
208
221
  }
209
222
  /* Special case of first server */
210
223
  if (mc.current_server == NULL){
221
234
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
222
235
  if(ret == -1){
223
236
    perror_plus("clock_gettime");
224
 
    return -1;
 
237
    return false;
225
238
  }
226
 
  return 0;
 
239
  return true;
227
240
}
228
241
 
229
242
/* 
230
243
 * Initialize GPGME.
231
244
 */
232
 
static bool init_gpgme(const char *seckey,
233
 
                       const char *pubkey, const char *tempdir){
 
245
static bool init_gpgme(const char *seckey, const char *pubkey,
 
246
                       const char *tempdir){
234
247
  gpgme_error_t rc;
235
248
  gpgme_engine_info_t engine_info;
236
249
  
251
264
    
252
265
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
253
266
    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));
 
267
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
268
                   gpgme_strsource(rc), gpgme_strerror(rc));
256
269
      return false;
257
270
    }
258
271
    
259
272
    rc = gpgme_op_import(mc.ctx, pgp_data);
260
273
    if(rc != GPG_ERR_NO_ERROR){
261
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
262
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
274
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
275
                   gpgme_strsource(rc), gpgme_strerror(rc));
263
276
      return false;
264
277
    }
265
278
    
272
285
  }
273
286
  
274
287
  if(debug){
275
 
    fprintf(stderr, "Initializing GPGME\n");
 
288
    fprintf_plus(stderr, "Initializing GPGME\n");
276
289
  }
277
290
  
278
291
  /* Init GPGME */
279
292
  gpgme_check_version(NULL);
280
293
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
281
294
  if(rc != GPG_ERR_NO_ERROR){
282
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
283
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
295
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
296
                 gpgme_strsource(rc), gpgme_strerror(rc));
284
297
    return false;
285
298
  }
286
299
  
287
300
  /* Set GPGME home directory for the OpenPGP engine only */
288
301
  rc = gpgme_get_engine_info(&engine_info);
289
302
  if(rc != GPG_ERR_NO_ERROR){
290
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
291
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
303
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
304
                 gpgme_strsource(rc), gpgme_strerror(rc));
292
305
    return false;
293
306
  }
294
307
  while(engine_info != NULL){
300
313
    engine_info = engine_info->next;
301
314
  }
302
315
  if(engine_info == NULL){
303
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
316
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
317
                 tempdir);
304
318
    return false;
305
319
  }
306
320
  
307
321
  /* Create new GPGME "context" */
308
322
  rc = gpgme_new(&(mc.ctx));
309
323
  if(rc != GPG_ERR_NO_ERROR){
310
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
311
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
324
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
325
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
326
                 gpgme_strerror(rc));
312
327
    return false;
313
328
  }
314
329
  
333
348
  ssize_t plaintext_length = 0;
334
349
  
335
350
  if(debug){
336
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
351
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
337
352
  }
338
353
  
339
354
  /* Create new GPGME data buffer from memory cryptotext */
340
355
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
341
356
                               0);
342
357
  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));
 
358
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
359
                 gpgme_strsource(rc), gpgme_strerror(rc));
345
360
    return -1;
346
361
  }
347
362
  
348
363
  /* Create new empty GPGME data buffer for the plaintext */
349
364
  rc = gpgme_data_new(&dh_plain);
350
365
  if(rc != GPG_ERR_NO_ERROR){
351
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
352
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
366
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
367
                 "bad gpgme_data_new: %s: %s\n",
 
368
                 gpgme_strsource(rc), gpgme_strerror(rc));
353
369
    gpgme_data_release(dh_crypto);
354
370
    return -1;
355
371
  }
358
374
     data buffer */
359
375
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
360
376
  if(rc != GPG_ERR_NO_ERROR){
361
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
362
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
377
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
378
                 gpgme_strsource(rc), gpgme_strerror(rc));
363
379
    plaintext_length = -1;
364
380
    if(debug){
365
381
      gpgme_decrypt_result_t result;
366
382
      result = gpgme_op_decrypt_result(mc.ctx);
367
383
      if(result == NULL){
368
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
384
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
369
385
      } 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);
 
386
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
387
                     result->unsupported_algorithm);
 
388
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
389
                     result->wrong_key_usage);
374
390
        if(result->file_name != NULL){
375
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
391
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
376
392
        }
377
393
        gpgme_recipient_t recipient;
378
394
        recipient = result->recipients;
379
395
        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");
 
396
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
397
                       gpgme_pubkey_algo_name
 
398
                       (recipient->pubkey_algo));
 
399
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
400
          fprintf_plus(stderr, "Secret key available: %s\n",
 
401
                       recipient->status == GPG_ERR_NO_SECKEY
 
402
                       ? "No" : "Yes");
386
403
          recipient = recipient->next;
387
404
        }
388
405
      }
391
408
  }
392
409
  
393
410
  if(debug){
394
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
411
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
395
412
  }
396
413
  
397
414
  /* Seek back to the beginning of the GPGME plaintext data buffer */
404
421
  *plaintext = NULL;
405
422
  while(true){
406
423
    plaintext_capacity = incbuffer(plaintext,
407
 
                                      (size_t)plaintext_length,
408
 
                                      plaintext_capacity);
 
424
                                   (size_t)plaintext_length,
 
425
                                   plaintext_capacity);
409
426
    if(plaintext_capacity == 0){
410
 
        perror_plus("incbuffer");
411
 
        plaintext_length = -1;
412
 
        goto decrypt_end;
 
427
      perror_plus("incbuffer");
 
428
      plaintext_length = -1;
 
429
      goto decrypt_end;
413
430
    }
414
431
    
415
432
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
428
445
  }
429
446
  
430
447
  if(debug){
431
 
    fprintf(stderr, "Decrypted password is: ");
 
448
    fprintf_plus(stderr, "Decrypted password is: ");
432
449
    for(ssize_t i = 0; i < plaintext_length; i++){
433
450
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
434
451
    }
456
473
/* GnuTLS log function callback */
457
474
static void debuggnutls(__attribute__((unused)) int level,
458
475
                        const char* string){
459
 
  fprintf(stderr, "GnuTLS: %s", string);
 
476
  fprintf_plus(stderr, "GnuTLS: %s", string);
460
477
}
461
478
 
462
479
static int init_gnutls_global(const char *pubkeyfilename,
464
481
  int ret;
465
482
  
466
483
  if(debug){
467
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
484
    fprintf_plus(stderr, "Initializing GnuTLS\n");
468
485
  }
469
486
  
470
487
  ret = gnutls_global_init();
471
488
  if(ret != GNUTLS_E_SUCCESS){
472
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
473
 
            safer_gnutls_strerror(ret));
 
489
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
490
                 safer_gnutls_strerror(ret));
474
491
    return -1;
475
492
  }
476
493
  
485
502
  /* OpenPGP credentials */
486
503
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
487
504
  if(ret != GNUTLS_E_SUCCESS){
488
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
489
 
            safer_gnutls_strerror(ret));
 
505
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
506
                 safer_gnutls_strerror(ret));
490
507
    gnutls_global_deinit();
491
508
    return -1;
492
509
  }
493
510
  
494
511
  if(debug){
495
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
496
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
497
 
            seckeyfilename);
 
512
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
513
                 " secret key %s as GnuTLS credentials\n",
 
514
                 pubkeyfilename,
 
515
                 seckeyfilename);
498
516
  }
499
517
  
500
518
  ret = gnutls_certificate_set_openpgp_key_file
501
519
    (mc.cred, pubkeyfilename, seckeyfilename,
502
520
     GNUTLS_OPENPGP_FMT_BASE64);
503
521
  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));
 
522
    fprintf_plus(stderr,
 
523
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
524
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
525
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
526
                 safer_gnutls_strerror(ret));
509
527
    goto globalfail;
510
528
  }
511
529
  
512
530
  /* GnuTLS server initialization */
513
531
  ret = gnutls_dh_params_init(&mc.dh_params);
514
532
  if(ret != GNUTLS_E_SUCCESS){
515
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
516
 
            " %s\n", safer_gnutls_strerror(ret));
 
533
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
534
                 " initialization: %s\n",
 
535
                 safer_gnutls_strerror(ret));
517
536
    goto globalfail;
518
537
  }
519
538
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
520
539
  if(ret != GNUTLS_E_SUCCESS){
521
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
522
 
            safer_gnutls_strerror(ret));
 
540
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
541
                 safer_gnutls_strerror(ret));
523
542
    goto globalfail;
524
543
  }
525
544
  
545
564
    }
546
565
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
547
566
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
549
 
            safer_gnutls_strerror(ret));
 
567
    fprintf_plus(stderr,
 
568
                 "Error in GnuTLS session initialization: %s\n",
 
569
                 safer_gnutls_strerror(ret));
550
570
  }
551
571
  
552
572
  {
559
579
      }
560
580
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
561
581
    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));
 
582
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
583
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
584
                   safer_gnutls_strerror(ret));
565
585
      gnutls_deinit(*session);
566
586
      return -1;
567
587
    }
576
596
    }
577
597
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
578
598
  if(ret != GNUTLS_E_SUCCESS){
579
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
580
 
            safer_gnutls_strerror(ret));
 
599
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
600
                 safer_gnutls_strerror(ret));
581
601
    gnutls_deinit(*session);
582
602
    return -1;
583
603
  }
628
648
    pf = PF_INET;
629
649
    break;
630
650
  default:
631
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
651
    fprintf_plus(stderr, "Bad address family: %d\n", af);
632
652
    errno = EINVAL;
633
653
    return -1;
634
654
  }
639
659
  }
640
660
  
641
661
  if(debug){
642
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
643
 
            "\n", ip, port);
 
662
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
663
                 PRIu16 "\n", ip, port);
644
664
  }
645
665
  
646
666
  tcp_sd = socket(pf, SOCK_STREAM, 0);
672
692
  }
673
693
  if(ret == 0){
674
694
    int e = errno;
675
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
695
    fprintf_plus(stderr, "Bad address: %s\n", ip);
676
696
    errno = e;
677
697
    goto mandos_end;
678
698
  }
683
703
    
684
704
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
685
705
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
686
 
                              -Wunreachable-code*/
 
706
                                -Wunreachable-code*/
687
707
      if(if_index == AVAHI_IF_UNSPEC){
688
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
689
 
                " without a network interface\n");
 
708
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
709
                     " incomplete without a network interface\n");
690
710
        errno = EINVAL;
691
711
        goto mandos_end;
692
712
      }
710
730
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
711
731
        perror_plus("if_indextoname");
712
732
      } else {
713
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
714
 
                ip, interface, port);
 
733
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
734
                     "\n", ip, interface, port);
715
735
      }
716
736
    } else {
717
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
718
 
              port);
 
737
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
738
                   ip, port);
719
739
    }
720
740
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
721
741
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
731
751
      perror_plus("inet_ntop");
732
752
    } else {
733
753
      if(strcmp(addrstr, ip) != 0){
734
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
754
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
735
755
      }
736
756
    }
737
757
  }
765
785
  while(true){
766
786
    size_t out_size = strlen(out);
767
787
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
768
 
                                   out_size - written));
 
788
                                        out_size - written));
769
789
    if(ret == -1){
770
790
      int e = errno;
771
791
      perror_plus("write");
791
811
  }
792
812
  
793
813
  if(debug){
794
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
814
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
795
815
  }
796
816
  
797
817
  if(quit_now){
817
837
  
818
838
  if(ret != GNUTLS_E_SUCCESS){
819
839
    if(debug){
820
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
840
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
821
841
      gnutls_perror(ret);
822
842
    }
823
843
    errno = EPROTO;
827
847
  /* Read OpenPGP packet that contains the wanted password */
828
848
  
829
849
  if(debug){
830
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
831
 
            ip);
 
850
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
851
                 " %s\n", ip);
832
852
  }
833
853
  
834
854
  while(true){
839
859
    }
840
860
    
841
861
    buffer_capacity = incbuffer(&buffer, buffer_length,
842
 
                                   buffer_capacity);
 
862
                                buffer_capacity);
843
863
    if(buffer_capacity == 0){
844
864
      int e = errno;
845
865
      perror_plus("incbuffer");
872
892
          }
873
893
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
874
894
        if(ret < 0){
875
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
895
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
896
                       "***\n");
876
897
          gnutls_perror(ret);
877
898
          errno = EPROTO;
878
899
          goto mandos_end;
879
900
        }
880
901
        break;
881
902
      default:
882
 
        fprintf(stderr, "Unknown error while reading data from"
883
 
                " encrypted session with Mandos server\n");
 
903
        fprintf_plus(stderr, "Unknown error while reading data from"
 
904
                     " encrypted session with Mandos server\n");
884
905
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
885
906
        errno = EIO;
886
907
        goto mandos_end;
891
912
  }
892
913
  
893
914
  if(debug){
894
 
    fprintf(stderr, "Closing TLS session\n");
 
915
    fprintf_plus(stderr, "Closing TLS session\n");
895
916
  }
896
917
  
897
918
  if(quit_now){
909
930
  
910
931
  if(buffer_length > 0){
911
932
    ssize_t decrypted_buffer_size;
912
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
913
 
                                               buffer_length,
 
933
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
914
934
                                               &decrypted_buffer);
915
935
    if(decrypted_buffer_size >= 0){
916
936
      
927
947
        if(ret == 0 and ferror(stdout)){
928
948
          int e = errno;
929
949
          if(debug){
930
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
931
 
                    strerror(errno));
 
950
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
951
                         strerror(errno));
932
952
          }
933
953
          errno = e;
934
954
          goto mandos_end;
991
1011
  switch(event){
992
1012
  default:
993
1013
  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)));
 
1014
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1015
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1016
                 domain,
 
1017
                 avahi_strerror(avahi_server_errno(mc.server)));
997
1018
    break;
998
1019
    
999
1020
  case AVAHI_RESOLVER_FOUND:
1001
1022
      char ip[AVAHI_ADDRESS_STR_MAX];
1002
1023
      avahi_address_snprint(ip, sizeof(ip), address);
1003
1024
      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);
 
1025
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1026
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1027
                     host_name, ip, (intmax_t)interface, port);
1007
1028
      }
1008
1029
      int ret = start_mandos_communication(ip, port, interface,
1009
1030
                                           avahi_proto_to_af(proto));
1010
1031
      if(ret == 0){
1011
1032
        avahi_simple_poll_quit(mc.simple_poll);
1012
1033
      } else {
1013
 
        ret = add_server(ip, port, interface,
1014
 
                         avahi_proto_to_af(proto));
 
1034
        if(not add_server(ip, port, interface,
 
1035
                          avahi_proto_to_af(proto))){
 
1036
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1037
                       " list\n", name);
 
1038
        }
1015
1039
      }
1016
1040
    }
1017
1041
  }
1041
1065
  default:
1042
1066
  case AVAHI_BROWSER_FAILURE:
1043
1067
    
1044
 
    fprintf(stderr, "(Avahi browser) %s\n",
1045
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1068
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1069
                 avahi_strerror(avahi_server_errno(mc.server)));
1046
1070
    avahi_simple_poll_quit(mc.simple_poll);
1047
1071
    return;
1048
1072
    
1055
1079
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1056
1080
                                    name, type, domain, protocol, 0,
1057
1081
                                    resolve_callback, NULL) == NULL)
1058
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1059
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1082
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1083
                   " %s\n", name,
 
1084
                   avahi_strerror(avahi_server_errno(mc.server)));
1060
1085
    break;
1061
1086
    
1062
1087
  case AVAHI_BROWSER_REMOVE:
1065
1090
  case AVAHI_BROWSER_ALL_FOR_NOW:
1066
1091
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1067
1092
    if(debug){
1068
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1093
      fprintf_plus(stderr, "No Mandos server found, still"
 
1094
                   " searching...\n");
1069
1095
    }
1070
1096
    break;
1071
1097
  }
1110
1136
  /* Reject the loopback device */
1111
1137
  if(ifr->ifr_flags & IFF_LOOPBACK){
1112
1138
    if(debug){
1113
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1114
 
              ifname);
 
1139
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1140
                   ifname);
1115
1141
    }
1116
1142
    return false;
1117
1143
  }
1118
1144
  /* Accept point-to-point devices only if connect_to is specified */
1119
1145
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1120
1146
    if(debug){
1121
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1122
 
              ifname);
 
1147
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1148
                   " \"%s\"\n", ifname);
1123
1149
    }
1124
1150
    return true;
1125
1151
  }
1126
1152
  /* Otherwise, reject non-broadcast-capable devices */
1127
1153
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1128
1154
    if(debug){
1129
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1130
 
              ifname);
 
1155
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1156
                   " \"%s\"\n", ifname);
1131
1157
    }
1132
1158
    return false;
1133
1159
  }
1134
1160
  /* Reject non-ARP interfaces (including dummy interfaces) */
1135
1161
  if(ifr->ifr_flags & IFF_NOARP){
1136
1162
    if(debug){
1137
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1163
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1164
                   ifname);
1138
1165
    }
1139
1166
    return false;
1140
1167
  }
1141
1168
  
1142
1169
  /* Accept this device */
1143
1170
  if(debug){
1144
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
 
1171
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1145
1172
  }
1146
1173
  return true;
1147
1174
}
1159
1186
  struct ifreq ifr;
1160
1187
  if(not get_flags(if_entry->d_name, &ifr)){
1161
1188
    if(debug){
1162
 
      fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1163
 
              if_entry->d_name);
 
1189
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1190
                   "\"%s\"\n", if_entry->d_name);
1164
1191
    }
1165
1192
    return 0;
1166
1193
  }
1184
1211
  struct ifreq ifr;
1185
1212
  if(not get_flags(if_entry->d_name, &ifr)){
1186
1213
    if(debug){
1187
 
      fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1188
 
              if_entry->d_name);
 
1214
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1215
                   "\"%s\"\n", if_entry->d_name);
1189
1216
    }
1190
1217
    return 0;
1191
1218
  }
1193
1220
  /* Reject down interfaces */
1194
1221
  if(not (ifr.ifr_flags & IFF_UP)){
1195
1222
    if(debug){
1196
 
      fprintf(stderr, "Rejecting down interface \"%s\"\n",
1197
 
              if_entry->d_name);
 
1223
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1224
                   if_entry->d_name);
1198
1225
    }
1199
1226
    return 0;
1200
1227
  }
1202
1229
  /* Reject non-running interfaces */
1203
1230
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1204
1231
    if(debug){
1205
 
      fprintf(stderr, "Rejecting non-running interface \"%s\"\n",
1206
 
              if_entry->d_name);
 
1232
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1233
                   if_entry->d_name);
1207
1234
    }
1208
1235
    return 0;
1209
1236
  }
1228
1255
/* Is this directory entry a runnable program? */
1229
1256
int runnable_hook(const struct dirent *direntry){
1230
1257
  int ret;
 
1258
  size_t sret;
1231
1259
  struct stat st;
1232
1260
  
1233
1261
  if((direntry->d_name)[0] == '\0'){
1235
1263
    return 0;
1236
1264
  }
1237
1265
  
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);
 
1266
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1267
                "abcdefghijklmnopqrstuvwxyz"
 
1268
                "0123456789"
 
1269
                "_-");
 
1270
  if((direntry->d_name)[sret] != '\0'){
 
1271
    /* Contains non-allowed characters */
 
1272
    if(debug){
 
1273
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1274
                   direntry->d_name);
 
1275
    }
 
1276
    return 0;
 
1277
  }
 
1278
  
 
1279
  char *fullname = NULL;
 
1280
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1281
  if(ret < 0){
 
1282
    perror_plus("asprintf");
 
1283
    return 0;
 
1284
  }
 
1285
  
 
1286
  ret = stat(fullname, &st);
1255
1287
  if(ret == -1){
1256
1288
    if(debug){
1257
 
      perror_plus("Could not stat plugin");
 
1289
      perror_plus("Could not stat hook");
1258
1290
    }
1259
1291
    return 0;
1260
1292
  }
1261
1293
  if(not (S_ISREG(st.st_mode))){
1262
1294
    /* Not a regular file */
 
1295
    if(debug){
 
1296
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1297
                   direntry->d_name);
 
1298
    }
1263
1299
    return 0;
1264
1300
  }
1265
1301
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1266
1302
    /* Not executable */
 
1303
    if(debug){
 
1304
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1305
                   direntry->d_name);
 
1306
    }
1267
1307
    return 0;
1268
1308
  }
 
1309
  if(debug){
 
1310
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1311
                 direntry->d_name);
 
1312
  }
1269
1313
  return 1;
1270
1314
}
1271
1315
 
1278
1322
  while(true){
1279
1323
    if(mc.current_server == NULL){
1280
1324
      if (debug){
1281
 
        fprintf(stderr,
1282
 
                "Wait until first server is found. No timeout!\n");
 
1325
        fprintf_plus(stderr, "Wait until first server is found."
 
1326
                     " No timeout!\n");
1283
1327
      }
1284
1328
      ret = avahi_simple_poll_iterate(s, -1);
1285
1329
    } else {
1286
1330
      if (debug){
1287
 
        fprintf(stderr, "Check current_server if we should run it,"
1288
 
                " or wait\n");
 
1331
        fprintf_plus(stderr, "Check current_server if we should run"
 
1332
                     " it, or wait\n");
1289
1333
      }
1290
1334
      /* the current time */
1291
1335
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1307
1351
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1308
1352
      
1309
1353
      if (debug){
1310
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1354
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1355
                     block_time);
1311
1356
      }
1312
1357
      
1313
1358
      if(block_time <= 0){
1333
1378
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1334
1379
    }
1335
1380
    if(ret != 0){
1336
 
      if (ret > 0 or errno != EINTR) {
 
1381
      if (ret > 0 or errno != EINTR){
1337
1382
        return (ret != 1) ? ret : 0;
1338
1383
      }
1339
1384
    }
1340
1385
  }
1341
1386
}
1342
1387
 
 
1388
bool run_network_hooks(const char *mode, const char *interface,
 
1389
                       const float delay){
 
1390
  struct dirent **direntries;
 
1391
  struct dirent *direntry;
 
1392
  int ret;
 
1393
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1394
                         alphasort);
 
1395
  if(numhooks == -1){
 
1396
    perror_plus("scandir");
 
1397
  } else {
 
1398
    int devnull = open("/dev/null", O_RDONLY);
 
1399
    for(int i = 0; i < numhooks; i++){
 
1400
      direntry = direntries[i];
 
1401
      char *fullname = NULL;
 
1402
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1403
      if(ret < 0){
 
1404
        perror_plus("asprintf");
 
1405
        continue;
 
1406
      }
 
1407
      if(debug){
 
1408
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1409
                     direntry->d_name);
 
1410
      }
 
1411
      pid_t hook_pid = fork();
 
1412
      if(hook_pid == 0){
 
1413
        /* Child */
 
1414
        /* Raise privileges */
 
1415
        errno = 0;
 
1416
        ret = seteuid(0);
 
1417
        if(ret == -1){
 
1418
          perror_plus("seteuid");
 
1419
        }
 
1420
        /* Raise privileges even more */
 
1421
        errno = 0;
 
1422
        ret = setuid(0);
 
1423
        if(ret == -1){
 
1424
          perror_plus("setuid");
 
1425
        }
 
1426
        /* Set group */
 
1427
        errno = 0;
 
1428
        ret = setgid(0);
 
1429
        if(ret == -1){
 
1430
          perror_plus("setgid");
 
1431
        }
 
1432
        /* Reset supplementary groups */
 
1433
        errno = 0;
 
1434
        ret = setgroups(0, NULL);
 
1435
        if(ret == -1){
 
1436
          perror_plus("setgroups");
 
1437
        }
 
1438
        dup2(devnull, STDIN_FILENO);
 
1439
        close(devnull);
 
1440
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1441
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1442
        if(ret == -1){
 
1443
          perror_plus("setenv");
 
1444
          _exit(EX_OSERR);
 
1445
        }
 
1446
        ret = setenv("DEVICE", interface, 1);
 
1447
        if(ret == -1){
 
1448
          perror_plus("setenv");
 
1449
          _exit(EX_OSERR);
 
1450
        }
 
1451
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1452
        if(ret == -1){
 
1453
          perror_plus("setenv");
 
1454
          _exit(EX_OSERR);
 
1455
        }
 
1456
        ret = setenv("MODE", mode, 1);
 
1457
        if(ret == -1){
 
1458
          perror_plus("setenv");
 
1459
          _exit(EX_OSERR);
 
1460
        }
 
1461
        char *delaystring;
 
1462
        ret = asprintf(&delaystring, "%f", delay);
 
1463
        if(ret == -1){
 
1464
          perror_plus("asprintf");
 
1465
          _exit(EX_OSERR);
 
1466
        }
 
1467
        ret = setenv("DELAY", delaystring, 1);
 
1468
        if(ret == -1){
 
1469
          free(delaystring);
 
1470
          perror_plus("setenv");
 
1471
          _exit(EX_OSERR);
 
1472
        }
 
1473
        free(delaystring);
 
1474
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1475
          perror_plus("execl");
 
1476
          _exit(EXIT_FAILURE);
 
1477
        }
 
1478
      } else {
 
1479
        int status;
 
1480
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1481
          perror_plus("waitpid");
 
1482
          free(fullname);
 
1483
          continue;
 
1484
        }
 
1485
        if(WIFEXITED(status)){
 
1486
          if(WEXITSTATUS(status) != 0){
 
1487
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1488
                         " with status %d\n", direntry->d_name,
 
1489
                         WEXITSTATUS(status));
 
1490
            free(fullname);
 
1491
            continue;
 
1492
          }
 
1493
        } else if(WIFSIGNALED(status)){
 
1494
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1495
                       " signal %d\n", direntry->d_name,
 
1496
                       WTERMSIG(status));
 
1497
          free(fullname);
 
1498
          continue;
 
1499
        } else {
 
1500
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1501
                       " crashed\n", direntry->d_name);
 
1502
          free(fullname);
 
1503
          continue;
 
1504
        }
 
1505
      }
 
1506
      free(fullname);
 
1507
      if(debug){
 
1508
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1509
                     direntry->d_name);
 
1510
      }
 
1511
    }
 
1512
    close(devnull);
 
1513
  }
 
1514
  return true;
 
1515
}
 
1516
 
1343
1517
int main(int argc, char *argv[]){
1344
1518
  AvahiSServiceBrowser *sb = NULL;
1345
1519
  int error;
1427
1601
        .arg = "SECONDS",
1428
1602
        .doc = "Retry interval used when denied by the mandos server",
1429
1603
        .group = 2 },
 
1604
      { .name = "network-hook-dir", .key = 133,
 
1605
        .arg = "DIR",
 
1606
        .doc = "Directory where network hooks are located",
 
1607
        .group = 2 },
1430
1608
      /*
1431
1609
       * These reproduce what we would get without ARGP_NO_HELP
1432
1610
       */
1485
1663
          argp_error(state, "Bad retry interval");
1486
1664
        }
1487
1665
        break;
 
1666
      case 133:                 /* --network-hook-dir */
 
1667
        hookdir = arg;
 
1668
        break;
1488
1669
        /*
1489
1670
         * These reproduce what we would get without ARGP_NO_HELP
1490
1671
         */
1496
1677
        argp_state_help(state, state->out_stream,
1497
1678
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1498
1679
      case 'V':                 /* --version */
1499
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1680
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1500
1681
        exit(argp_err_exit_status);
1501
1682
        break;
1502
1683
      default:
1529
1710
  {
1530
1711
    /* Work around Debian bug #633582:
1531
1712
       <http://bugs.debian.org/633582> */
1532
 
    struct stat st;
1533
1713
    
1534
1714
    /* Re-raise priviliges */
1535
1715
    errno = 0;
1536
1716
    ret = seteuid(0);
1537
1717
    if(ret == -1){
1538
1718
      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");
 
1719
    } else {
 
1720
      struct stat st;
 
1721
      
 
1722
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1723
        int seckey_fd = open(seckey, O_RDONLY);
 
1724
        if(seckey_fd == -1){
 
1725
          perror_plus("open");
 
1726
        } else {
 
1727
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1728
          if(ret == -1){
 
1729
            perror_plus("fstat");
 
1730
          } else {
 
1731
            if(S_ISREG(st.st_mode)
 
1732
               and st.st_uid == 0 and st.st_gid == 0){
 
1733
              ret = fchown(seckey_fd, uid, gid);
 
1734
              if(ret == -1){
 
1735
                perror_plus("fchown");
 
1736
              }
 
1737
            }
 
1738
          }
 
1739
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
1740
        }
 
1741
      }
 
1742
    
 
1743
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1744
        int pubkey_fd = open(pubkey, O_RDONLY);
 
1745
        if(pubkey_fd == -1){
 
1746
          perror_plus("open");
 
1747
        } else {
 
1748
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1749
          if(ret == -1){
 
1750
            perror_plus("fstat");
 
1751
          } else {
 
1752
            if(S_ISREG(st.st_mode)
 
1753
               and st.st_uid == 0 and st.st_gid == 0){
 
1754
              ret = fchown(pubkey_fd, uid, gid);
 
1755
              if(ret == -1){
 
1756
                perror_plus("fchown");
 
1757
              }
 
1758
            }
 
1759
          }
 
1760
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1761
        }
 
1762
      }
 
1763
    
 
1764
      /* Lower privileges */
 
1765
      errno = 0;
 
1766
      ret = seteuid(uid);
 
1767
      if(ret == -1){
 
1768
        perror_plus("seteuid");
 
1769
      }
1586
1770
    }
1587
1771
  }
1588
1772
  
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
 
        setenv("DEVICE", interface, 1);
1612
 
        setenv("VERBOSE", debug ? "1" : "0", 1);
1613
 
        setenv("MODE", "start", 1);
1614
 
        /* setenv( XXX more here */
1615
 
        ret = execl(fullname, direntry->d_name, "start", NULL);
1616
 
        perror_plus("execl");
1617
 
      }
1618
 
      free(fullname);
1619
 
      if(quit_now){
1620
 
        goto end;
1621
 
      }
1622
 
    }
1623
 
    close(devnull);
 
1773
  /* Run network hooks */
 
1774
  if(not run_network_hooks("start", interface, delay)){
 
1775
    goto end;
1624
1776
  }
1625
1777
  
1626
1778
  if(not debug){
1642
1794
      /* Pick the first interface returned */
1643
1795
      interface = strdup(direntries[0]->d_name);
1644
1796
      if(debug){
1645
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1797
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1646
1798
      }
1647
1799
      if(interface == NULL){
1648
1800
        perror_plus("malloc");
1653
1805
      free(direntries);
1654
1806
    } else {
1655
1807
      free(direntries);
1656
 
      fprintf(stderr, "Could not find a network interface\n");
 
1808
      fprintf_plus(stderr, "Could not find a network interface\n");
1657
1809
      exitcode = EXIT_FAILURE;
1658
1810
      goto end;
1659
1811
    }
1665
1817
  srand((unsigned int) time(NULL));
1666
1818
  mc.simple_poll = avahi_simple_poll_new();
1667
1819
  if(mc.simple_poll == NULL){
1668
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1820
    fprintf_plus(stderr,
 
1821
                 "Avahi: Failed to create simple poll object.\n");
1669
1822
    exitcode = EX_UNAVAILABLE;
1670
1823
    goto end;
1671
1824
  }
1737
1890
  if(strcmp(interface, "none") != 0){
1738
1891
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1739
1892
    if(if_index == 0){
1740
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1893
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1741
1894
      exitcode = EX_UNAVAILABLE;
1742
1895
      goto end;
1743
1896
    }
1863
2016
#endif  /* __linux__ */
1864
2017
    /* Lower privileges */
1865
2018
    errno = 0;
1866
 
    if(take_down_interface){
1867
 
      /* Lower privileges */
1868
 
      ret = seteuid(uid);
1869
 
      if(ret == -1){
1870
 
        perror_plus("seteuid");
1871
 
      }
1872
 
    } else {
1873
 
      /* Lower privileges permanently */
1874
 
      ret = setuid(uid);
1875
 
      if(ret == -1){
1876
 
        perror_plus("setuid");
1877
 
      }
 
2019
    /* Lower privileges */
 
2020
    ret = seteuid(uid);
 
2021
    if(ret == -1){
 
2022
      perror_plus("seteuid");
1878
2023
    }
1879
2024
  }
1880
2025
  
1884
2029
  
1885
2030
  ret = init_gnutls_global(pubkey, seckey);
1886
2031
  if(ret == -1){
1887
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2032
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1888
2033
    exitcode = EX_UNAVAILABLE;
1889
2034
    goto end;
1890
2035
  } else {
1906
2051
  }
1907
2052
  
1908
2053
  if(not init_gpgme(pubkey, seckey, tempdir)){
1909
 
    fprintf(stderr, "init_gpgme failed\n");
 
2054
    fprintf_plus(stderr, "init_gpgme failed\n");
1910
2055
    exitcode = EX_UNAVAILABLE;
1911
2056
    goto end;
1912
2057
  } else {
1922
2067
    /* (Mainly meant for debugging) */
1923
2068
    char *address = strrchr(connect_to, ':');
1924
2069
    if(address == NULL){
1925
 
      fprintf(stderr, "No colon in address\n");
 
2070
      fprintf_plus(stderr, "No colon in address\n");
1926
2071
      exitcode = EX_USAGE;
1927
2072
      goto end;
1928
2073
    }
1936
2081
    tmpmax = strtoimax(address+1, &tmp, 10);
1937
2082
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1938
2083
       or tmpmax != (uint16_t)tmpmax){
1939
 
      fprintf(stderr, "Bad port number\n");
 
2084
      fprintf_plus(stderr, "Bad port number\n");
1940
2085
      exitcode = EX_USAGE;
1941
2086
      goto end;
1942
2087
    }
1972
2117
        break;
1973
2118
      }
1974
2119
      if(debug){
1975
 
        fprintf(stderr, "Retrying in %d seconds\n",
1976
 
                (int)retry_interval);
 
2120
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2121
                     (int)retry_interval);
1977
2122
      }
1978
2123
      sleep((int)retry_interval);
1979
2124
    }
2009
2154
  
2010
2155
  /* Check if creating the Avahi server object succeeded */
2011
2156
  if(mc.server == NULL){
2012
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2013
 
            avahi_strerror(error));
 
2157
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2158
                 avahi_strerror(error));
2014
2159
    exitcode = EX_UNAVAILABLE;
2015
2160
    goto end;
2016
2161
  }
2024
2169
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2025
2170
                                   NULL, 0, browse_callback, NULL);
2026
2171
  if(sb == NULL){
2027
 
    fprintf(stderr, "Failed to create service browser: %s\n",
2028
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2172
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2173
                 avahi_strerror(avahi_server_errno(mc.server)));
2029
2174
    exitcode = EX_UNAVAILABLE;
2030
2175
    goto end;
2031
2176
  }
2037
2182
  /* Run the main loop */
2038
2183
  
2039
2184
  if(debug){
2040
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2185
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2041
2186
  }
2042
2187
 
2043
2188
  ret = avahi_loop_with_timeout(mc.simple_poll,
2044
2189
                                (int)(retry_interval * 1000));
2045
2190
  if(debug){
2046
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2047
 
            (ret == 0) ? "successfully" : "with error");
 
2191
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2192
                 (ret == 0) ? "successfully" : "with error");
2048
2193
  }
2049
2194
  
2050
2195
 end:
2051
2196
  
2052
2197
  if(debug){
2053
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2198
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2054
2199
  }
2055
2200
  
2056
2201
  /* Cleanup things */
2072
2217
  if(gpgme_initialized){
2073
2218
    gpgme_release(mc.ctx);
2074
2219
  }
2075
 
 
 
2220
  
2076
2221
  /* Cleans up the circular linked list of Mandos servers the client
2077
2222
     has seen */
2078
2223
  if(mc.current_server != NULL){
2084
2229
    }
2085
2230
  }
2086
2231
  
2087
 
  /* XXX run network hooks "stop" here  */
 
2232
  /* Run network hooks */
 
2233
  run_network_hooks("stop", interface, delay);
2088
2234
  
2089
 
  /* Take down the network interface */
2090
 
  if(take_down_interface){
2091
 
    /* Re-raise priviliges */
 
2235
  /* Re-raise priviliges */
 
2236
  {
2092
2237
    errno = 0;
2093
2238
    ret = seteuid(0);
2094
2239
    if(ret == -1){
2095
2240
      perror_plus("seteuid");
2096
2241
    }
2097
 
    if(geteuid() == 0){
 
2242
    
 
2243
    /* Take down the network interface */
 
2244
    if(take_down_interface and geteuid() == 0){
2098
2245
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2099
2246
      if(ret == -1){
2100
2247
        perror_plus("ioctl SIOCGIFFLAGS");
2101
 
      } else if(network.ifr_flags & IFF_UP) {
 
2248
      } else if(network.ifr_flags & IFF_UP){
2102
2249
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2103
2250
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2104
2251
        if(ret == -1){
2109
2256
      if(ret == -1){
2110
2257
        perror_plus("close");
2111
2258
      }
2112
 
      /* Lower privileges permanently */
2113
 
      errno = 0;
2114
 
      ret = setuid(uid);
2115
 
      if(ret == -1){
2116
 
        perror_plus("setuid");
2117
 
      }
2118
2259
    }
2119
2260
  }
 
2261
  /* Lower privileges permanently */
 
2262
  errno = 0;
 
2263
  ret = setuid(uid);
 
2264
  if(ret == -1){
 
2265
    perror_plus("setuid");
 
2266
  }
2120
2267
  
2121
2268
  /* Removes the GPGME temp directory and all files inside */
2122
2269
  if(tempdir_created){
2136
2283
        }
2137
2284
        ret = remove(fullname);
2138
2285
        if(ret == -1){
2139
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2140
 
                  strerror(errno));
 
2286
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2287
                       strerror(errno));
2141
2288
        }
2142
2289
        free(fullname);
2143
2290
      }