/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 Hogeborn
  • Date: 2012-01-01 20:45:53 UTC
  • Revision ID: teddy@recompile.se-20120101204553-f1zlty873gswtf5n
* README: Hint that the intro(8mandos) manual page is in the server
          package.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008-2012 Teddy Hogeborn
 
13
 * Copyright © 2008-2012 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
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
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
89
                                   WEXITSTATUS(), WTERMSIG() */
 
90
#include <grp.h>                /* setgroups() */
90
91
 
91
92
#ifdef __linux__
92
93
#include <sys/klog.h>           /* klogctl() */
110
111
                                   init_gnutls_session(),
111
112
                                   GNUTLS_* */
112
113
#include <gnutls/openpgp.h>
113
 
                          /* gnutls_certificate_set_openpgp_key_file(),
114
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
114
                         /* gnutls_certificate_set_openpgp_key_file(),
 
115
                            GNUTLS_OPENPGP_FMT_BASE64 */
115
116
 
116
117
/* GPGME */
117
118
#include <gpgme.h>              /* All GPGME types, constants and
169
170
 
170
171
/* Function to use when printing errors */
171
172
void perror_plus(const char *print_text){
 
173
  int e = errno;
172
174
  fprintf(stderr, "Mandos plugin %s: ",
173
175
          program_invocation_short_name);
 
176
  errno = e;
174
177
  perror(print_text);
175
178
}
176
179
 
 
180
__attribute__((format (gnu_printf, 2, 3)))
 
181
int fprintf_plus(FILE *stream, const char *format, ...){
 
182
  va_list ap;
 
183
  va_start (ap, format);
 
184
  
 
185
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
186
                             program_invocation_short_name));
 
187
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
188
}
 
189
 
177
190
/*
178
191
 * Make additional room in "buffer" for at least BUFFER_SIZE more
179
192
 * bytes. "buffer_capacity" is how much is currently allocated,
180
193
 * "buffer_length" is how much is already used.
181
194
 */
182
195
size_t incbuffer(char **buffer, size_t buffer_length,
183
 
                  size_t buffer_capacity){
 
196
                 size_t buffer_capacity){
184
197
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
185
198
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
186
199
    if(buffer == NULL){
192
205
}
193
206
 
194
207
/* Add server to set of servers to retry periodically */
195
 
int add_server(const char *ip, uint16_t port,
196
 
                 AvahiIfIndex if_index,
197
 
                 int af){
 
208
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
209
                int af){
198
210
  int ret;
199
211
  server *new_server = malloc(sizeof(server));
200
212
  if(new_server == NULL){
201
213
    perror_plus("malloc");
202
 
    return -1;
 
214
    return false;
203
215
  }
204
216
  *new_server = (server){ .ip = strdup(ip),
205
 
                         .port = port,
206
 
                         .if_index = if_index,
207
 
                         .af = af };
 
217
                          .port = port,
 
218
                          .if_index = if_index,
 
219
                          .af = af };
208
220
  if(new_server->ip == NULL){
209
221
    perror_plus("strdup");
210
 
    return -1;
 
222
    return false;
211
223
  }
212
224
  /* Special case of first server */
213
225
  if (mc.current_server == NULL){
224
236
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
225
237
  if(ret == -1){
226
238
    perror_plus("clock_gettime");
227
 
    return -1;
 
239
    return false;
228
240
  }
229
 
  return 0;
 
241
  return true;
230
242
}
231
243
 
232
244
/* 
233
245
 * Initialize GPGME.
234
246
 */
235
 
static bool init_gpgme(const char *seckey,
236
 
                       const char *pubkey, const char *tempdir){
 
247
static bool init_gpgme(const char *seckey, const char *pubkey,
 
248
                       const char *tempdir){
237
249
  gpgme_error_t rc;
238
250
  gpgme_engine_info_t engine_info;
239
251
  
254
266
    
255
267
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
256
268
    if(rc != GPG_ERR_NO_ERROR){
257
 
      fprintf(stderr, "Mandos plugin mandos-client: "
258
 
              "bad gpgme_data_new_from_fd: %s: %s\n",
259
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
269
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
270
                   gpgme_strsource(rc), gpgme_strerror(rc));
260
271
      return false;
261
272
    }
262
273
    
263
274
    rc = gpgme_op_import(mc.ctx, pgp_data);
264
275
    if(rc != GPG_ERR_NO_ERROR){
265
 
      fprintf(stderr, "Mandos plugin mandos-client: "
266
 
              "bad gpgme_op_import: %s: %s\n",
267
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
276
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
277
                   gpgme_strsource(rc), gpgme_strerror(rc));
268
278
      return false;
269
279
    }
270
280
    
277
287
  }
278
288
  
279
289
  if(debug){
280
 
    fprintf(stderr, "Mandos plugin mandos-client: "
281
 
            "Initializing GPGME\n");
 
290
    fprintf_plus(stderr, "Initializing GPGME\n");
282
291
  }
283
292
  
284
293
  /* Init GPGME */
285
294
  gpgme_check_version(NULL);
286
295
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
287
296
  if(rc != GPG_ERR_NO_ERROR){
288
 
    fprintf(stderr, "Mandos plugin mandos-client: "
289
 
            "bad gpgme_engine_check_version: %s: %s\n",
290
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
297
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
298
                 gpgme_strsource(rc), gpgme_strerror(rc));
291
299
    return false;
292
300
  }
293
301
  
294
302
  /* Set GPGME home directory for the OpenPGP engine only */
295
303
  rc = gpgme_get_engine_info(&engine_info);
296
304
  if(rc != GPG_ERR_NO_ERROR){
297
 
    fprintf(stderr, "Mandos plugin mandos-client: "
298
 
            "bad gpgme_get_engine_info: %s: %s\n",
299
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
305
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
306
                 gpgme_strsource(rc), gpgme_strerror(rc));
300
307
    return false;
301
308
  }
302
309
  while(engine_info != NULL){
308
315
    engine_info = engine_info->next;
309
316
  }
310
317
  if(engine_info == NULL){
311
 
    fprintf(stderr, "Mandos plugin mandos-client: "
312
 
            "Could not set GPGME home dir to %s\n", tempdir);
 
318
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
319
                 tempdir);
313
320
    return false;
314
321
  }
315
322
  
316
323
  /* Create new GPGME "context" */
317
324
  rc = gpgme_new(&(mc.ctx));
318
325
  if(rc != GPG_ERR_NO_ERROR){
319
 
    fprintf(stderr, "Mandos plugin mandos-client: "
320
 
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
321
 
            gpgme_strerror(rc));
 
326
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
327
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
328
                 gpgme_strerror(rc));
322
329
    return false;
323
330
  }
