/mandos/release

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

« back to all changes in this revision

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

* plugins.d/mandos-client.c: Prefix all printouts with "Mandos plugin
                             mandos-client: ".
* plugins.d/mandos-client.c (main): Wait for network hooks and check
                                    the completion status.

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