/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

* initramfs-tools-hook: Install network hooks (and any required files)
                        in the initramfs image.
* plugins.d/mandos-client.c (main): Also set MANDOSNETHOOKDIR for
                                    network hooks.
* plugins.d/mandos-client.xml (OPTIONS): Use <filename
                                         class="directory">, not
                                         <directory>.

Show diffs side-by-side

added added

removed removed

Lines of Context:
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open() */
 
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
85
85
                                   raise() */
86
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
89
                                   WEXITSTATUS(), WTERMSIG() */
88
90
 
89
91
#ifdef __linux__
90
92
#include <sys/klog.h>           /* klogctl() */
108
110
                                   init_gnutls_session(),
109
111
                                   GNUTLS_* */
110
112
#include <gnutls/openpgp.h>
111
 
                          /* gnutls_certificate_set_openpgp_key_file(),
112
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
113
                         /* gnutls_certificate_set_openpgp_key_file(),
 
114
                            GNUTLS_OPENPGP_FMT_BASE64 */
113
115
 
114
116
/* GPGME */
115
117
#include <gpgme.h>              /* All GPGME types, constants and
123
125
#define PATHDIR "/conf/conf.d/mandos"
124
126
#define SECKEY "seckey.txt"
125
127
#define PUBKEY "pubkey.txt"
 
128
#define HOOKDIR "/lib/mandos/network-hooks.d"
126
129
 
127
130
bool debug = false;
128
131
static const char mandos_protocol_version[] = "1";
129
132
const char *argp_program_version = "mandos-client " VERSION;
130
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
133
const char *argp_program_bug_address = "<mandos@recompile.se>";
131
134
static const char sys_class_net[] = "/sys/class/net";
132
135
char *connect_to = NULL;
 
136
const char *hookdir = HOOKDIR;
133
137
 