324
331
  
343
350
  ssize_t plaintext_length = 0;
344
351
  
345
352
  if(debug){
346
 
    fprintf(stderr, "Mandos plugin mandos-client: "
347
 
            "Trying to decrypt OpenPGP data\n");
 
353
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
348
354
  }
349
355
  
350
356
  /* Create new GPGME data buffer from memory cryptotext */
351
357
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
352
358
                               0);
353
359
  if(rc != GPG_ERR_NO_ERROR){
354
 
    fprintf(stderr, "Mandos plugin mandos-client: "
355
 
            "bad gpgme_data_new_from_mem: %s: %s\n",
356
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
360
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
361
                 gpgme_strsource(rc), gpgme_strerror(rc));
357
362
    return -1;
358
363
  }
359
364
  
360
365
  /* Create new empty GPGME data buffer for the plaintext */
361
366
  rc = gpgme_data_new(&dh_plain);
362
367
  if(rc != GPG_ERR_NO_ERROR){
363
 
    fprintf(stderr, "Mandos plugin mandos-client: "
364
 
            "bad gpgme_data_new: %s: %s\n",
365
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
368
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
369
                 "bad gpgme_data_new: %s: %s\n",
 
370
                 gpgme_strsource(rc), gpgme_strerror(rc));
366
371
    gpgme_data_release(dh_crypto);
367
372
    return -1;
368
373
  }
371
376
     data buffer */
372
377
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
373
378
  if(rc != GPG_ERR_NO_ERROR){
374
 
    fprintf(stderr, "Mandos plugin mandos-client: "
375
 
            "bad gpgme_op_decrypt: %s: %s\n",
376
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
379
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
380
                 gpgme_strsource(rc), gpgme_strerror(rc));
377
381
    plaintext_length = -1;
378
382
    if(debug){
379
383
      gpgme_decrypt_result_t result;
380
384
      result = gpgme_op_decrypt_result(mc.ctx);
381
385
      if(result == NULL){
382
 
        fprintf(stderr, "Mandos plugin mandos-client: "
383
 
                "gpgme_op_decrypt_result failed\n");
 
386
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
384
387
      } else {
385
 
        fprintf(stderr, "Mandos plugin mandos-client: "
386
 
                "Unsupported algorithm: %s\n",
387
 
                result->unsupported_algorithm);
388
 
        fprintf(stderr, "Mandos plugin mandos-client: "
389
 
                "Wrong key usage: %u\n",
390
 
                result->wrong_key_usage);
 
388
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
389
                     result->unsupported_algorithm);
 
390
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
391
                     result->wrong_key_usage);
391
392
        if(result->file_name != NULL){
392
 
          fprintf(stderr, "Mandos plugin mandos-client: "
393
 
                  "File name: %s\n", result->file_name);
 
393
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
394
394
        }
395
395
        gpgme_recipient_t recipient;
396
396
        recipient = result->recipients;
397
397
        while(recipient != NULL){
398
 
          fprintf(stderr, "Mandos plugin mandos-client: "
399
 
                  "Public key algorithm: %s\n",
400
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
401
 
          fprintf(stderr, "Mandos plugin mandos-client: "
402
 
                  "Key ID: %s\n", recipient->keyid);
403
 
          fprintf(stderr, "Mandos plugin mandos-client: "
404
 
                  "Secret key available: %s\n",
405
 
                  recipient->status == GPG_ERR_NO_SECKEY
406
 
                  ? "No" : "Yes");
 
398
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
399
                       gpgme_pubkey_algo_name
 
400
                       (recipient->pubkey_algo));
 
401
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
402
          fprintf_plus(stderr, "Secret key available: %s\n",
 
403
                       recipient->status == GPG_ERR_NO_SECKEY
 
404
                       ? "No" : "Yes");
407
405
          recipient = recipient->next;
408
406
        }
409
407
      }
412
410
  }
413
411
  
414
412
  if(debug){
415
 
    fprintf(stderr, "Mandos plugin mandos-client: "
416
 
            "Decryption of OpenPGP data succeeded\n");
 
413
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
417
414
  }
418
415
  
419
416
  /* Seek back to the beginning of the GPGME plaintext data buffer */
426
423
  *plaintext = NULL;
427
424
  while(true){
428
425
    plaintext_capacity = incbuffer(plaintext,
429
 
                                      (size_t)plaintext_length,
430
 
                                      plaintext_capacity);
 
426
                                   (size_t)plaintext_length,
 
427
                                   plaintext_capacity);
431
428
    if(plaintext_capacity == 0){
432
 
        perror_plus("incbuffer");
433
 
        plaintext_length = -1;
434
 
        goto decrypt_end;
 
429
      perror_plus("incbuffer");
 
430
      plaintext_length = -1;
 
431
      goto decrypt_end;
435
432
    }
436
433
    
437
434
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
450
447
  }
451
448
  
452
449
  if(debug){
453
 
    fprintf(stderr, "Mandos plugin mandos-client: "
454
 
            "Decrypted password is: ");
 
450
    fprintf_plus(stderr, "Decrypted password is: ");
455
451
    for(ssize_t i = 0; i < plaintext_length; i++){
456
452
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
457
453
    }
479
475
/* GnuTLS log function callback */
480
476
static void debuggnutls(__attribute__((unused)) int level,
481
477
                        const char* string){
482
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
478
  fprintf_plus(stderr, "GnuTLS: %s", string);
483
479
}
484
480
 
485
481
static int init_gnutls_global(const char *pubkeyfilename,
487
483
  int ret;
488
484
  
489
485
  if(debug){
490
 
    fprintf(stderr, "Mandos plugin mandos-client: "
491
 
            "Initializing GnuTLS\n");
 
486
    fprintf_plus(stderr, "Initializing GnuTLS\n");
492
487
  }
493
488
  
494
489
  ret = gnutls_global_init();
495
490
  if(ret != GNUTLS_E_SUCCESS){
496
 
    fprintf(stderr, "Mandos plugin mandos-client: "
497
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
491
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
492
                 safer_gnutls_strerror(ret));
498
493
    return -1;
499
494
  }
500
495
  
509
504
  /* OpenPGP credentials */
510
505
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
511
506
  if(ret != GNUTLS_E_SUCCESS){
512
 
    fprintf(stderr, "Mandos plugin mandos-client: "
513
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
507
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
508
                 safer_gnutls_strerror(ret));
514
509
    gnutls_global_deinit();
515
510
    return -1;
516
511
  }
517
512
  
518
513
  if(debug){
519
 
    fprintf(stderr, "Mandos plugin mandos-client: "
520
 
            "Attempting to use OpenPGP public key %s and"
521
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
522
 
            seckeyfilename);
 
514
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
515
                 " secret key %s as GnuTLS credentials\n",
 
516
                 pubkeyfilename,
 
517
                 seckeyfilename);
523
518
  }
524
519
  
525
520
  ret = gnutls_certificate_set_openpgp_key_file
526
521
    (mc.cred, pubkeyfilename, seckeyfilename,
527
522
     GNUTLS_OPENPGP_FMT_BASE64);
528
523
  if(ret != GNUTLS_E_SUCCESS){
529
 
    fprintf(stderr,
530
 
            "Mandos plugin mandos-client: "
531
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
532
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
533
 
    fprintf(stderr, "Mandos plugin mandos-client: "
534
 
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
 
524
    fprintf_plus(stderr,
 
525
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
526
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
527
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
528
                 safer_gnutls_strerror(ret));
535
529
    goto globalfail;
536
530
  }
537
531
  
538
532
  /* GnuTLS server initialization */
539
533
  ret = gnutls_dh_params_init(&mc.dh_params);
540
534
  if(ret != GNUTLS_E_SUCCESS){
541
 
    fprintf(stderr, "Mandos plugin mandos-client: "
542
 
            "Error in GnuTLS DH parameter initialization:"
543
 
            " %s\n", safer_gnutls_strerror(ret));
 
535
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
536
                 " initialization: %s\n",
 
537
                 safer_gnutls_strerror(ret));
544
538
    goto globalfail;
545
539
  }
546
540
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
547
541
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf(stderr, "Mandos plugin mandos-client: "
549
 
            "Error in GnuTLS prime generation: %s\n",
550
 
            safer_gnutls_strerror(ret));
 
542
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
543
                 safer_gnutls_strerror(ret));
551
544
    goto globalfail;
552
545
  }
553
546
  
573
566
    }
574
567
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
575
568
  if(ret != GNUTLS_E_SUCCESS){
576
 
    fprintf(stderr, "Mandos plugin mandos-client: "
577
 
            "Error in GnuTLS session initialization: %s\n",
578
 
            safer_gnutls_strerror(ret));
 
569
    fprintf_plus(stderr,
 
570
                 "Error in GnuTLS session initialization: %s\n",
 
571
                 safer_gnutls_strerror(ret));
579
572
  }
580
573
  
581
574
  {
588
581
      }
589
582
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
590
583
    if(ret != GNUTLS_E_SUCCESS){
591
 
      fprintf(stderr, "Mandos plugin mandos-client: "
592
 
              "Syntax error at: %s\n", err);
593
 
      fprintf(stderr, "Mandos plugin mandos-client: "
594
 
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
 
584
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
585
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
586
                   safer_gnutls_strerror(ret));
595
587
      gnutls_deinit(*session);
596
588
      return -1;
597
589
    }
606
598
    }
607
599
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
608
600
  if(ret != GNUTLS_E_SUCCESS){
609
 
    fprintf(stderr, "Mandos plugin mandos-client: "
610
 
            "Error setting GnuTLS credentials: %s\n",
611
 
            safer_gnutls_strerror(ret));
 
601
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
602
                 safer_gnutls_strerror(ret));
612
603
    gnutls_deinit(*session);
613
604
    return -1;
614
605
  }
659
650
    pf = PF_INET;
660
651
    break;
661
652
  default:
662
 
    fprintf(stderr, "Mandos plugin mandos-client: "
663
 
            "Bad address family: %d\n", af);
 
653
    fprintf_plus(stderr, "Bad address family: %d\n", af);
664
654
    errno = EINVAL;
665
655
    return -1;
666
656
  }
671
661
  }
672
662
  
673
663
  if(debug){
674
 
    fprintf(stderr, "Mandos plugin mandos-client: "
675
 
            "Setting up a TCP connection to %s, port %" PRIu16
676
 
            "\n", ip, port);
 
664
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
665
                 PRIu16 "\n", ip, port);
677
666
  }
678
667
  
679
668
  tcp_sd = socket(pf, SOCK_STREAM, 0);
705
694
  }
706
695
  if(ret == 0){
707
696
    int e = errno;
708
 
    fprintf(stderr, "Mandos plugin mandos-client: "
709
 
            "Bad address: %s\n", ip);
 
697
    fprintf_plus(stderr, "Bad address: %s\n", ip);
710
698
    errno = e;
711
699
    goto mandos_end;
712
700
  }
717
705
    
718
706
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
719
707
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
720
 
                              -Wunreachable-code*/
 
708
                                -Wunreachable-code*/
721
709
      if(if_index == AVAHI_IF_UNSPEC){
722
 
        fprintf(stderr, "Mandos plugin mandos-client: "
723
 
                "An IPv6 link-local address is incomplete"
724
 
                " without a network interface\n");
 
710
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
711
                     " incomplete without a network interface\n");
725
712
        errno = EINVAL;
726
713
        goto mandos_end;
727
714
      }
745
732
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
746
733
        perror_plus("if_indextoname");
747
734
      } else {
748
 
        fprintf(stderr, "Mandos plugin mandos-client: "
749
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
750
 
                ip, interface, port);
 
735
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
736
                     "\n", ip, interface, port);
751
737
      }
752
738
    } else {
753
 
      fprintf(stderr, "Mandos plugin mandos-client: "
754
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
739
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
740
                   ip, port);
755
741
    }
756
742
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
757
743
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
767
753
      perror_plus("inet_ntop");
768
754
    } else {
769
755
      if(strcmp(addrstr, ip) != 0){
770
 
        fprintf(stderr, "Mandos plugin mandos-client: "
771
 
                "Canonical address form: %s\n", addrstr);
 
756
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
772
757
      }
773
758
    }
774
759
  }
802
787
  while(true){
803
788
    size_t out_size = strlen(out);
804
789
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
805
 
                                   out_size - written));
 
790
                                        out_size - written));
806
791
    if(ret == -1){
807
792
      int e = errno;
808
793
      perror_plus("write");
828
813
  }
829
814
  
830
815
  if(debug){
831
 
    fprintf(stderr, "Mandos plugin mandos-client: "
832
 
            "Establishing TLS session with %s\n", ip);
 
816
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
833
817
  }
834
818
  