134
138
/* Doubly linked list that need to be circularly linked when used */
135
139
typedef struct server{
176
180
 * "buffer_length" is how much is already used.
177
181
 */
178
182
size_t incbuffer(char **buffer, size_t buffer_length,
179
 
                  size_t buffer_capacity){
 
183
                 size_t buffer_capacity){
180
184
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
181
185
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
182
186
    if(buffer == NULL){
187
191
  return buffer_capacity;
188
192
}
189
193
 
190
 
int add_server(const char *ip, uint16_t port,
191
 
                 AvahiIfIndex if_index,
192
 
                 int af){
 
194
/* Add server to set of servers to retry periodically */
 
195
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
196
               int af){
193
197
  int ret;
194
198
  server *new_server = malloc(sizeof(server));
195
199
  if(new_server == NULL){
197
201
    return -1;
198
202
  }
199
203
  *new_server = (server){ .ip = strdup(ip),
200
 
                         .port = port,
201
 
                         .if_index = if_index,
202
 
                         .af = af };
 
204
                          .port = port,
 
205
                          .if_index = if_index,
 
206
                          .af = af };
203
207
  if(new_server->ip == NULL){
204
208
    perror_plus("strdup");
205
209
    return -1;
206
210
  }
207
 
  /* unique case of first server */
 
211
  /* Special case of first server */
208
212
  if (mc.current_server == NULL){
209
213
    new_server->next = new_server;
210
214
    new_server->prev = new_server;
211
215
    mc.current_server = new_server;
212
 
  /* Placing the new server last in the list */
 
216
  /* Place the new server last in the list */
213
217
  } else {
214
218
    new_server->next = mc.current_server;
215
219
    new_server->prev = mc.current_server->prev;
227
231
/* 
228
232
 * Initialize GPGME.
229
233
 */
230
 
static bool init_gpgme(const char *seckey,
231
 
                       const char *pubkey, const char *tempdir){
 
234
static bool init_gpgme(const char *seckey, const char *pubkey,
 
235
                       const char *tempdir){
232
236
  gpgme_error_t rc;
233
237
  gpgme_engine_info_t engine_info;
234
238
  
249
253
    
250
254
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
251
255
    if(rc != GPG_ERR_NO_ERROR){
252
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
256
      fprintf(stderr, "Mandos plugin mandos-client: "
 
257
              "bad gpgme_data_new_from_fd: %s: %s\n",
253
258
              gpgme_strsource(rc), gpgme_strerror(rc));
254
259
      return false;
255
260
    }
256
261
    
257
262
    rc = gpgme_op_import(mc.ctx, pgp_data);
258
263
    if(rc != GPG_ERR_NO_ERROR){
259
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
264
      fprintf(stderr, "Mandos plugin mandos-client: "
 
265
              "bad gpgme_op_import: %s: %s\n",
260
266
              gpgme_strsource(rc), gpgme_strerror(rc));
261
267
      return false;
262
268
    }
270
276
  }
271
277
  
272
278
  if(debug){
273
 
    fprintf(stderr, "Initializing GPGME\n");
 
279
    fprintf(stderr, "Mandos plugin mandos-client: "
 
280
            "Initializing GPGME\n");
274
281
  }
275
282
  
276
283
  /* Init GPGME */
277
284
  gpgme_check_version(NULL);
278
285
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
279
286
  if(rc != GPG_ERR_NO_ERROR){
280
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
287
    fprintf(stderr, "Mandos plugin mandos-client: "
 
288
            "bad gpgme_engine_check_version: %s: %s\n",
281
289
            gpgme_strsource(rc), gpgme_strerror(rc));
282
290
    return false;
283
291
  }
284
292
  
285
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
293
  /* Set GPGME home directory for the OpenPGP engine only */
286
294
  rc = gpgme_get_engine_info(&engine_info);
287
295
  if(rc != GPG_ERR_NO_ERROR){
288
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
296
    fprintf(stderr, "Mandos plugin mandos-client: "
 
297
            "bad gpgme_get_engine_info: %s: %s\n",
289
298
            gpgme_strsource(rc), gpgme_strerror(rc));
290
299
    return false;
291
300
  }
298
307
    engine_info = engine_info->next;
299
308
  }
300
309
  if(engine_info == NULL){
301
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
310
    fprintf(stderr, "Mandos plugin mandos-client: "
 
311
            "Could not set GPGME home dir to %s\n", tempdir);
302
312
    return false;
303
313
  }
304
314
  
305
315
  /* Create new GPGME "context" */
306
316
  rc = gpgme_new(&(mc.ctx));
307
317
  if(rc != GPG_ERR_NO_ERROR){
308
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
309
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
318
    fprintf(stderr, "Mandos plugin mandos-client: "
 
319
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
320
            gpgme_strerror(rc));
310
321
    return false;
311
322
  }
312
323
  
331
342
  ssize_t plaintext_length = 0;
332
343
  
333
344
  if(debug){
334
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
345
    fprintf(stderr, "Mandos plugin mandos-client: "
 
346
            "Trying to decrypt OpenPGP data\n");
335
347
  }
336
348
  
337
349
  /* Create new GPGME data buffer from memory cryptotext */
338
350
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
339
351
                               0);
340
352
  if(rc != GPG_ERR_NO_ERROR){
341
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
353
    fprintf(stderr, "Mandos plugin mandos-client: "
 
354
            "bad gpgme_data_new_from_mem: %s: %s\n",
342
355
            gpgme_strsource(rc), gpgme_strerror(rc));
343
356
    return -1;
344
357
  }
346
359
  /* Create new empty GPGME data buffer for the plaintext */
347
360
  rc = gpgme_data_new(&dh_plain);
348
361
  if(rc != GPG_ERR_NO_ERROR){
349
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
362
    fprintf(stderr, "Mandos plugin mandos-client: "
 
363
            "bad gpgme_data_new: %s: %s\n",
350
364
            gpgme_strsource(rc), gpgme_strerror(rc));
351
365
    gpgme_data_release(dh_crypto);
352
366
    return -1;
356
370
     data buffer */
357
371
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
358
372
  if(rc != GPG_ERR_NO_ERROR){
359
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
373
    fprintf(stderr, "Mandos plugin mandos-client: "
 
374
            "bad gpgme_op_decrypt: %s: %s\n",
360
375
            gpgme_strsource(rc), gpgme_strerror(rc));
361
376
    plaintext_length = -1;
362
377
    if(debug){
363
378
      gpgme_decrypt_result_t result;
364
379
      result = gpgme_op_decrypt_result(mc.ctx);
365
380
      if(result == NULL){
366
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
381
        fprintf(stderr, "Mandos plugin mandos-client: "
 
382
                "gpgme_op_decrypt_result failed\n");
367
383
      } else {
368
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
384
        fprintf(stderr, "Mandos plugin mandos-client: "
 
385
                "Unsupported algorithm: %s\n",
369
386
                result->unsupported_algorithm);
370
 
        fprintf(stderr, "Wrong key usage: %u\n",
 
387
        fprintf(stderr, "Mandos plugin mandos-client: "
 
388
                "Wrong key usage: %u\n",
371
389
                result->wrong_key_usage);
372
390
        if(result->file_name != NULL){
373
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
391
          fprintf(stderr, "Mandos plugin mandos-client: "
 
392
                  "File name: %s\n", result->file_name);
374
393
        }
375
394
        gpgme_recipient_t recipient;
376
395
        recipient = result->recipients;
377
396
        while(recipient != NULL){
378
 
          fprintf(stderr, "Public key algorithm: %s\n",
 
397
          fprintf(stderr, "Mandos plugin mandos-client: "
 
398
                  "Public key algorithm: %s\n",
379
399
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
380
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
381
 
          fprintf(stderr, "Secret key available: %s\n",
 
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",
382
404
                  recipient->status == GPG_ERR_NO_SECKEY
383
405
                  ? "No" : "Yes");
384
406
          recipient = recipient->next;
389
411
  }
390
412
  
391
413
  if(debug){
392
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
414
    fprintf(stderr, "Mandos plugin mandos-client: "
 
415
            "Decryption of OpenPGP data succeeded\n");
393
416
  }
394
417
  
395
418
  /* Seek back to the beginning of the GPGME plaintext data buffer */
402
425
  *plaintext = NULL;
403
426
  while(true){
404
427
    plaintext_capacity = incbuffer(plaintext,
405
 
                                      (size_t)plaintext_length,
406
 
                                      plaintext_capacity);
 
428
                                   (size_t)plaintext_length,
 
429
                                   plaintext_capacity);
407
430
    if(plaintext_capacity == 0){
408
 
        perror_plus("incbuffer");
409
 
        plaintext_length = -1;
410
 
        goto decrypt_end;
 
431
      perror_plus("incbuffer");
 
432
      plaintext_length = -1;
 
433
      goto decrypt_end;
411
434
    }
412
435
    
413
436
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
426
449
  }
427
450
  
428
451
  if(debug){
429
 
    fprintf(stderr, "Decrypted password is: ");
 
452
    fprintf(stderr, "Mandos plugin mandos-client: "
 
453
            "Decrypted password is: ");
430
454
    for(ssize_t i = 0; i < plaintext_length; i++){
431
455
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
432
456
    }
454
478
/* GnuTLS log function callback */
455
479
static void debuggnutls(__attribute__((unused)) int level,
456
480
                        const char* string){
457
 
  fprintf(stderr, "GnuTLS: %s", string);
 
481
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
458
482
}
459
483
 
460
484
static int init_gnutls_global(const char *pubkeyfilename,
462
486
  int ret;
463
487
  
464
488
  if(debug){
465
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
489
    fprintf(stderr, "Mandos plugin mandos-client: "
 
490
            "Initializing GnuTLS\n");
466
491
  }
467
492
  
468
493
  ret = gnutls_global_init();
469
494
  if(ret != GNUTLS_E_SUCCESS){
470
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
471
 
            safer_gnutls_strerror(ret));
 
495
    fprintf(stderr, "Mandos plugin mandos-client: "
 
496
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
472
497
    return -1;
473
498
  }
474
499
  
483
508
  /* OpenPGP credentials */
484
509
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
485
510
  if(ret != GNUTLS_E_SUCCESS){
486
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
487
 
            safer_gnutls_strerror(ret));
 
511
    fprintf(stderr, "Mandos plugin mandos-client: "
 
512
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
488
513
    gnutls_global_deinit();
489
514
    return -1;
490
515
  }
491
516
  
492
517
  if(debug){
493
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
518
    fprintf(stderr, "Mandos plugin mandos-client: "
 
519
            "Attempting to use OpenPGP public key %s and"
494
520
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
495
521
            seckeyfilename);
496
522
  }
500
526
     GNUTLS_OPENPGP_FMT_BASE64);
501
527
  if(ret != GNUTLS_E_SUCCESS){
502
528
    fprintf(stderr,
 
529
            "Mandos plugin mandos-client: "
503
530
            "Error[%d] while reading the OpenPGP key pair ('%s',"
504
531
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
505
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
506
 
            safer_gnutls_strerror(ret));
 
532
    fprintf(stderr, "Mandos plugin mandos-client: "
 
533
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
507
534
    goto globalfail;
508
535
  }
509
536
  
510
537
  /* GnuTLS server initialization */
511
538
  ret = gnutls_dh_params_init(&mc.dh_params);
512
539
  if(ret != GNUTLS_E_SUCCESS){
513
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
540
    fprintf(stderr, "Mandos plugin mandos-client: "
 
541
            "Error in GnuTLS DH parameter initialization:"
514
542
            " %s\n", safer_gnutls_strerror(ret));
515
543
    goto globalfail;
516
544
  }
517
545
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
518
546
  if(ret != GNUTLS_E_SUCCESS){
519
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
547
    fprintf(stderr, "Mandos plugin mandos-client: "
 
548
            "Error in GnuTLS prime generation: %s\n",
520
549
            safer_gnutls_strerror(ret));
521
550
    goto globalfail;
522
551
  }
543
572
    }
544
573
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
545
574
  if(ret != GNUTLS_E_SUCCESS){
546
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
575
    fprintf(stderr, "Mandos plugin mandos-client: "
 
576
            "Error in GnuTLS session initialization: %s\n",
547
577
            safer_gnutls_strerror(ret));
548
578
  }
549
579
  
557
587
      }
558
588
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
559
589
    if(ret != GNUTLS_E_SUCCESS){
560
 
      fprintf(stderr, "Syntax error at: %s\n", err);
561
 
      fprintf(stderr, "GnuTLS error: %s\n",
562
 
              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));
563
594
      gnutls_deinit(*session);
564
595
      return -1;
565
596
    }
574
605
    }
575
606
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
576
607
  if(ret != GNUTLS_E_SUCCESS){
577
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
608
    fprintf(stderr, "Mandos plugin mandos-client: "
 
609
            "Error setting GnuTLS credentials: %s\n",
578
610
            safer_gnutls_strerror(ret));
579
611
    gnutls_deinit(*session);
580
612
    return -1;
626
658
    pf = PF_INET;
627
659
    break;
628
660
  default:
629
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
661
    fprintf(stderr, "Mandos plugin mandos-client: "
 
662
            "Bad address family: %d\n", af);
630
663
    errno = EINVAL;
631
664
    return -1;
632
665
  }
637
670
  }
638
671
  
639
672
  if(debug){
640
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
673
    fprintf(stderr, "Mandos plugin mandos-client: "
 
674
            "Setting up a TCP connection to %s, port %" PRIu16
641
675
            "\n", ip, port);
642
676
  }
643
677
  
670
704
  }
671
705
  if(ret == 0){
672
706
    int e = errno;
673
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
707
    fprintf(stderr, "Mandos plugin mandos-client: "
 
708
            "Bad address: %s\n", ip);
674
709
    errno = e;
675
710
    goto mandos_end;
676
711
  }
681
716
    
682
717
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
683
718
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
684
 
                              -Wunreachable-code*/
 
719
                                -Wunreachable-code*/
685
720
      if(if_index == AVAHI_IF_UNSPEC){
686
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
721
        fprintf(stderr, "Mandos plugin mandos-client: "
 
722
                "An IPv6 link-local address is incomplete"
687
723
                " without a network interface\n");
688
724
        errno = EINVAL;
689
725
        goto mandos_end;
708
744
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
709
745
        perror_plus("if_indextoname");
710
746
      } else {
711
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
747
        fprintf(stderr, "Mandos plugin mandos-client: "
 
748
                "Connection to: %s%%%s, port %" PRIu16 "\n",
712
749
                ip, interface, port);
713
750
      }
714
751
    } else {
715
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
716
 
              port);
 
752
      fprintf(stderr, "Mandos plugin mandos-client: "
 
753
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
717
754
    }
718
755
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
719
756
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
729
766
      perror_plus("inet_ntop");
730
767
    } else {
731
768
      if(strcmp(addrstr, ip) != 0){
732
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
769
        fprintf(stderr, "Mandos plugin mandos-client: "
 
770
                "Canonical address form: %s\n", addrstr);
733
771
      }
734
772
    }
735
773
  }
763
801
  while(true){
764
802
    size_t out_size = strlen(out);
765
803
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
766
 
                                   out_size - written));
 