835
819
  if(quit_now){
855
839
  
856
840
  if(ret != GNUTLS_E_SUCCESS){
857
841
    if(debug){
858
 
      fprintf(stderr, "Mandos plugin mandos-client: "
859
 
              "*** GnuTLS Handshake failed ***\n");
 
842
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
860
843
      gnutls_perror(ret);
861
844
    }
862
845
    errno = EPROTO;
866
849
  /* Read OpenPGP packet that contains the wanted password */
867
850
  
868
851
  if(debug){
869
 
    fprintf(stderr, "Mandos plugin mandos-client: "
870
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
852
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
853
                 " %s\n", ip);
871
854
  }
872
855
  
873
856
  while(true){
878
861
    }
879
862
    
880
863
    buffer_capacity = incbuffer(&buffer, buffer_length,
881
 
                                   buffer_capacity);
 
864
                                buffer_capacity);
882
865
    if(buffer_capacity == 0){
883
866
      int e = errno;
884
867
      perror_plus("incbuffer");
911
894
          }
912
895
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
913
896
        if(ret < 0){
914
 
          fprintf(stderr, "Mandos plugin mandos-client: "
915
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
897
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
898
                       "***\n");
916
899
          gnutls_perror(ret);
917
900
          errno = EPROTO;
918
901
          goto mandos_end;
919
902
        }
920
903
        break;
921
904
      default:
922
 
        fprintf(stderr, "Mandos plugin mandos-client: "
923
 
                "Unknown error while reading data from"
924
 
                " encrypted session with Mandos server\n");
 
905
        fprintf_plus(stderr, "Unknown error while reading data from"
 
906
                     " encrypted session with Mandos server\n");
925
907
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
926
908
        errno = EIO;
927
909
        goto mandos_end;
932
914
  }
933
915
  
934
916
  if(debug){
935
 
    fprintf(stderr, "Mandos plugin mandos-client: "
936
 
            "Closing TLS session\n");
 
917
    fprintf_plus(stderr, "Closing TLS session\n");
937
918
  }
938
919
  
939
920
  if(quit_now){
951
932
  
952
933
  if(buffer_length > 0){
953
934
    ssize_t decrypted_buffer_size;
954
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
955
 
                                               buffer_length,
 
935
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
956
936
                                               &decrypted_buffer);
957
937
    if(decrypted_buffer_size >= 0){
958
938
      
969
949
        if(ret == 0 and ferror(stdout)){
970
950
          int e = errno;
971
951
          if(debug){
972
 
            fprintf(stderr, "Mandos plugin mandos-client: "
973
 
                    "Error writing encrypted data: %s\n",
974
 
                    strerror(errno));
 
952
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
953
                         strerror(errno));
975
954
          }
976
955
          errno = e;
977
956
          goto mandos_end;
1034
1013
  switch(event){
1035
1014
  default:
1036
1015
  case AVAHI_RESOLVER_FAILURE:
1037
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1038
 
            "(Avahi Resolver) Failed to resolve service '%s'"
1039
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1040
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1016
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1017
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1018
                 domain,
 
1019
                 avahi_strerror(avahi_server_errno(mc.server)));
1041
1020
    break;
1042
1021
    
1043
1022
  case AVAHI_RESOLVER_FOUND:
1045
1024
      char ip[AVAHI_ADDRESS_STR_MAX];
1046
1025
      avahi_address_snprint(ip, sizeof(ip), address);
1047
1026
      if(debug){
1048
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1049
 
                "Mandos server \"%s\" found on %s (%s, %"
1050
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1051
 
                ip, (intmax_t)interface, port);
 
1027
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1028
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1029
                     host_name, ip, (intmax_t)interface, port);
1052
1030
      }
1053
1031
      int ret = start_mandos_communication(ip, port, interface,
1054
1032
                                           avahi_proto_to_af(proto));
1055
1033
      if(ret == 0){
1056
1034
        avahi_simple_poll_quit(mc.simple_poll);
1057
1035
      } else {
1058
 
        ret = add_server(ip, port, interface,
1059
 
                         avahi_proto_to_af(proto));
 
1036
        if(not add_server(ip, port, interface,
 
1037
                          avahi_proto_to_af(proto))){
 
1038
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1039
                       " list\n", name);
 
1040
        }
1060
1041
      }
1061
1042
    }
1062
1043
  }
1086
1067
  default:
1087
1068
  case AVAHI_BROWSER_FAILURE:
1088
1069
    
1089
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1090
 
            "(Avahi browser) %s\n",
1091
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1070
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1071
                 avahi_strerror(avahi_server_errno(mc.server)));
1092
1072
    avahi_simple_poll_quit(mc.simple_poll);
1093
1073
    return;
1094
1074
    
1101
1081
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1102
1082
                                    name, type, domain, protocol, 0,
1103
1083
                                    resolve_callback, NULL) == NULL)
1104
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1105
 
              "Avahi: Failed to resolve service '%s': %s\n",
1106
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1084
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1085
                   " %s\n", name,
 
1086
                   avahi_strerror(avahi_server_errno(mc.server)));
1107
1087
    break;
1108
1088
    
1109
1089
  case AVAHI_BROWSER_REMOVE:
1112
1092
  case AVAHI_BROWSER_ALL_FOR_NOW:
1113
1093
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1114
1094
    if(debug){
1115
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1116
 
              "No Mandos server found, still searching...\n");
 
1095
      fprintf_plus(stderr, "No Mandos server found, still"
 
1096
                   " searching...\n");
1117
1097
    }
1118
1098
    break;
1119
1099
  }
1158
1138
  /* Reject the loopback device */
1159
1139
  if(ifr->ifr_flags & IFF_LOOPBACK){
1160
1140
    if(debug){
1161
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1162
 
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1141
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1142
                   ifname);
1163
1143
    }
1164
1144
    return false;
1165
1145
  }
1166
1146
  /* Accept point-to-point devices only if connect_to is specified */
1167
1147
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1168
1148
    if(debug){
1169
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1170
 
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1149
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1150
                   " \"%s\"\n", ifname);
1171
1151
    }
1172
1152
    return true;
1173
1153
  }
1174
1154
  /* Otherwise, reject non-broadcast-capable devices */
1175
1155
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1176
1156
    if(debug){
1177
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1178
 
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1157
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1158
                   " \"%s\"\n", ifname);
1179
1159
    }
1180
1160
    return false;
1181
1161
  }
1182
1162
  /* Reject non-ARP interfaces (including dummy interfaces) */
1183
1163
  if(ifr->ifr_flags & IFF_NOARP){
1184
1164
    if(debug){
1185
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1186
 
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1165
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1166
                   ifname);
1187
1167
    }
1188
1168
    return false;
1189
1169
  }
1190
1170
  
1191
1171
  /* Accept this device */
1192
1172
  if(debug){
1193
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1194
 
            "Interface \"%s\" is good\n", ifname);
 
1173
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1195
1174
  }
1196
1175
  return true;
1197
1176
}
1209
1188
  struct ifreq ifr;
1210
1189
  if(not get_flags(if_entry->d_name, &ifr)){
1211
1190
    if(debug){
1212
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1213
 
              "Failed to get flags for interface \"%s\"\n",
1214
 
              if_entry->d_name);
 
1191
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1192
                   "\"%s\"\n", if_entry->d_name);
1215
1193
    }
1216
1194
    return 0;
1217
1195
  }
1235
1213
  struct ifreq ifr;
1236
1214
  if(not get_flags(if_entry->d_name, &ifr)){
1237
1215
    if(debug){
1238
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1239
 
              "Failed to get flags for interface \"%s\"\n",
1240
 
              if_entry->d_name);
 
1216
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1217
                   "\"%s\"\n", if_entry->d_name);
1241
1218
    }
1242
1219
    return 0;
1243
1220
  }
1245
1222
  /* Reject down interfaces */
1246
1223
  if(not (ifr.ifr_flags & IFF_UP)){
1247
1224
    if(debug){
1248
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1249
 
              "Rejecting down interface \"%s\"\n",
1250
 
              if_entry->d_name);
 
1225
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1226
                   if_entry->d_name);
1251
1227
    }
1252
1228
    return 0;
1253
1229
  }
1255
1231
  /* Reject non-running interfaces */
1256
1232
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1257
1233
    if(debug){
1258
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1259
 
              "Rejecting non-running interface \"%s\"\n",
1260
 
              if_entry->d_name);
 
1234
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1235
                   if_entry->d_name);
1261
1236
    }
1262
1237
    return 0;
1263
1238
  }
1282
1257
/* Is this directory entry a runnable program? */
1283
1258
int runnable_hook(const struct dirent *direntry){
1284
1259
  int ret;
 
1260
  size_t sret;
1285
1261
  struct stat st;
1286
1262
  
1287
1263
  if((direntry->d_name)[0] == '\0'){
1289
1265
    return 0;
1290
1266
  }
1291
1267
  
1292
 
  /* Save pointer to last character */
1293
 
  char *end = strchr(direntry->d_name, '\0')-1;
1294
 
  
1295
 
  if(*end == '~'){
1296
 
    /* Backup name~ */
1297
 
    return 0;
1298
 
  }
1299
 
  
1300
 
  if(((direntry->d_name)[0] == '#')
1301
 
     and (*end == '#')){
1302
 
    /* Temporary #name# */
1303
 
    return 0;
1304
 
  }
1305
 
  
1306
 
  /* XXX more rules here */
 
1268
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1269
                "abcdefghijklmnopqrstuvwxyz"
 
1270
                "0123456789"
 
1271
                "_-");
 
1272
  if((direntry->d_name)[sret] != '\0'){
 
1273
    /* Contains non-allowed characters */
 
1274
    if(debug){
 
1275
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1276
                   direntry->d_name);
 
1277
    }
 
1278
    return 0;
 
1279
  }
1307
1280
  
1308
1281
  char *fullname = NULL;
1309
 
  ret = asprintf(&fullname, "%s/%s", hookdir,
1310
 
                 direntry->d_name);
 
1282
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1311
1283
  if(ret < 0){
1312
1284
    perror_plus("asprintf");
1313
1285
    return 0;
1316
1288
  ret = stat(fullname, &st);
1317
1289
  if(ret == -1){
1318
1290
    if(debug){
1319
 
      perror_plus("Could not stat plugin");
 
1291
      perror_plus("Could not stat hook");
1320
1292
    }
1321
1293
    return 0;
1322
1294
  }
1323
1295
  if(not (S_ISREG(st.st_mode))){
1324
1296
    /* Not a regular file */
 
1297
    if(debug){
 
1298
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1299
                   direntry->d_name);
 
1300
    }
1325
1301
    return 0;
1326
1302
  }
1327
1303
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1328
1304
    /* Not executable */
 
1305
    if(debug){
 
1306
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1307
                   direntry->d_name);
 
1308
    }
1329
1309
    return 0;
1330
1310
  }
 
1311
  if(debug){
 
1312
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1313
                 direntry->d_name);
 
1314
  }
1331
1315
  return 1;
1332
1316
}
1333
1317
 
1340
1324
  while(true){
1341
1325
    if(mc.current_server == NULL){
1342
1326
      if (debug){
1343
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1344
 
                "Wait until first server is found. No timeout!\n");
 
1327
        fprintf_plus(stderr, "Wait until first server is found."
 
1328
                     " No timeout!\n");
1345
1329
      }
1346
1330
      ret = avahi_simple_poll_iterate(s, -1);
1347
1331
    } else {
1348
1332
      if (debug){
1349
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1350
 
                "Check current_server if we should run it,"
1351
 
                " or wait\n");
 
1333
        fprintf_plus(stderr, "Check current_server if we should run"
 
1334
                     " it, or wait\n");
1352
1335
      }
1353
1336
      /* the current time */
1354
1337
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1370
1353
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1371
1354
      
1372
1355
      if (debug){
1373
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1374
 
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1356
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1357
                     block_time);
1375
1358
      }
1376
1359
      
1377
1360
      if(block_time <= 0){
1404
1387
  }
1405
1388
}
1406
1389
 
 
1390
bool run_network_hooks(const char *mode, const char *interface,
 
1391
                       const float delay){
 
1392
  struct dirent **direntries;
 
1393
  struct dirent *direntry;
 
1394
  int ret;
 
1395
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1396
                         alphasort);
 