804
                                        out_size - written));
767
805
    if(ret == -1){
768
806
      int e = errno;
769
807
      perror_plus("write");
789
827
  }
790
828
  
791
829
  if(debug){
792
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
830
    fprintf(stderr, "Mandos plugin mandos-client: "
 
831
            "Establishing TLS session with %s\n", ip);
793
832
  }
794
833
  
795
834
  if(quit_now){
815
854
  
816
855
  if(ret != GNUTLS_E_SUCCESS){
817
856
    if(debug){
818
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
857
      fprintf(stderr, "Mandos plugin mandos-client: "
 
858
              "*** GnuTLS Handshake failed ***\n");
819
859
      gnutls_perror(ret);
820
860
    }
821
861
    errno = EPROTO;
825
865
  /* Read OpenPGP packet that contains the wanted password */
826
866
  
827
867
  if(debug){
828
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
829
 
            ip);
 
868
    fprintf(stderr, "Mandos plugin mandos-client: "
 
869
            "Retrieving OpenPGP encrypted password from %s\n", ip);
830
870
  }
831
871
  
832
872
  while(true){
837
877
    }
838
878
    
839
879
    buffer_capacity = incbuffer(&buffer, buffer_length,
840
 
                                   buffer_capacity);
 
880
                                buffer_capacity);
841
881
    if(buffer_capacity == 0){
842
882
      int e = errno;
843
883
      perror_plus("incbuffer");
870
910
          }