1397
  if(numhooks == -1){
 
1398
    perror_plus("scandir");
 
1399
  } else {
 
1400
    int devnull = open("/dev/null", O_RDONLY);
 
1401
    for(int i = 0; i < numhooks; i++){
 
1402
      direntry = direntries[i];
 
1403
      char *fullname = NULL;
 
1404
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1405
      if(ret < 0){
 
1406
        perror_plus("asprintf");
 
1407
        continue;
 
1408
      }
 
1409
      if(debug){
 
1410
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1411
                     direntry->d_name);
 
1412
      }
 
1413
      pid_t hook_pid = fork();
 
1414
      if(hook_pid == 0){
 
1415
        /* Child */
 
1416
        /* Raise privileges */
 
1417
        errno = 0;
 
1418
        ret = seteuid(0);
 
1419
        if(ret == -1){
 
1420
          perror_plus("seteuid");
 
1421
        }
 
1422
        /* Raise privileges even more */
 
1423
        errno = 0;
 
1424
        ret = setuid(0);
 
1425
        if(ret == -1){
 
1426
          perror_plus("setuid");
 
1427
        }
 
1428
        /* Set group */
 
1429
        errno = 0;
 
1430
        ret = setgid(0);
 
1431
        if(ret == -1){
 
1432
          perror_plus("setgid");
 
1433
        }
 
1434
        /* Reset supplementary groups */
 
1435
        errno = 0;
 
1436
        ret = setgroups(0, NULL);
 
1437
        if(ret == -1){
 
1438
          perror_plus("setgroups");
 
1439
        }
 
1440
        dup2(devnull, STDIN_FILENO);
 
1441
        close(devnull);
 
1442
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1443
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1444
        if(ret == -1){
 
1445
          perror_plus("setenv");
 
1446
          _exit(EX_OSERR);
 
1447
        }
 
1448
        ret = setenv("DEVICE", interface, 1);
 
1449
        if(ret == -1){
 
1450
          perror_plus("setenv");
 
1451
          _exit(EX_OSERR);
 
1452
        }
 
1453
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1454
        if(ret == -1){
 
1455
          perror_plus("setenv");
 
1456
          _exit(EX_OSERR);
 
1457
        }
 
1458
        ret = setenv("MODE", mode, 1);
 
1459
        if(ret == -1){
 
1460
          perror_plus("setenv");
 
1461
          _exit(EX_OSERR);
 
1462
        }
 
1463
        char *delaystring;
 
1464
        ret = asprintf(&delaystring, "%f", delay);
 
1465
        if(ret == -1){
 
1466
          perror_plus("asprintf");
 
1467
          _exit(EX_OSERR);
 
1468
        }
 
1469
        ret = setenv("DELAY", delaystring, 1);
 
1470
        if(ret == -1){
 
1471
          free(delaystring);
 
1472
          perror_plus("setenv");
 
1473
          _exit(EX_OSERR);
 
1474
        }
 
1475
        free(delaystring);
 
1476
        if(connect_to != NULL){
 
1477
          ret = setenv("CONNECT", connect_to, 1);
 
1478
          if(ret == -1){
 
1479
            perror_plus("setenv");
 
1480
            _exit(EX_OSERR);
 
1481
          }
 
1482
        }
 
1483
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1484
          perror_plus("execl");
 
1485
          _exit(EXIT_FAILURE);
 
1486
        }
 
1487
      } else {
 
1488
        int status;
 
1489
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1490
          perror_plus("waitpid");
 
1491
          free(fullname);
 
1492
          continue;
 
1493
        }
 
1494
        if(WIFEXITED(status)){
 
1495
          if(WEXITSTATUS(status) != 0){
 
1496
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1497
                         " with status %d\n", direntry->d_name,
 
1498
                         WEXITSTATUS(status));
 
1499
            free(fullname);
 
1500
            continue;
 
1501
          }
 
1502
        } else if(WIFSIGNALED(status)){
 
1503
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1504
                       " signal %d\n", direntry->d_name,
 
1505
                       WTERMSIG(status));
 
1506
          free(fullname);
 
1507
          continue;
 
1508
        } else {
 
1509
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1510
                       " crashed\n", direntry->d_name);
 
1511
          free(fullname);
 
1512
          continue;
 
1513
        }
 
1514
      }
 
1515
      free(fullname);
 
1516
      if(debug){
 
1517
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1518
                     direntry->d_name);
 
1519
      }
 
1520
    }
 
1521
    close(devnull);
 
1522
  }
 
1523
  return true;
 
1524
}
 
1525
 
1407
1526
int main(int argc, char *argv[]){
1408
1527
  AvahiSServiceBrowser *sb = NULL;
1409
1528
  int error;
1489
1608
        .group = 2 },
1490
1609
      { .name = "retry", .key = 132,
1491
1610
        .arg = "SECONDS",
1492
 
        .doc = "Retry interval used when denied by the mandos server",
 
1611
        .doc = "Retry interval used when denied by the Mandos server",
1493
1612
        .group = 2 },
1494
1613
      { .name = "network-hook-dir", .key = 133,
1495
1614
        .arg = "DIR",
1567
1686
        argp_state_help(state, state->out_stream,
1568
1687
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1569
1688
      case 'V':                 /* --version */
1570
 
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1571
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1689
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1572
1690
        exit(argp_err_exit_status);
1573
1691
        break;
1574
1692
      default:
1601
1719
  {
1602
1720
    /* Work around Debian bug #633582:
1603
1721
       <http://bugs.debian.org/633582> */
1604
 
    struct stat st;
1605
1722
    
1606
1723
    /* Re-raise priviliges */
1607
1724
    errno = 0;
1608
1725
    ret = seteuid(0);
1609
1726
    if(ret == -1){
1610
1727
      perror_plus("seteuid");
1611
 
    }
1612
 
    
1613
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1614
 
      int seckey_fd = open(seckey, O_RDONLY);
1615
 
      if(seckey_fd == -1){
1616
 
        perror_plus("open");
1617
 
      } else {
1618
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1619
 
        if(ret == -1){
1620
 
          perror_plus("fstat");
1621
 
        } else {
1622
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1623
 
            ret = fchown(seckey_fd, uid, gid);
1624
 
            if(ret == -1){
1625
 
              perror_plus("fchown");
1626
 
            }
1627
 
          }
1628
 
        }
1629
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1630
 
      }
1631
 
    }
1632
 
    
1633
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1634
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1635
 
      if(pubkey_fd == -1){
1636
 
        perror_plus("open");
1637
 
      } else {
1638
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1639
 
        if(ret == -1){
1640
 
          perror_plus("fstat");
1641
 
        } else {
1642
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1643
 
            ret = fchown(pubkey_fd, uid, gid);
1644
 
            if(ret == -1){
1645
 
              perror_plus("fchown");
1646
 
            }
1647
 
          }
1648
 
        }
1649
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1650
 
      }
1651
 
    }
1652
 
    
1653
 
    /* Lower privileges */
1654
 
    errno = 0;
1655
 
    ret = seteuid(uid);
1656
 
    if(ret == -1){
1657
 
      perror_plus("seteuid");
1658
 
    }
1659
 
  }
1660
 
  
1661
 
  /* Find network hooks and run them */
1662
 
  {
1663
 
    struct dirent **direntries;
1664
 
    struct dirent *direntry;
1665
 
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
1666
 
                           alphasort);