871
911
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
872
912
        if(ret < 0){
873
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
913
          fprintf(stderr, "Mandos plugin mandos-client: "
 
914
                  "*** GnuTLS Re-handshake failed ***\n");
874
915
          gnutls_perror(ret);
875
916
          errno = EPROTO;
876
917
          goto mandos_end;
877
918
        }
878
919
        break;
879
920
      default:
880
 
        fprintf(stderr, "Unknown error while reading data from"
 
921
        fprintf(stderr, "Mandos plugin mandos-client: "
 
922
                "Unknown error while reading data from"
881
923
                " encrypted session with Mandos server\n");
882
924
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
883
925
        errno = EIO;
889
931
  }
890
932
  
891
933
  if(debug){
892
 
    fprintf(stderr, "Closing TLS session\n");
 
934
    fprintf(stderr, "Mandos plugin mandos-client: "
 
935
            "Closing TLS session\n");
893
936
  }
894
937
  
895
938
  if(quit_now){
907
950
  
908
951
  if(buffer_length > 0){
909
952
    ssize_t decrypted_buffer_size;
910
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
911
 
                                               buffer_length,
 
953
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
912
954
                                               &decrypted_buffer);
913
955
    if(decrypted_buffer_size >= 0){
914
956
      
925
967
        if(ret == 0 and ferror(stdout)){
926
968
          int e = errno;
927
969
          if(debug){
928
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
970
            fprintf(stderr, "Mandos plugin mandos-client: "
 
971
                    "Error writing encrypted data: %s\n",
929
972
                    strerror(errno));
930
973
          }
931
974
          errno = e;
989
1032
  switch(event){
990
1033
  default:
991
1034
  case AVAHI_RESOLVER_FAILURE:
992
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
1035
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1036
            "(Avahi Resolver) Failed to resolve service '%s'"
993
1037
            " of type '%s' in domain '%s': %s\n", name, type, domain,
994
1038
            avahi_strerror(avahi_server_errno(mc.server)));
995
1039
    break;
999
1043
      char ip[AVAHI_ADDRESS_STR_MAX];
1000
1044
      avahi_address_snprint(ip, sizeof(ip), address);
1001
1045
      if(debug){
1002
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1046
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1047
                "Mandos server \"%s\" found on %s (%s, %"
1003
1048
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1004
1049
                ip, (intmax_t)interface, port);
1005
1050
      }
1039
1084
  default:
1040
1085
  case AVAHI_BROWSER_FAILURE:
1041
1086
    
1042
 
    fprintf(stderr, "(Avahi browser) %s\n",
 
1087
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1088
            "(Avahi browser) %s\n",
1043
1089
            avahi_strerror(avahi_server_errno(mc.server)));
1044
1090
    avahi_simple_poll_quit(mc.simple_poll);
1045
1091
    return;
1053
1099
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1054
1100
                                    name, type, domain, protocol, 0,
1055
1101
                                    resolve_callback, NULL) == NULL)
1056
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1102
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1103
              "Avahi: Failed to resolve service '%s': %s\n",
1057
1104
              name, avahi_strerror(avahi_server_errno(mc.server)));
1058
1105
    break;
1059
1106
    
1063
1110
  case AVAHI_BROWSER_ALL_FOR_NOW:
1064
1111
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1065
1112
    if(debug){
1066
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1113
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1114
              "No Mandos server found, still searching...\n");
1067
1115
    }
1068
1116
    break;
1069
1117
  }
1084
1132
  errno = old_errno;
1085
1133
}
1086
1134
 
1087
 
/* 
1088
 
 * This function determines if a directory entry in /sys/class/net
1089
 
 * corresponds to an acceptable network device.
1090
 
 * (This function is passed to scandir(3) as a filter function.)
1091
 
 */
1092
 
int good_interface(const struct dirent *if_entry){
1093
 
  ssize_t ssret;
1094
 
  char *flagname = NULL;
1095
 
  if(if_entry->d_name[0] == '.'){
1096
 
    return 0;
1097
 
  }
1098
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1099
 
                     if_entry->d_name);
1100
 
  if(ret < 0){
1101
 
    perror_plus("asprintf");
1102
 
    return 0;
1103
 
  }
1104
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1105
 
  if(flags_fd == -1){
1106
 
    perror_plus("open");
1107
 
    free(flagname);
1108
 
    return 0;
1109
 
  }
1110
 
  free(flagname);
1111
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1112
 
  /* read line from flags_fd */
1113
 
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
1114
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1115
 
  flagstring[(size_t)to_read] = '\0';
1116
 
  if(flagstring == NULL){
1117
 
    perror_plus("malloc");
1118
 
    close(flags_fd);
1119
 
    return 0;
1120
 
  }
1121
 
  while(to_read > 0){
1122
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1123
 
                                             (size_t)to_read));
1124
 
    if(ssret == -1){
1125
 
      perror_plus("read");
1126
 
      free(flagstring);
1127
 
      close(flags_fd);
1128
 
      return 0;
1129
 
    }
1130
 
    to_read -= ssret;
1131
 
    if(ssret == 0){
1132
 
      break;
1133
 
    }
1134
 
  }
1135
 
  close(flags_fd);
1136
 
  intmax_t tmpmax;
1137
 
  char *tmp;
1138
 
  errno = 0;
1139
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1140
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1141
 
                                         and not (isspace(*tmp)))
1142
 
     or tmpmax != (ifreq_flags)tmpmax){
 
1135
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1136
  int ret;
 
1137
  
 
1138
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1139
  if(s < 0){
 
1140
    perror_plus("socket");
 
1141
    return false;
 
1142
  }
 
1143
  strcpy(ifr->ifr_name, ifname);
 
1144
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1145
  if(ret == -1){
1143
1146
    if(debug){
1144
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1145
 
              flagstring, if_entry->d_name);
 
1147
      perror_plus("ioctl SIOCGIFFLAGS");
1146
1148
    }
1147
 
    free(flagstring);
1148
 
    return 0;
 
1149
    return false;
1149
1150
  }
1150
 
  free(flagstring);
1151
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1151
  return true;
 
1152
}
 
1153
 
 
1154
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1155
  
1152
1156
  /* Reject the loopback device */
1153
 
  if(flags & IFF_LOOPBACK){
 
1157
  if(ifr->ifr_flags & IFF_LOOPBACK){
1154
1158
    if(debug){
1155
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1156
 
              if_entry->d_name);
 
1159
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1160
              "Rejecting loopback interface \"%s\"\n", ifname);
1157
1161
    }
1158
 
    return 0;
 
1162
    return false;
1159
1163
  }
1160
1164
  /* Accept point-to-point devices only if connect_to is specified */
1161
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1165
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1162
1166
    if(debug){
1163
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1164
 
              if_entry->d_name);
 
1167
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1168
              "Accepting point-to-point interface \"%s\"\n", ifname);
1165
1169
    }
1166
 
    return 1;
 
1170
    return true;
1167
1171
  }
1168
1172
  /* Otherwise, reject non-broadcast-capable devices */
1169
 
  if(not (flags & IFF_BROADCAST)){
 
1173
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1170
1174
    if(debug){
1171
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1172
 
              if_entry->d_name);
 
1175
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1176
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
1173
1177
    }
1174
 
    return 0;
 
1178
    return false;
1175
1179
  }
1176
1180
  /* Reject non-ARP interfaces (including dummy interfaces) */
1177
 
  if(flags & IFF_NOARP){
 
1181
  if(ifr->ifr_flags & IFF_NOARP){
1178
1182
    if(debug){
1179
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1180
 
              if_entry->d_name);
 
1183
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1184
              "Rejecting non-ARP interface \"%s\"\n", ifname);
1181
1185
    }
1182
 
    return 0;
 
1186
    return false;
1183
1187
  }
 
1188
  
1184
1189
  /* Accept this device */
1185
1190
  if(debug){
1186
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1187
 
            if_entry->d_name);
 
1191
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1192
            "Interface \"%s\" is good\n", ifname);
 
1193
  }
 
1194
  return true;
 
1195
}
 
1196
 
 
1197
/* 
 
1198
 * This function determines if a directory entry in /sys/class/net
 
1199
 * corresponds to an acceptable network device.
 
1200
 * (This function is passed to scandir(3) as a filter function.)
 
1201
 */
 
1202
int good_interface(const struct dirent *if_entry){
 
1203
  if(if_entry->d_name[0] == '.'){
 
1204
    return 0;
 
1205
  }
 
1206
  
 
1207
  struct ifreq ifr;
 
1208
  if(not get_flags(if_entry->d_name, &ifr)){
 
1209
    if(debug){
 
1210
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1211
              "Failed to get flags for interface \"%s\"\n",
 
1212
              if_entry->d_name);
 
1213
    }
 
1214
    return 0;
 
1215
  }
 
1216
  
 
1217
  if(not good_flags(if_entry->d_name, &ifr)){
 
1218
    return 0;
 
1219
  }
 
1220
  return 1;
 
1221
}
 
1222
 
 
1223
/* 
 
1224
 * This function determines if a directory entry in /sys/class/net
 
1225
 * corresponds to an acceptable network device which is up.
 
1226
 * (This function is passed to scandir(3) as a filter function.)
 
1227
 */
 
1228
int up_interface(const struct dirent *if_entry){
 
1229
  if(if_entry->d_name[0] == '.'){
 
1230
    return 0;
 
1231
  }
 
1232
  
 
1233
  struct ifreq ifr;
 
1234
  if(not get_flags(if_entry->d_name, &ifr)){
 
1235
    if(debug){
 
1236
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1237
              "Failed to get flags for interface \"%s\"\n",
 
1238
              if_entry->d_name);
 
1239
    }
 
1240
    return 0;
 
1241
  }
 
1242
  
 
1243
  /* Reject down interfaces */
 
1244
  if(not (ifr.ifr_flags & IFF_UP)){
 
1245
    if(debug){
 
1246
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1247
              "Rejecting down interface \"%s\"\n",
 
1248
              if_entry->d_name);
 
1249
    }
 
1250
    return 0;
 
1251
  }
 
1252
  
 
1253
  /* Reject non-running interfaces */
 
1254
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1255
    if(debug){
 
1256
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1257
              "Rejecting non-running interface \"%s\"\n",
 
1258
              if_entry->d_name);
 
1259
    }
 
1260
    return 0;
 
1261
  }
 
1262
  
 
1263
  if(not good_flags(if_entry->d_name, &ifr)){
 
1264
    return 0;
1188
1265
  }
1189
1266
  return 1;
1190
1267
}
1200
1277
  return 1;
1201
1278
}
1202
1279
 
 
1280
/* Is this directory entry a runnable program? */
 
1281
int runnable_hook(const struct dirent *direntry){
 
1282
  int ret;
 
1283
  size_t sret;
 
1284
  struct stat st;
 
1285
  
 
1286
  if((direntry->d_name)[0] == '\0'){
 
1287
    /* Empty name? */
 
1288
    return 0;
 
1289
  }
 
1290
  
 
1291
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1292
                "abcdefghijklmnopqrstuvwxyz"
 
1293
                "0123456789"
 
1294
                "_-");
 
1295
  if((direntry->d_name)[sret] != '\0'){
 
1296
    /* Contains non-allowed characters */
 
1297
    if(debug){
 
1298
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1299
              "Ignoring hook \"%s\" with bad name\n",
 
1300
              direntry->d_name);
 
1301
    }
 
1302
    return 0;
 
1303
  }
 
1304
  
 
1305
  char *fullname = NULL;
 
1306
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1307
  if(ret < 0){
 
1308
    perror_plus("asprintf");
 
1309
    return 0;
 
1310
  }
 
1311
  
 
1312
  ret = stat(fullname, &st);
 
1313
  if(ret == -1){
 
1314
    if(debug){
 
1315
      perror_plus("Could not stat hook");
 
1316
    }
 
1317
    return 0;
 
1318
  }
 
1319
  if(not (S_ISREG(st.st_mode))){
 
1320
    /* Not a regular file */
 
1321
    if(debug){
 
1322
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1323
              "Ignoring hook \"%s\" - not a file\n",
 
1324
              direntry->d_name);
 
1325
    }
 
1326
    return 0;
 
1327
  }
 