1667
 
    if(numhooks == -1){
1668
 
      perror_plus("scandir");
1669
1728
    } else {
1670
 
      int devnull = open("/dev/null", O_RDONLY);
1671
 
      for(int i = 0; i < numhooks; i++){
1672
 
        direntry = direntries[0];
1673
 
        char *fullname = NULL;
1674
 
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1675
 
        if(ret < 0){
1676
 
          perror_plus("asprintf");
1677
 
          continue;
1678
 
        }
1679
 
        pid_t hook_pid = fork();
1680
 
        if(hook_pid == 0){
1681
 
          /* Child */
1682
 
          dup2(devnull, STDIN_FILENO);
1683
 
          close(devnull);
1684
 
          dup2(STDERR_FILENO, STDOUT_FILENO);
1685
 
          ret = setenv("DEVICE", interface, 1);
1686
 
          if(ret == -1){
1687
 
            perror_plus("setenv");
1688
 
            exit(1);
1689
 
          }
1690
 
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1691
 
          if(ret == -1){
1692
 
            perror_plus("setenv");
1693
 
            exit(1);
1694
 
          }
1695
 
          ret = setenv("MODE", "start", 1);
1696
 
          if(ret == -1){
1697
 
            perror_plus("setenv");
1698
 
            exit(1);
1699
 
          }
1700
 
          char *delaystring;
1701
 
          ret = asprintf(&delaystring, "%f", delay);
1702
 
          if(ret == -1){
1703
 
            perror_plus("asprintf");
1704
 
            exit(1);
1705
 
          }
1706
 
          ret = setenv("DELAY", delaystring, 1);
1707
 
          if(ret == -1){
1708
 
            free(delaystring);
1709
 
            perror_plus("setenv");
1710
 
            exit(1);
1711
 
          }
1712
 
          free(delaystring);
1713
 
          ret = execl(fullname, direntry->d_name, "start", NULL);
1714
 
          perror_plus("execl");
1715
 
        } else {
1716
 
          int status;
1717
 
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1718
 
            perror_plus("waitpid");
1719
 
            free(fullname);
1720
 
            continue;
1721
 
          }
1722
 
          if(WIFEXITED(status)){
1723
 
            if(WEXITSTATUS(status) != 0){
1724
 
              fprintf(stderr, "Mandos plugin mandos-client: "
1725
 
                      "Warning: network hook \"%s\" exited"
1726
 
                      " with status %d\n", direntry->d_name,
1727
 
                      WEXITSTATUS(status));
1728
 
              free(fullname);
1729
 
              continue;
1730
 
            }
1731
 
          } else if(WIFSIGNALED(status)){
1732
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1733
 
                    "Warning: network hook \"%s\" died by"
1734
 
                    " signal %d\n", direntry->d_name,
1735
 
                    WTERMSIG(status));
1736
 
            free(fullname);
1737
 
            continue;
1738
 
          } else {
1739
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1740
 
                    "Warning: network hook \"%s\" crashed\n",
1741
 
                    direntry->d_name);
1742
 
            free(fullname);
1743
 
            continue;
1744
 
          }
1745
 
        }
1746
 
        free(fullname);
1747
 
        if(quit_now){
1748
 
          goto end;
1749
 
        }
1750
 
      }
1751
 
      close(devnull);
 
1729
      struct stat st;
 
1730
      
 
1731
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1732
        int seckey_fd = open(seckey, O_RDONLY);
 
1733
        if(seckey_fd == -1){
 
1734
          perror_plus("open");
 
1735
        } else {
 
1736
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1737
          if(ret == -1){
 
1738
            perror_plus("fstat");
 
1739
          } else {
 
1740
            if(S_ISREG(st.st_mode)
 
1741
               and st.st_uid == 0 and st.st_gid == 0){
 
1742
              ret = fchown(seckey_fd, uid, gid);
 
1743
              if(ret == -1){
 
1744
                perror_plus("fchown");
 
1745
              }
 
1746
            }
 
1747
          }
 
1748
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
1749
        }
 
1750
      }
 
1751
    
 
1752
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1753
        int pubkey_fd = open(pubkey, O_RDONLY);
 
1754
        if(pubkey_fd == -1){
 
1755
          perror_plus("open");
 
1756
        } else {
 
1757
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1758
          if(ret == -1){
 
1759
            perror_plus("fstat");
 
1760
          } else {
 
1761
            if(S_ISREG(st.st_mode)
 
1762
               and st.st_uid == 0 and st.st_gid == 0){
 
1763
              ret = fchown(pubkey_fd, uid, gid);
 
1764
              if(ret == -1){
 
1765
                perror_plus("fchown");
 
1766
              }
 
1767
            }
 
1768
          }
 
1769
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1770
        }
 
1771
      }
 
1772
    
 
1773
      /* Lower privileges */
 
1774
      errno = 0;
 
1775
      ret = seteuid(uid);
 
1776
      if(ret == -1){
 
1777
        perror_plus("seteuid");
 
1778
      }
1752
1779
    }
1753
1780
  }
1754
1781
  
 
1782
  /* Run network hooks */
 
1783
  if(not run_network_hooks("start", interface, delay)){
 
1784
    goto end;
 
1785
  }
 
1786
  
1755
1787
  if(not debug){
1756
1788
    avahi_set_log_function(empty_log);
1757
1789
  }
1771
1803
      /* Pick the first interface returned */
1772
1804
      interface = strdup(direntries[0]->d_name);
1773
1805
      if(debug){
1774
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1775
 
                "Using interface \"%s\"\n", interface);
 
1806
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1776
1807
      }
1777
1808
      if(interface == NULL){
1778
1809
        perror_plus("malloc");
1783
1814
      free(direntries);
1784
1815
    } else {
1785
1816
      free(direntries);
1786
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1787
 
              "Could not find a network interface\n");
 
1817
      fprintf_plus(stderr, "Could not find a network interface\n");
1788
1818
      exitcode = EXIT_FAILURE;
1789
1819
      goto end;
1790
1820
    }
1796
1826
  srand((unsigned int) time(NULL));
1797
1827
  mc.simple_poll = avahi_simple_poll_new();
1798
1828
  if(mc.simple_poll == NULL){
1799
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1800
 
            "Avahi: Failed to create simple poll object.\n");
 
1829
    fprintf_plus(stderr,
 
1830
                 "Avahi: Failed to create simple poll object.\n");
1801
1831
    exitcode = EX_UNAVAILABLE;
1802
1832
    goto end;
1803
1833
  }
1869
1899
  if(strcmp(interface, "none") != 0){
1870
1900
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1871
1901
    if(if_index == 0){
1872
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1873
 
              "No such interface: \"%s\"\n", interface);
 
1902
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1874
1903
      exitcode = EX_UNAVAILABLE;
1875
1904
      goto end;
1876
1905
    }