1328
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1329
    /* Not executable */
 
1330
    if(debug){
 
1331
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1332
              "Ignoring hook \"%s\" - not executable\n",
 
1333
              direntry->d_name);
 
1334
    }
 
1335
    return 0;
 
1336
  }
 
1337
  return 1;
 
1338
}
 
1339
 
1203
1340
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1204
1341
  int ret;
1205
1342
  struct timespec now;
1206
1343
  struct timespec waited_time;
1207
1344
  intmax_t block_time;
1208
 
 
 
1345
  
1209
1346
  while(true){
1210
1347
    if(mc.current_server == NULL){
1211
1348
      if (debug){
1212
 
        fprintf(stderr,
 
1349
        fprintf(stderr, "Mandos plugin mandos-client: "
1213
1350
                "Wait until first server is found. No timeout!\n");
1214
1351
      }
1215
1352
      ret = avahi_simple_poll_iterate(s, -1);
1216
1353
    } else {
1217
1354
      if (debug){
1218
 
        fprintf(stderr, "Check current_server if we should run it,"
 
1355
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1356
                "Check current_server if we should run it,"
1219
1357
                " or wait\n");
1220
1358
      }
1221
1359
      /* the current time */
1236
1374
      block_time = ((retry_interval
1237
1375
                     - ((intmax_t)waited_time.tv_sec * 1000))
1238
1376
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1239
 
 
 
1377
      
1240
1378
      if (debug){
1241
 
        fprintf(stderr, "Blocking for %ld ms\n", block_time);
 
1379
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1380
                "Blocking for %" PRIdMAX " ms\n", block_time);
1242
1381
      }
1243
 
 
 
1382
      
1244
1383
      if(block_time <= 0){
1245
1384
        ret = start_mandos_communication(mc.current_server->ip,
1246
1385
                                         mc.current_server->port,
1264
1403
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1265
1404
    }
1266
1405
    if(ret != 0){
1267
 
      if (ret > 0 or errno != EINTR) {
 
1406
      if (ret > 0 or errno != EINTR){
1268
1407
        return (ret != 1) ? ret : 0;
1269
1408
      }
1270
1409
    }
1358
1497
        .arg = "SECONDS",
1359
1498
        .doc = "Retry interval used when denied by the mandos server",
1360
1499
        .group = 2 },
 
1500
      { .name = "network-hook-dir", .key = 133,
 
1501
        .arg = "DIR",
 
1502
        .doc = "Directory where network hooks are located",
 
1503
        .group = 2 },
1361
1504
      /*
1362
1505
       * These reproduce what we would get without ARGP_NO_HELP
1363
1506
       */
1411
1554
        errno = 0;
1412
1555
        retry_interval = strtod(arg, &tmp);
1413
1556
        if(errno != 0 or tmp == arg or *tmp != '\0'
1414
 
           or (retry_interval * 1000) > INT_MAX){
 
1557
           or (retry_interval * 1000) > INT_MAX
 
1558
           or retry_interval < 0){
1415
1559
          argp_error(state, "Bad retry interval");
1416
1560
        }
1417
1561
        break;
 
1562
      case 133:                 /* --network-hook-dir */
 
1563
        hookdir = arg;
 
1564
        break;
1418
1565
        /*
1419
1566
         * These reproduce what we would get without ARGP_NO_HELP
1420
1567
         */
1426
1573
        argp_state_help(state, state->out_stream,
1427
1574
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1428
1575
      case 'V':                 /* --version */
 
1576
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1429
1577
        fprintf(state->out_stream, "%s\n", argp_program_version);
1430
1578
        exit(argp_err_exit_status);
1431
1579
        break;
1468
1616
      perror_plus("seteuid");
1469
1617
    }
1470
1618
    
1471
 
    int seckey_fd = open(PATHDIR "/" SECKEY, O_RDONLY);
1472
 
    if(seckey_fd == -1){
1473
 
      perror_plus("open");
1474
 
    } else {
1475
 
      ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1476
 
      if(ret == -1){
1477
 
        perror_plus("fstat");
 
1619
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1620
      int seckey_fd = open(seckey, O_RDONLY);
 
1621
      if(seckey_fd == -1){
 
1622
        perror_plus("open");
1478
1623
      } else {
1479
 
        if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1480
 
          ret = fchown(seckey_fd, uid, gid);
1481
 
          if(ret == -1){
1482
 
            perror_plus("fchown");
 
1624
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1625
        if(ret == -1){
 
1626
          perror_plus("fstat");
 
1627
        } else {
 
1628
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1629
            ret = fchown(seckey_fd, uid, gid);
 
1630
            if(ret == -1){
 
1631
              perror_plus("fchown");
 
1632
            }
1483
1633
          }
1484
1634
        }
 
1635
        TEMP_FAILURE_RETRY(close(seckey_fd));
1485
1636
      }
1486
 
      TEMP_FAILURE_RETRY(close(seckey_fd));
1487
1637
    }
1488
1638
    
1489
 
    int pubkey_fd = open(PATHDIR "/" PUBKEY, O_RDONLY);
1490
 
    if(pubkey_fd == -1){
1491
 
      perror_plus("open");
1492
 
    } else {
1493
 
      ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1494
 
      if(ret == -1){
1495
 
        perror_plus("fstat");
 
1639
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1640
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1641
      if(pubkey_fd == -1){
 
1642
        perror_plus("open");
1496
1643
      } else {
1497
 
        if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1498
 
          ret = fchown(pubkey_fd, uid, gid);
1499
 
          if(ret == -1){
1500
 
            perror_plus("fchown");
 
1644
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1645
        if(ret == -1){
 
1646
          perror_plus("fstat");
 
1647
        } else {
 
1648
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1649
            ret = fchown(pubkey_fd, uid, gid);
 
1650
            if(ret == -1){
 
1651
              perror_plus("fchown");
 
1652
            }
1501
1653
          }
1502
1654
        }
 
1655
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1503
1656
      }
1504
 
      TEMP_FAILURE_RETRY(close(pubkey_fd));
1505
1657
    }
1506
1658
    
1507
1659
    /* Lower privileges */
1512
1664
    }
1513
1665
  }
1514
1666
  
 
1667
  /* Find network hooks and run them */
 
1668
  {
 
1669
    struct dirent **direntries;
 
1670
    struct dirent *direntry;
 
1671
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1672
                           alphasort);
 
1673
    if(numhooks == -1){
 
1674
      perror_plus("scandir");
 
1675
    } else {
 
1676
      int devnull = open("/dev/null", O_RDONLY);
 
1677
      for(int i = 0; i < numhooks; i++){
 
1678
        direntry = direntries[0];
 
1679
        char *fullname = NULL;
 
1680
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1681
        if(ret < 0){
 
1682
          perror_plus("asprintf");
 
1683
          continue;
 
1684
        }
 
1685
        pid_t hook_pid = fork();
 
1686
        if(hook_pid == 0){
 
1687
          /* Child */
 
1688
          dup2(devnull, STDIN_FILENO);
 
1689
          close(devnull);
 
1690
          dup2(STDERR_FILENO, STDOUT_FILENO);
 
1691
          ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1692
          if(ret == -1){
 
1693
            perror_plus("setenv");
 
1694
            exit(1);
 
1695
          }
 
1696
          ret = setenv("DEVICE", interface, 1);
 
1697
          if(ret == -1){
 
1698
            perror_plus("setenv");
 
1699
            exit(1);
 
1700
          }
 
1701
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1702
          if(ret == -1){
 
1703
            perror_plus("setenv");
 
1704
            exit(1);
 
1705
          }
 
1706
          ret = setenv("MODE", "start", 1);
 
1707
          if(ret == -1){
 
1708
            perror_plus("setenv");
 
1709
            exit(1);
 
1710
          }
 
1711
          char *delaystring;
 
1712
          ret = asprintf(&delaystring, "%f", delay);
 
1713
          if(ret == -1){
 
1714
            perror_plus("asprintf");
 
1715
            exit(1);
 
1716
          }
 
1717
          ret = setenv("DELAY", delaystring, 1);
 
1718
          if(ret == -1){
 
1719
            free(delaystring);
 
1720
            perror_plus("setenv");
 
1721
            exit(1);
 
1722
          }
 
1723
          free(delaystring);
 
1724
          ret = execl(fullname, direntry->d_name, "start", NULL);
 
1725
          perror_plus("execl");
 
1726
        } else {
 
1727
          int status;
 
1728
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1729
            perror_plus("waitpid");
 
1730
            free(fullname);
 
1731
            continue;
 
1732
          }
 
1733
          if(WIFEXITED(status)){
 
1734
            if(WEXITSTATUS(status) != 0){
 
1735
              fprintf(stderr, "Mandos plugin mandos-client: "
 
1736
                      "Warning: network hook \"%s\" exited"
 
1737
                      " with status %d\n", direntry->d_name,
 
1738
                      WEXITSTATUS(status));
 
1739
              free(fullname);
 
1740
              continue;
 
1741
            }
 
1742
          } else if(WIFSIGNALED(status)){
 
1743
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1744
                    "Warning: network hook \"%s\" died by"
 
1745
                    " signal %d\n", direntry->d_name,
 
1746
                    WTERMSIG(status));
 
1747
            free(fullname);
 
1748
            continue;
 
1749
          } else {
 
1750
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1751
                    "Warning: network hook \"%s\" crashed\n",
 
1752
                    direntry->d_name);
 
1753
            free(fullname);
 
1754
            continue;
 
1755
          }
 
1756
        }
 
1757
        free(fullname);
 
1758
        if(quit_now){
 
1759
          goto end;
 
1760
        }
 
1761
      }
 
1762
      close(devnull);
 
1763
    }
 
1764
  }
 
1765
  
1515
1766
  if(not debug){
1516
1767
    avahi_set_log_function(empty_log);
1517
1768
  }
1518
 
 
 
1769
  
1519
1770
  if(interface[0] == '\0'){
1520
1771
    struct dirent **direntries;
1521
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1772
    /* First look for interfaces that are up */
 
1773
    ret = scandir(sys_class_net, &direntries, up_interface,
1522
1774
                  alphasort);
 
1775
    if(ret == 0){
 
1776
      /* No up interfaces, look for any good interfaces */
 
1777
      free(direntries);
 
1778
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1779
                    alphasort);
 
1780
    }
1523
1781
    if(ret >= 1){
1524
 
      /* Pick the first good interface */
 
1782
      /* Pick the first interface returned */
1525
1783
      interface = strdup(direntries[0]->d_name);
1526
1784
      if(debug){
1527
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1785
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1786
                "Using interface \"%s\"\n", interface);
1528
1787
      }
1529
1788
      if(interface == NULL){
1530
1789
        perror_plus("malloc");
1535
1794
      free(direntries);
1536
1795
    } else {
1537
1796
      free(direntries);
1538
 
      fprintf(stderr, "Could not find a network interface\n");
 
1797
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1798
              "Could not find a network interface\n");
1539
1799
      exitcode = EXIT_FAILURE;
1540
1800
      goto end;
1541
1801
    }
1547
1807
  srand((unsigned int) time(NULL));
1548
1808
  mc.simple_poll = avahi_simple_poll_new();
1549
1809
  if(mc.simple_poll == NULL){
1550
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1810
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1811
            "Avahi: Failed to create simple poll object.\n");
1551
1812
    exitcode = EX_UNAVAILABLE;
1552
1813
    goto end;
1553
1814
  }
1619
1880
  if(strcmp(interface, "none") != 0){
1620
1881
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1621
1882
    if(if_index == 0){
1622
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1883
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1884
              "No such interface: \"%s\"\n", interface);
1623
1885
      exitcode = EX_UNAVAILABLE;
1624
1886
      goto end;
1625
1887
    }
1766
2028
  
1767
2029
  ret = init_gnutls_global(pubkey, seckey);
1768
2030
  if(ret == -1){
1769
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2031
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2032
            "init_gnutls_global failed\n");
1770
2033
    exitcode = EX_UNAVAILABLE;
1771
2034
    goto end;
1772
2035
  } else {
1788
2051
  }
1789
2052
  
1790
2053
  if(not init_gpgme(pubkey, seckey, tempdir)){
1791
 
    fprintf(stderr, "init_gpgme failed\n");
 
2054
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2055
            "init_gpgme failed\n");