1996
2025
#endif  /* __linux__ */
1997
2026
    /* Lower privileges */
1998
2027
    errno = 0;
1999
 
    if(take_down_interface){
2000
 
      /* Lower privileges */
2001
 
      ret = seteuid(uid);
2002
 
      if(ret == -1){
2003
 
        perror_plus("seteuid");
2004
 
      }
2005
 
    } else {
2006
 
      /* Lower privileges permanently */
2007
 
      ret = setuid(uid);
2008
 
      if(ret == -1){
2009
 
        perror_plus("setuid");
2010
 
      }
 
2028
    /* Lower privileges */
 
2029
    ret = seteuid(uid);
 
2030
    if(ret == -1){
 
2031
      perror_plus("seteuid");
2011
2032
    }
2012
2033
  }
2013
2034
  
2017
2038
  
2018
2039
  ret = init_gnutls_global(pubkey, seckey);
2019
2040
  if(ret == -1){
2020
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2021
 
            "init_gnutls_global failed\n");
 
2041
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2022
2042
    exitcode = EX_UNAVAILABLE;
2023
2043
    goto end;
2024
2044
  } else {
2040
2060
  }
2041
2061
  
2042
2062
  if(not init_gpgme(pubkey, seckey, tempdir)){
2043
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2044
 
            "init_gpgme failed\n");
 
2063
    fprintf_plus(stderr, "init_gpgme failed\n");
2045
2064
    exitcode = EX_UNAVAILABLE;
2046
2065
    goto end;
2047
2066
  } else {
2057
2076
    /* (Mainly meant for debugging) */
2058
2077
    char *address = strrchr(connect_to, ':');
2059
2078
    if(address == NULL){
2060
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2061
 
              "No colon in address\n");
 
2079
      fprintf_plus(stderr, "No colon in address\n");
2062
2080
      exitcode = EX_USAGE;
2063
2081
      goto end;
2064
2082
    }
2072
2090
    tmpmax = strtoimax(address+1, &tmp, 10);
2073
2091
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2074
2092
       or tmpmax != (uint16_t)tmpmax){
2075
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2076
 
              "Bad port number\n");
 
2093
      fprintf_plus(stderr, "Bad port number\n");
2077
2094
      exitcode = EX_USAGE;
2078
2095
      goto end;
2079
2096
    }
2109
2126
        break;
2110
2127
      }
2111
2128
      if(debug){
2112
 
        fprintf(stderr, "Mandos plugin mandos-client: "
2113
 
                "Retrying in %d seconds\n", (int)retry_interval);
 
2129
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2130
                     (int)retry_interval);
2114
2131
      }
2115
2132
      sleep((int)retry_interval);
2116
2133
    }
2146
2163
  
2147
2164
  /* Check if creating the Avahi server object succeeded */
2148
2165
  if(mc.server == NULL){
2149
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2150
 
            "Failed to create Avahi server: %s\n",
2151
 
            avahi_strerror(error));
 
2166
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2167
                 avahi_strerror(error));
2152
2168
    exitcode = EX_UNAVAILABLE;
2153
2169
    goto end;
2154
2170
  }
2162
2178
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2163
2179
                                   NULL, 0, browse_callback, NULL);
2164
2180
  if(sb == NULL){
2165
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2166
 
            "Failed to create service browser: %s\n",
2167
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2181
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2182
                 avahi_strerror(avahi_server_errno(mc.server)));
2168
2183
    exitcode = EX_UNAVAILABLE;
2169
2184
    goto end;
2170
2185
  }
2176
2191
  /* Run the main loop */
2177
2192
  
2178
2193
  if(debug){
2179
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2180
 
            "Starting Avahi loop search\n");
 
2194
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2181
2195
  }
2182
2196
 
2183
2197
  ret = avahi_loop_with_timeout(mc.simple_poll,
2184
2198
                                (int)(retry_interval * 1000));
2185
2199
  if(debug){
2186
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2187
 
            "avahi_loop_with_timeout exited %s\n",
2188
 
            (ret == 0) ? "successfully" : "with error");
 
2200
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2201
                 (ret == 0) ? "successfully" : "with error");
2189
2202
  }
2190
2203
  
2191
2204
 end:
2192
2205
  
2193
2206
  if(debug){
2194
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2195
 
            "%s exiting\n", argv[0]);
 
2207
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2196
2208
  }
2197
2209
  
2198
2210
  /* Cleanup things */
2214
2226
  if(gpgme_initialized){
2215
2227
    gpgme_release(mc.ctx);
2216
2228
  }
2217
 
 
 
2229
  
2218
2230
  /* Cleans up the circular linked list of Mandos servers the client
2219
2231
     has seen */
2220
2232
  if(mc.current_server != NULL){
2226
2238
    }
2227
2239
  }
2228
2240
  
2229
 
  /* XXX run network hooks "stop" here  */
 
2241
  /* Run network hooks */
 
2242
  run_network_hooks("stop", interface, delay);
2230
2243
  
2231
 
  /* Take down the network interface */
2232
 
  if(take_down_interface){
2233
 
    /* Re-raise priviliges */
 
2244
  /* Re-raise priviliges */
 
2245
  {
2234
2246
    errno = 0;
2235
2247
    ret = seteuid(0);
2236
2248
    if(ret == -1){
2237
2249
      perror_plus("seteuid");
2238
2250
    }
2239
 
    if(geteuid() == 0){
 
2251
    
 
2252
    /* Take down the network interface */
 
2253
    if(take_down_interface and geteuid() == 0){
2240
2254
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2241
2255
      if(ret == -1){
2242
2256
        perror_plus("ioctl SIOCGIFFLAGS");
2251
2265
      if(ret == -1){
2252
2266
        perror_plus("close");
2253
2267
      }
2254
 
      /* Lower privileges permanently */
2255
 
      errno = 0;
2256
 
      ret = setuid(uid);
2257
 
      if(ret == -1){
2258
 
        perror_plus("setuid");
2259
 
      }
2260
2268
    }
2261
2269
  }
 
2270
  /* Lower privileges permanently */
 
2271
  errno = 0;
 
2272
  ret = setuid(uid);
 
2273
  if(ret == -1){
 
2274
    perror_plus("setuid");
 
2275
  }
2262
2276
  
2263
2277
  /* Removes the GPGME temp directory and all files inside */
2264
2278
  if(tempdir_created){
2278
2292
        }
2279
2293
        ret = remove(fullname);
2280
2294
        if(ret == -1){
2281
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2282
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
2295
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2296
                       strerror(errno));
2283
2297
        }
2284
2298
        free(fullname);
2285
2299
      }