1792
2056
    exitcode = EX_UNAVAILABLE;
1793
2057
    goto end;
1794
2058
  } else {
1804
2068
    /* (Mainly meant for debugging) */
1805
2069
    char *address = strrchr(connect_to, ':');
1806
2070
    if(address == NULL){
1807
 
      fprintf(stderr, "No colon in address\n");
 
2071
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2072
              "No colon in address\n");
1808
2073
      exitcode = EX_USAGE;
1809
2074
      goto end;
1810
2075
    }
1818
2083
    tmpmax = strtoimax(address+1, &tmp, 10);
1819
2084
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1820
2085
       or tmpmax != (uint16_t)tmpmax){
1821
 
      fprintf(stderr, "Bad port number\n");
 
2086
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2087
              "Bad port number\n");
1822
2088
      exitcode = EX_USAGE;
1823
2089
      goto end;
1824
2090
    }
1829
2095
    
1830
2096
    port = (uint16_t)tmpmax;
1831
2097
    *address = '\0';
1832
 
    address = connect_to;
1833
2098
    /* Colon in address indicates IPv6 */
1834
2099
    int af;
1835
 
    if(strchr(address, ':') != NULL){
 
2100
    if(strchr(connect_to, ':') != NULL){
1836
2101
      af = AF_INET6;
 
2102
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2103
      if(connect_to[0] == '[' and address[-1] == ']')
 
2104
        {
 
2105
          connect_to++;
 
2106
          address[-1] = '\0';
 
2107
        }
1837
2108
    } else {
1838
2109
      af = AF_INET;
1839
2110
    }
 
2111
    address = connect_to;
1840
2112
    
1841
2113
    if(quit_now){
1842
2114
      goto end;
1843
2115
    }
1844
 
 
 
2116
    
1845
2117
    while(not quit_now){
1846
2118
      ret = start_mandos_communication(address, port, if_index, af);
1847
2119
      if(quit_now or ret == 0){
1848
2120
        break;
1849
2121
      }
1850
 
      sleep((int)retry_interval or 1);
1851
 
    };
1852
 
 
 
2122
      if(debug){
 
2123
        fprintf(stderr, "Mandos plugin mandos-client: "
 
2124
                "Retrying in %d seconds\n", (int)retry_interval);
 
2125
      }
 
2126
      sleep((int)retry_interval);
 
2127
    }
 
2128
    
1853
2129
    if (not quit_now){
1854
2130
      exitcode = EXIT_SUCCESS;
1855
2131
    }
1856
 
 
 
2132
    
1857
2133
    goto end;
1858
2134
  }
1859
2135
  
1881
2157
  
1882
2158
  /* Check if creating the Avahi server object succeeded */
1883
2159
  if(mc.server == NULL){
1884
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2160
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2161
            "Failed to create Avahi server: %s\n",
1885
2162
            avahi_strerror(error));
1886
2163
    exitcode = EX_UNAVAILABLE;
1887
2164
    goto end;
1896
2173
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1897
2174
                                   NULL, 0, browse_callback, NULL);
1898
2175
  if(sb == NULL){
1899
 
    fprintf(stderr, "Failed to create service browser: %s\n",
 
2176
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2177
            "Failed to create service browser: %s\n",
1900
2178
            avahi_strerror(avahi_server_errno(mc.server)));
1901
2179
    exitcode = EX_UNAVAILABLE;
1902
2180
    goto end;
1909
2187
  /* Run the main loop */
1910
2188
  
1911
2189
  if(debug){
1912
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2190
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2191
            "Starting Avahi loop search\n");
1913
2192
  }
1914
2193
 
1915
2194
  ret = avahi_loop_with_timeout(mc.simple_poll,
1916
2195
                                (int)(retry_interval * 1000));
1917
2196
  if(debug){
1918
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
2197
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2198
            "avahi_loop_with_timeout exited %s\n",
1919
2199
            (ret == 0) ? "successfully" : "with error");
1920
2200
  }
1921
2201
  
1922
2202
 end:
1923
2203
  
1924
2204
  if(debug){
1925
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2205
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2206
            "%s exiting\n", argv[0]);
1926
2207
  }
1927
2208
  
1928
2209
  /* Cleanup things */
1956
2237
    }
1957
2238
  }
1958
2239
  
 
2240
  /* XXX run network hooks "stop" here  */
 
2241
  
1959
2242
  /* Take down the network interface */
1960
2243
  if(take_down_interface){
1961
2244
    /* Re-raise priviliges */
1968
2251
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1969
2252
      if(ret == -1){
1970
2253
        perror_plus("ioctl SIOCGIFFLAGS");
1971
 
      } else if(network.ifr_flags & IFF_UP) {
 
2254
      } else if(network.ifr_flags & IFF_UP){
1972
2255
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1973
2256
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1974
2257
        if(ret == -1){
1992
2275
  if(tempdir_created){
1993
2276
    struct dirent **direntries = NULL;
1994
2277
    struct dirent *direntry = NULL;
1995
 
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
1996
 
    if (ret > 0){
1997
 
      for(int i = 0; i < ret; i++){
 
2278
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2279
                             alphasort);
 
2280
    if (numentries > 0){
 
2281
      for(int i = 0; i < numentries; i++){
1998
2282
        direntry = direntries[i];
1999
2283
        char *fullname = NULL;
2000
2284
        ret = asprintf(&fullname, "%s/%s", tempdir,
2005
2289
        }
2006
2290
        ret = remove(fullname);
2007
2291
        if(ret == -1){
2008
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2009
 
                  strerror(errno));
 
2292
          fprintf(stderr, "Mandos plugin mandos-client: "
 
2293
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
2010
2294
        }
2011
2295
        free(fullname);
2012
2296
      }
2013
2297
    }
2014
2298
 
2015
 
    /* need to be cleaned even if ret == 0 because man page doesn't
2016
 
       specify */
 
2299
    /* need to clean even if 0 because man page doesn't specify */
2017
2300
    free(direntries);
2018
 
    if (ret == -1){
 
2301
    if (numentries == -1){
2019
2302
      perror_plus("scandir");
2020
2303
    }
2021
2304
    ret = rmdir(tempdir);