/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

Four new interrelated features:

1. Support using a different network interface via both initramfs.conf
   (the DEVICE setting) and the kernel command line (sixth field of
   the "ip=" option as in Linux' Documentation/nfsroot.txt).

2. Support connecting to a specified Mandos server directly using a
   kernel command line option ("mandos=connect:<ADDRESS>:<PORT>").

3. Support connecting directly to an IPv4 address (and port) using the
   "--connect" option of mandos-client.

4. Support an empty string to the --interface option to mandos-client.

* Makefile (WARN): Increase strictness by changing to
                   "-Wstrict-aliasing=1".

* debian/mandos-client.README.Debian (Use the Correct Network
  Interface): Changed to refer to initramfs.conf and nfsroot.txt.
  (Test the Server): Improve wording.
  (Non-local Connection): New section.
* initramfs-tools-script: Obey DEVICE environment variable and setting
                          from "/conf/initramfs.conf".  Also let any
                          "ip=" kernel command line option override
                          it.  Support new "mandos=connect" option.
                          Call "configure_networking" to set up IP
                          address on interface if necessary.
* plugin-runner.conf: Change example.
* plugins.d/mandos-client.c: Some whitespace and comment changes.
  (start_mandos_communication): Take an additional argument for
                                address family, all callers changed.
                                Connect to an IPv4 address if address
                                family is AF_INET.  Only set IPv6
                                scope_id for link-local addresses.
  (main): Accept empty interface name; this will not bring up any
         interface and leave the interface as unspecified.  Also do
         not restore kernel log level if lowering it failed.
* plugins.d/mandos-client.xml (OPTIONS): Document that the
                                         "--interface" option accepts
                                         an empty string.
  (EXAMPLE): Change example IPv6 address to a link-local address.

Show diffs side-by-side

added added

removed removed

Lines of Context:
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
33
 
#ifndef _LARGEFILE_SOURCE
34
33
#define _LARGEFILE_SOURCE
35
 
#endif
36
 
#ifndef _FILE_OFFSET_BITS
37
34
#define _FILE_OFFSET_BITS 64
38
 
#endif
39
35
 
40
36
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
37
 
42
38
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror(), remove() */
 
39
                                   stdout, ferror(), sscanf(),
 
40
                                   remove() */
44
41
#include <stdint.h>             /* uint16_t, uint32_t */
45
42
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
43
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
47
 
                                   srand(), strtof(), abort() */
 
44
                                   srand() */
48
45
#include <stdbool.h>            /* bool, false, true */
49
46
#include <string.h>             /* memset(), strcmp(), strlen(),
50
47
                                   strerror(), asprintf(), strcpy() */
59
56
#include <fcntl.h>              /* open() */
60
57
#include <dirent.h>             /* opendir(), struct dirent, readdir()
61
58
                                 */
62
 
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
 
                                   strtoimax() */
 
59
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
64
60
#include <assert.h>             /* assert() */
65
61
#include <errno.h>              /* perror(), errno */
66
62
#include <time.h>               /* nanosleep(), time() */
71
67
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
72
68
                                */
73
69
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
 
                                   getuid(), getgid(), seteuid(),
75
 
                                   setgid(), pause() */
 
70
                                   getuid(), getgid(), setuid(),
 
71
                                   setgid() */
76
72
#include <arpa/inet.h>          /* inet_pton(), htons */
77
73
#include <iso646.h>             /* not, or, and */
78
74
#include <argp.h>               /* struct argp_option, error_t, struct
79
75
                                   argp_state, struct argp,
80
76
                                   argp_parse(), ARGP_KEY_ARG,
81
77
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
82
 
#include <signal.h>             /* sigemptyset(), sigaddset(),
83
 
                                   sigaction(), SIGTERM, sig_atomic_t,
84
 
                                   raise() */
85
 
 
86
78
#ifdef __linux__
87
79
#include <sys/klog.h>           /* klogctl() */
88
 
#endif  /* __linux__ */
 
80
#endif
89
81
 
90
82
/* Avahi */
91
83
/* All Avahi types, constants and functions
125
117
static const char mandos_protocol_version[] = "1";
126
118
const char *argp_program_version = "mandos-client " VERSION;
127
119
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
128
 
static const char sys_class_net[] = "/sys/class/net";
129
 
char *connect_to = NULL;
130
120
 
131
121
/* Used for passing in values through the Avahi callback functions */
132
122
typedef struct {
139
129
  gpgme_ctx_t ctx;
140
130
} mandos_context;
141
131
 
142
 
/* global context so signal handler can reach it*/
143
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
144
 
                      .dh_bits = 1024, .priority = "SECURE256"
145
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
146
 
 
147
 
sig_atomic_t quit_now = 0;
148
 
int signal_received = 0;
149
 
 
150
132
/*
151
 
 * Make additional room in "buffer" for at least BUFFER_SIZE more
152
 
 * bytes. "buffer_capacity" is how much is currently allocated,
 
133
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
 
134
 * "buffer_capacity" is how much is currently allocated,
153
135
 * "buffer_length" is how much is already used.
154
136
 */
155
 
size_t incbuffer(char **buffer, size_t buffer_length,
 
137
size_t adjustbuffer(char **buffer, size_t buffer_length,
156
138
                  size_t buffer_capacity){
157
139
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
158
140
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
167
149
/* 
168
150
 * Initialize GPGME.
169
151
 */
170
 
static bool init_gpgme(const char *seckey,
 
152
static bool init_gpgme(mandos_context *mc, const char *seckey,
171
153
                       const char *pubkey, const char *tempdir){
 
154
  int ret;
172
155
  gpgme_error_t rc;
173
156
  gpgme_engine_info_t engine_info;
174
157
  
177
160
   * Helper function to insert pub and seckey to the engine keyring.
178
161
   */
179
162
  bool import_key(const char *filename){
180
 
    int ret;
181
163
    int fd;
182
164
    gpgme_data_t pgp_data;
183
165
    
194
176
      return false;
195
177
    }
196
178
    
197
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
179
    rc = gpgme_op_import(mc->ctx, pgp_data);
198
180
    if(rc != GPG_ERR_NO_ERROR){
199
181
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
200
182
              gpgme_strsource(rc), gpgme_strerror(rc));
210
192
  }
211
193
  
212
194
  if(debug){
213
 
    fprintf(stderr, "Initializing GPGME\n");
 
195
    fprintf(stderr, "Initialize gpgme\n");
214
196
  }
215
197
  
216
198
  /* Init GPGME */
243
225
  }
244
226
  
245
227
  /* Create new GPGME "context" */
246
 
  rc = gpgme_new(&(mc.ctx));
 
228
  rc = gpgme_new(&(mc->ctx));
247
229
  if(rc != GPG_ERR_NO_ERROR){
248
230
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
249
231
            gpgme_strsource(rc), gpgme_strerror(rc));
254
236
    return false;
255
237
  }
256
238
  
257
 
  return true;
 
239
  return true; 
258
240
}
259
241
 
260
242
/* 
261
243
 * Decrypt OpenPGP data.
262
244
 * Returns -1 on error
263
245
 */
264
 
static ssize_t pgp_packet_decrypt(const char *cryptotext,
 
246
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
 
247
                                  const char *cryptotext,
265
248
                                  size_t crypto_size,
266
249
                                  char **plaintext){
267
250
  gpgme_data_t dh_crypto, dh_plain;
294
277
  
295
278
  /* Decrypt data from the cryptotext data buffer to the plaintext
296
279
     data buffer */
297
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
280
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
298
281
  if(rc != GPG_ERR_NO_ERROR){
299
282
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
300
283
            gpgme_strsource(rc), gpgme_strerror(rc));
301
284
    plaintext_length = -1;
302
285
    if(debug){
303
286
      gpgme_decrypt_result_t result;
304
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
287
      result = gpgme_op_decrypt_result(mc->ctx);
305
288
      if(result == NULL){
306
289
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
307
290
      } else {
314
297
        }
315
298
        gpgme_recipient_t recipient;
316
299
        recipient = result->recipients;
317
 
        while(recipient != NULL){
318
 
          fprintf(stderr, "Public key algorithm: %s\n",
319
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
320
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
321
 
          fprintf(stderr, "Secret key available: %s\n",
322
 
                  recipient->status == GPG_ERR_NO_SECKEY
323
 
                  ? "No" : "Yes");
324
 
          recipient = recipient->next;
 
300
        if(recipient){
 
301
          while(recipient != NULL){
 
302
            fprintf(stderr, "Public key algorithm: %s\n",
 
303
                    gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
304
            fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
305
            fprintf(stderr, "Secret key available: %s\n",
 
306
                    recipient->status == GPG_ERR_NO_SECKEY
 
307
                    ? "No" : "Yes");
 
308
            recipient = recipient->next;
 
309
          }
325
310
        }
326
311
      }
327
312
    }
341
326
  
342
327
  *plaintext = NULL;
343
328
  while(true){
344
 
    plaintext_capacity = incbuffer(plaintext,
 
329
    plaintext_capacity = adjustbuffer(plaintext,
345
330
                                      (size_t)plaintext_length,
346
331
                                      plaintext_capacity);
347
332
    if(plaintext_capacity == 0){
348
 
        perror("incbuffer");
 
333
        perror("adjustbuffer");
349
334
        plaintext_length = -1;
350
335
        goto decrypt_end;
351
336
    }
397
382
  fprintf(stderr, "GnuTLS: %s", string);
398
383
}
399
384
 
400
 
static int init_gnutls_global(const char *pubkeyfilename,
 
385
static int init_gnutls_global(mandos_context *mc,
 
386
                              const char *pubkeyfilename,
401
387
                              const char *seckeyfilename){
402
388
  int ret;
403
389
  
421
407
  }
422
408
  
423
409
  /* OpenPGP credentials */
424
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
410
  gnutls_certificate_allocate_credentials(&mc->cred);
425
411
  if(ret != GNUTLS_E_SUCCESS){
426
412
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
427
413
                                                    from
439
425
  }
440
426
  
441
427
  ret = gnutls_certificate_set_openpgp_key_file
442
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
428
    (mc->cred, pubkeyfilename, seckeyfilename,
443
429
     GNUTLS_OPENPGP_FMT_BASE64);
444
430
  if(ret != GNUTLS_E_SUCCESS){
445
431
    fprintf(stderr,
451
437
  }
452
438
  
453
439
  /* GnuTLS server initialization */
454
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
440
  ret = gnutls_dh_params_init(&mc->dh_params);
455
441
  if(ret != GNUTLS_E_SUCCESS){
456
442
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
457
443
            " %s\n", safer_gnutls_strerror(ret));
458
444
    goto globalfail;
459
445
  }
460
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
446
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
461
447
  if(ret != GNUTLS_E_SUCCESS){
462
448
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
463
449
            safer_gnutls_strerror(ret));
464
450
    goto globalfail;
465
451
  }
466
452
  
467
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
453
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
468
454
  
469
455
  return 0;
470
456
  
471
457
 globalfail:
472
458
  
473
 
  gnutls_certificate_free_credentials(mc.cred);
 
459
  gnutls_certificate_free_credentials(mc->cred);
474
460
  gnutls_global_deinit();
475
 
  gnutls_dh_params_deinit(mc.dh_params);
 
461
  gnutls_dh_params_deinit(mc->dh_params);
476
462
  return -1;
477
463
}
478
464
 
479
 
static int init_gnutls_session(gnutls_session_t *session){
 
465
static int init_gnutls_session(mandos_context *mc,
 
466
                               gnutls_session_t *session){
480
467
  int ret;
481
468
  /* GnuTLS session creation */
482
 
  do {
483
 
    ret = gnutls_init(session, GNUTLS_SERVER);
484
 
    if(quit_now){
485
 
      return -1;
486
 
    }
487
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
469
  ret = gnutls_init(session, GNUTLS_SERVER);
488
470
  if(ret != GNUTLS_E_SUCCESS){
489
471
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
490
472
            safer_gnutls_strerror(ret));
492
474
  
493
475
  {
494
476
    const char *err;
495
 
    do {
496
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
497
 
      if(quit_now){
498
 
        gnutls_deinit(*session);
499
 
        return -1;
500
 
      }
501
 
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
477
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
502
478
    if(ret != GNUTLS_E_SUCCESS){
503
479
      fprintf(stderr, "Syntax error at: %s\n", err);
504
480
      fprintf(stderr, "GnuTLS error: %s\n",
508
484
    }
509
485
  }
510
486
  
511
 
  do {
512
 
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
513
 
                                 mc.cred);
514
 
    if(quit_now){
515
 
      gnutls_deinit(*session);
516
 
      return -1;
517
 
    }
518
 
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
 
487
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
488
                               mc->cred);
519
489
  if(ret != GNUTLS_E_SUCCESS){
520
490
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
521
491
            safer_gnutls_strerror(ret));
524
494
  }
525
495
  
526
496
  /* ignore client certificate if any. */
527
 
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
 
497
  gnutls_certificate_server_set_request(*session,
 
498
                                        GNUTLS_CERT_IGNORE);
528
499
  
529
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
500
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
530
501
  
531
502
  return 0;
532
503
}
538
509
/* Called when a Mandos server is found */
539
510
static int start_mandos_communication(const char *ip, uint16_t port,
540
511
                                      AvahiIfIndex if_index,
541
 
                                      int af){
542
 
  int ret, tcp_sd = -1;
 
512
                                      mandos_context *mc, int af){
 
513
  int ret, tcp_sd;
543
514
  ssize_t sret;
544
515
  union {
545
516
    struct sockaddr_in in;
546
517
    struct sockaddr_in6 in6;
547
518
  } to;
548
519
  char *buffer = NULL;
549
 
  char *decrypted_buffer = NULL;
 
520
  char *decrypted_buffer;
550
521
  size_t buffer_length = 0;
551
522
  size_t buffer_capacity = 0;
 
523
  ssize_t decrypted_buffer_size;
552
524
  size_t written;
553
 
  int retval = -1;
 
525
  int retval = 0;
554
526
  gnutls_session_t session;
555
527
  int pf;                       /* Protocol family */
556
528
  
557
 
  if(quit_now){
558
 
    return -1;
559
 
  }
560
 
  
561
529
  switch(af){
562
530
  case AF_INET6:
563
531
    pf = PF_INET6;
570
538
    return -1;
571
539
  }
572
540
  
573
 
  ret = init_gnutls_session(&session);
 
541
  ret = init_gnutls_session(mc, &session);
574
542
  if(ret != 0){
575
543
    return -1;
576
544
  }
583
551
  tcp_sd = socket(pf, SOCK_STREAM, 0);
584
552
  if(tcp_sd < 0){
585
553
    perror("socket");
586
 
    goto mandos_end;
587
 
  }
588
 
  
589
 
  if(quit_now){
590
 
    goto mandos_end;
 
554
    return -1;
591
555
  }
592
556
  
593
557
  memset(&to, 0, sizeof(to));
594
558
  if(af == AF_INET6){
595
 
    to.in6.sin6_family = (sa_family_t)af;
 
559
    to.in6.sin6_family = (uint16_t)af;
596
560
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
597
561
  } else {                      /* IPv4 */
598
562
    to.in.sin_family = (sa_family_t)af;
600
564
  }
601
565
  if(ret < 0 ){
602
566
    perror("inet_pton");
603
 
    goto mandos_end;
 
567
    return -1;
604
568
  }
605
569
  if(ret == 0){
606
570
    fprintf(stderr, "Bad address: %s\n", ip);
607
 
    goto mandos_end;
 
571
    return -1;
608
572
  }
609
573
  if(af == AF_INET6){
610
574
    to.in6.sin6_port = htons(port); /* Spurious warnings from
617
581
      if(if_index == AVAHI_IF_UNSPEC){
618
582
        fprintf(stderr, "An IPv6 link-local address is incomplete"
619
583
                " without a network interface\n");
620
 
        goto mandos_end;
 
584
        return -1;
621
585
      }
622
586
      /* Set the network interface number as scope */
623
587
      to.in6.sin6_scope_id = (uint32_t)if_index;
628
592
                                     -Wunreachable-code */
629
593
  }
630
594
  
631
 
  if(quit_now){
632
 
    goto mandos_end;
633
 
  }
634
 
  
635
595
  if(debug){
636
596
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
637
597
      char interface[IF_NAMESIZE];
664
624
    }
665
625
  }
666
626
  
667
 
  if(quit_now){
668
 
    goto mandos_end;
669
 
  }
670
 
  
671
627
  if(af == AF_INET6){
672
628
    ret = connect(tcp_sd, &to.in6, sizeof(to));
673
629
  } else {
675
631
  }
676
632
  if(ret < 0){
677
633
    perror("connect");
678
 
    goto mandos_end;
679
 
  }
680
 
  
681
 
  if(quit_now){
682
 
    goto mandos_end;
 
634
    return -1;
683
635
  }
684
636
  
685
637
  const char *out = mandos_protocol_version;
690
642
                                   out_size - written));
691
643
    if(ret == -1){
692
644
      perror("write");
 
645
      retval = -1;
693
646
      goto mandos_end;
694
647
    }
695
648
    written += (size_t)ret;
703
656
        break;
704
657
      }
705
658
    }
706
 
  
707
 
    if(quit_now){
708
 
      goto mandos_end;
709
 
    }
710
659
  }
711
660
  
712
661
  if(debug){
713
662
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
714
663
  }
715
664
  
716
 
  if(quit_now){
717
 
    goto mandos_end;
718
 
  }
719
 
  
720
665
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
721
666
  
722
 
  if(quit_now){
723
 
    goto mandos_end;
724
 
  }
725
 
  
726
 
  do {
 
667
  do{
727
668
    ret = gnutls_handshake(session);
728
 
    if(quit_now){
729
 
      goto mandos_end;
730
 
    }
731
669
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
732
670
  
733
671
  if(ret != GNUTLS_E_SUCCESS){
735
673
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
736
674
      gnutls_perror(ret);
737
675
    }
 
676
    retval = -1;
738
677
    goto mandos_end;
739
678
  }
740
679
  
746
685
  }
747
686
  
748
687
  while(true){
749
 
    
750
 
    if(quit_now){
751
 
      goto mandos_end;
752
 
    }
753
 
    
754
 
    buffer_capacity = incbuffer(&buffer, buffer_length,
 
688
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
755
689
                                   buffer_capacity);
756
690
    if(buffer_capacity == 0){
757
 
      perror("incbuffer");
758
 
      goto mandos_end;
759
 
    }
760
 
    
761
 
    if(quit_now){
 
691
      perror("adjustbuffer");
 
692
      retval = -1;
762
693
      goto mandos_end;
763
694
    }
764
695
    
773
704
      case GNUTLS_E_AGAIN:
774
705
        break;
775
706
      case GNUTLS_E_REHANDSHAKE:
776
 
        do {
 
707
        do{
777
708
          ret = gnutls_handshake(session);
778
 
          
779
 
          if(quit_now){
780
 
            goto mandos_end;
781
 
          }
782
709
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
783
710
        if(ret < 0){
784
711
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
785
712
          gnutls_perror(ret);
 
713
          retval = -1;
786
714
          goto mandos_end;
787
715
        }
788
716
        break;
789
717
      default:
790
718
        fprintf(stderr, "Unknown error while reading data from"
791
719
                " encrypted session with Mandos server\n");
 
720
        retval = -1;
792
721
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
793
722
        goto mandos_end;
794
723
      }
801
730
    fprintf(stderr, "Closing TLS session\n");
802
731
  }
803
732
  
804
 
  if(quit_now){
805
 
    goto mandos_end;
806
 
  }
807
 
  
808
 
  do {
809
 
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
810
 
    if(quit_now){
811
 
      goto mandos_end;
812
 
    }
813
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
 
733
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
814
734
  
815
735
  if(buffer_length > 0){
816
 
    ssize_t decrypted_buffer_size;
817
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
736
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
818
737
                                               buffer_length,
819
738
                                               &decrypted_buffer);
820
739
    if(decrypted_buffer_size >= 0){
821
 
      
822
740
      written = 0;
823
741
      while(written < (size_t) decrypted_buffer_size){
824
 
        if(quit_now){
825
 
          goto mandos_end;
826
 
        }
827
 
        
828
742
        ret = (int)fwrite(decrypted_buffer + written, 1,
829
743
                          (size_t)decrypted_buffer_size - written,
830
744
                          stdout);
833
747
            fprintf(stderr, "Error writing encrypted data: %s\n",
834
748
                    strerror(errno));
835
749
          }
836
 
          goto mandos_end;
 
750
          retval = -1;
 
751
          break;
837
752
        }
838
753
        written += (size_t)ret;
839
754
      }
840
 
      retval = 0;
 
755
      free(decrypted_buffer);
 
756
    } else {
 
757
      retval = -1;
841
758
    }
 
759
  } else {
 
760
    retval = -1;
842
761
  }
843
762
  
844
763
  /* Shutdown procedure */
845
764
  
846
765
 mandos_end:
847
 
  free(decrypted_buffer);
848
766
  free(buffer);
849
 
  if(tcp_sd >= 0){
850
 
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
851
 
  }
 
767
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
852
768
  if(ret == -1){
853
769
    perror("close");
854
770
  }
855
771
  gnutls_deinit(session);
856
 
  if(quit_now){
857
 
    retval = -1;
858
 
  }
859
772
  return retval;
860
773
}
861
774
 
872
785
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
873
786
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
874
787
                             flags,
875
 
                             AVAHI_GCC_UNUSED void* userdata){
 
788
                             void* userdata){
 
789
  mandos_context *mc = userdata;
876
790
  assert(r);
877
791
  
878
792
  /* Called whenever a service has been resolved successfully or
879
793
     timed out */
880
794
  
881
 
  if(quit_now){
882
 
    return;
883
 
  }
884
 
  
885
795
  switch(event){
886
796
  default:
887
797
  case AVAHI_RESOLVER_FAILURE:
888
798
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
889
799
            " of type '%s' in domain '%s': %s\n", name, type, domain,
890
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
800
            avahi_strerror(avahi_server_errno(mc->server)));
891
801
    break;
892
802
    
893
803
  case AVAHI_RESOLVER_FOUND:
899
809
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
900
810
                ip, (intmax_t)interface, port);
901
811
      }
902
 
      int ret = start_mandos_communication(ip, port, interface,
 
812
      int ret = start_mandos_communication(ip, port, interface, mc,
903
813
                                           avahi_proto_to_af(proto));
904
814
      if(ret == 0){
905
 
        avahi_simple_poll_quit(mc.simple_poll);
 
815
        avahi_simple_poll_quit(mc->simple_poll);
906
816
      }
907
817
    }
908
818
  }
918
828
                            const char *domain,
919
829
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
920
830
                            flags,
921
 
                            AVAHI_GCC_UNUSED void* userdata){
 
831
                            void* userdata){
 
832
  mandos_context *mc = userdata;
922
833
  assert(b);
923
834
  
924
835
  /* Called whenever a new services becomes available on the LAN or
925
836
     is removed from the LAN */
926
837
  
927
 
  if(quit_now){
928
 
    return;
929
 
  }
930
 
  
931
838
  switch(event){
932
839
  default:
933
840
  case AVAHI_BROWSER_FAILURE:
934
841
    
935
842
    fprintf(stderr, "(Avahi browser) %s\n",
936
 
            avahi_strerror(avahi_server_errno(mc.server)));
937
 
    avahi_simple_poll_quit(mc.simple_poll);
 
843
            avahi_strerror(avahi_server_errno(mc->server)));
 
844
    avahi_simple_poll_quit(mc->simple_poll);
938
845
    return;
939
846
    
940
847
  case AVAHI_BROWSER_NEW:
943
850
       the callback function is called the Avahi server will free the
944
851
       resolver for us. */
945
852
    
946
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
947
 
                                    name, type, domain, protocol, 0,
948
 
                                    resolve_callback, NULL) == NULL)
 
853
    if(!(avahi_s_service_resolver_new(mc->server, interface,
 
854
                                       protocol, name, type, domain,
 
855
                                       AVAHI_PROTO_INET6, 0,
 
856
                                       resolve_callback, mc)))
949
857
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
950
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
858
              name, avahi_strerror(avahi_server_errno(mc->server)));
951
859
    break;
952
860
    
953
861
  case AVAHI_BROWSER_REMOVE:
962
870
  }
963
871
}
964
872
 
965
 
/* stop main loop after sigterm has been called */
966
 
static void handle_sigterm(int sig){
967
 
  if(quit_now){
968
 
    return;
969
 
  }
970
 
  quit_now = 1;
971
 
  signal_received = sig;
972
 
  int old_errno = errno;
973
 
  if(mc.simple_poll != NULL){
974
 
    avahi_simple_poll_quit(mc.simple_poll);
975
 
  }
976
 
  errno = old_errno;
977
 
}
978
 
 
979
 
/* 
980
 
 * This function determines if a directory entry in /sys/class/net
981
 
 * corresponds to an acceptable network device.
982
 
 * (This function is passed to scandir(3) as a filter function.)
983
 
 */
984
 
int good_interface(const struct dirent *if_entry){
985
 
  ssize_t ssret;
986
 
  char *flagname = NULL;
987
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
988
 
                     if_entry->d_name);
989
 
  if(ret < 0){
990
 
    perror("asprintf");
991
 
    return 0;
992
 
  }
993
 
  if(if_entry->d_name[0] == '.'){
994
 
    return 0;
995
 
  }
996
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
997
 
  if(flags_fd == -1){
998
 
    perror("open");
999
 
    return 0;
1000
 
  }
1001
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1002
 
  /* read line from flags_fd */
1003
 
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
1004
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1005
 
  flagstring[(size_t)to_read] = '\0';
1006
 
  if(flagstring == NULL){
1007
 
    perror("malloc");
1008
 
    close(flags_fd);
1009
 
    return 0;
1010
 
  }
1011
 
  while(to_read > 0){
1012
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1013
 
                                             (size_t)to_read));
1014
 
    if(ssret == -1){
1015
 
      perror("read");
1016
 
      free(flagstring);
1017
 
      close(flags_fd);
1018
 
      return 0;
1019
 
    }
1020
 
    to_read -= ssret;
1021
 
    if(ssret == 0){
1022
 
      break;
1023
 
    }
1024
 
  }
1025
 
  close(flags_fd);
1026
 
  intmax_t tmpmax;
1027
 
  char *tmp;
1028
 
  errno = 0;
1029
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1030
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1031
 
                                         and not (isspace(*tmp)))
1032
 
     or tmpmax != (ifreq_flags)tmpmax){
1033
 
    if(debug){
1034
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1035
 
              flagstring, if_entry->d_name);
1036
 
    }
1037
 
    free(flagstring);
1038
 
    return 0;
1039
 
  }
1040
 
  free(flagstring);
1041
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
1042
 
  /* Reject the loopback device */
1043
 
  if(flags & IFF_LOOPBACK){
1044
 
    if(debug){
1045
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1046
 
              if_entry->d_name);
1047
 
    }
1048
 
    return 0;
1049
 
  }
1050
 
  /* Accept point-to-point devices only if connect_to is specified */
1051
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1052
 
    if(debug){
1053
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1054
 
              if_entry->d_name);
1055
 
    }
1056
 
    return 1;
1057
 
  }
1058
 
  /* Otherwise, reject non-broadcast-capable devices */
1059
 
  if(not (flags & IFF_BROADCAST)){
1060
 
    if(debug){
1061
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1062
 
              if_entry->d_name);
1063
 
    }
1064
 
    return 0;
1065
 
  }
1066
 
  /* Accept this device */
1067
 
  if(debug){
1068
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1069
 
            if_entry->d_name);
1070
 
  }
1071
 
  return 1;
1072
 
}
1073
 
 
1074
873
int main(int argc, char *argv[]){
1075
874
  AvahiSServiceBrowser *sb = NULL;
1076
875
  int error;
1077
876
  int ret;
1078
877
  intmax_t tmpmax;
1079
 
  char *tmp;
 
878
  int numchars;
1080
879
  int exitcode = EXIT_SUCCESS;
1081
 
  const char *interface = "";
 
880
  const char *interface = "eth0";
1082
881
  struct ifreq network;
1083
 
  int sd = -1;
1084
 
  bool take_down_interface = false;
 
882
  int sd;
1085
883
  uid_t uid;
1086
884
  gid_t gid;
 
885
  char *connect_to = NULL;
1087
886
  char tempdir[] = "/tmp/mandosXXXXXX";
1088
887
  bool tempdir_created = false;
1089
888
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1090
889
  const char *seckey = PATHDIR "/" SECKEY;
1091
890
  const char *pubkey = PATHDIR "/" PUBKEY;
1092
891
  
 
892
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
893
                        .dh_bits = 1024, .priority = "SECURE256"
 
894
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
1093
895
  bool gnutls_initialized = false;
1094
896
  bool gpgme_initialized = false;
1095
 
  float delay = 2.5f;
1096
 
  
1097
 
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1098
 
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1099
 
  
1100
 
  uid = getuid();
1101
 
  gid = getgid();
1102
 
  
1103
 
  /* Lower any group privileges we might have, just to be safe */
1104
 
  errno = 0;
1105
 
  ret = setgid(gid);
1106
 
  if(ret == -1){
1107
 
    perror("setgid");
1108
 
  }
1109
 
  
1110
 
  /* Lower user privileges (temporarily) */
1111
 
  errno = 0;
1112
 
  ret = seteuid(uid);
1113
 
  if(ret == -1){
1114
 
    perror("seteuid");
1115
 
  }
1116
 
  
1117
 
  if(quit_now){
1118
 
    goto end;
1119
 
  }
 
897
  double delay = 2.5;
1120
898
  
1121
899
  {
1122
900
    struct argp_option options[] = {
1174
952
        pubkey = arg;
1175
953
        break;
1176
954
      case 129:                 /* --dh-bits */
1177
 
        errno = 0;
1178
 
        tmpmax = strtoimax(arg, &tmp, 10);
1179
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1180
 
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
 
955
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
956
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
 
957
           or arg[numchars] != '\0'){
1181
958
          fprintf(stderr, "Bad number of DH bits\n");
1182
959
          exit(EXIT_FAILURE);
1183
960
        }
1187
964
        mc.priority = arg;
1188
965
        break;
1189
966
      case 131:                 /* --delay */
1190
 
        errno = 0;
1191
 
        delay = strtof(arg, &tmp);
1192
 
        if(errno != 0 or tmp == arg or *tmp != '\0'){
 
967
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
 
968
        if(ret < 1 or arg[numchars] != '\0'){
1193
969
          fprintf(stderr, "Bad delay\n");
1194
970
          exit(EXIT_FAILURE);
1195
971
        }
1216
992
    }
1217
993
  }
1218
994
  
1219
 
  if(not debug){
1220
 
    avahi_set_log_function(empty_log);
1221
 
  }
1222
 
 
1223
 
  if(interface[0] == '\0'){
1224
 
    struct dirent **direntries;
1225
 
    ret = scandir(sys_class_net, &direntries, good_interface,
1226
 
                  alphasort);
1227
 
    if(ret >= 1){
1228
 
      /* Pick the first good interface */
1229
 
      interface = strdup(direntries[0]->d_name);
1230
 
      if(debug){
1231
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1232
 
      }
1233
 
      if(interface == NULL){
1234
 
        perror("malloc");
1235
 
        free(direntries);
1236
 
        exitcode = EXIT_FAILURE;
1237
 
        goto end;
1238
 
      }
1239
 
      free(direntries);
1240
 
    } else {
1241
 
      free(direntries);
1242
 
      fprintf(stderr, "Could not find a network interface\n");
1243
 
      exitcode = EXIT_FAILURE;
1244
 
      goto end;
1245
 
    }
1246
 
  }
1247
 
  
1248
 
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1249
 
     from the signal handler */
1250
 
  /* Initialize the pseudo-RNG for Avahi */
1251
 
  srand((unsigned int) time(NULL));
1252
 
  mc.simple_poll = avahi_simple_poll_new();
1253
 
  if(mc.simple_poll == NULL){
1254
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1255
 
    exitcode = EXIT_FAILURE;
1256
 
    goto end;
1257
 
  }
1258
 
  
1259
 
  sigemptyset(&sigterm_action.sa_mask);
1260
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1261
 
  if(ret == -1){
1262
 
    perror("sigaddset");
1263
 
    exitcode = EXIT_FAILURE;
1264
 
    goto end;
1265
 
  }
1266
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1267
 
  if(ret == -1){
1268
 
    perror("sigaddset");
1269
 
    exitcode = EXIT_FAILURE;
1270
 
    goto end;
1271
 
  }
1272
 
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1273
 
  if(ret == -1){
1274
 
    perror("sigaddset");
1275
 
    exitcode = EXIT_FAILURE;
1276
 
    goto end;
1277
 
  }
1278
 
  /* Need to check if the handler is SIG_IGN before handling:
1279
 
     | [[info:libc:Initial Signal Actions]] |
1280
 
     | [[info:libc:Basic Signal Handling]]  |
1281
 
  */
1282
 
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1283
 
  if(ret == -1){
1284
 
    perror("sigaction");
1285
 
    return EXIT_FAILURE;
1286
 
  }
1287
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1288
 
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1289
 
    if(ret == -1){
1290
 
      perror("sigaction");
1291
 
      exitcode = EXIT_FAILURE;
1292
 
      goto end;
1293
 
    }
1294
 
  }
1295
 
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1296
 
  if(ret == -1){
1297
 
    perror("sigaction");
1298
 
    return EXIT_FAILURE;
1299
 
  }
1300
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1301
 
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1302
 
    if(ret == -1){
1303
 
      perror("sigaction");
1304
 
      exitcode = EXIT_FAILURE;
1305
 
      goto end;
1306
 
    }
1307
 
  }
1308
 
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1309
 
  if(ret == -1){
1310
 
    perror("sigaction");
1311
 
    return EXIT_FAILURE;
1312
 
  }
1313
 
  if(old_sigterm_action.sa_handler != SIG_IGN){
1314
 
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1315
 
    if(ret == -1){
1316
 
      perror("sigaction");
1317
 
      exitcode = EXIT_FAILURE;
1318
 
      goto end;
1319
 
    }
1320
 
  }
1321
 
  
1322
995
  /* If the interface is down, bring it up */
1323
 
  if(strcmp(interface, "none") != 0){
1324
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1325
 
    if(if_index == 0){
1326
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1327
 
      exitcode = EXIT_FAILURE;
1328
 
      goto end;
1329
 
    }
1330
 
    
1331
 
    if(quit_now){
1332
 
      goto end;
1333
 
    }
1334
 
    
1335
 
    /* Re-raise priviliges */
1336
 
    errno = 0;
1337
 
    ret = seteuid(0);
1338
 
    if(ret == -1){
1339
 
      perror("seteuid");
1340
 
    }
1341
 
    
 
996
  if(interface[0] != '\0'){
1342
997
#ifdef __linux__
1343
998
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1344
999
       messages to mess up the prompt */
1348
1003
      restore_loglevel = false;
1349
1004
      perror("klogctl");
1350
1005
    }
1351
 
#endif  /* __linux__ */
 
1006
#endif
1352
1007
    
1353
1008
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1354
1009
    if(sd < 0){
1361
1016
          perror("klogctl");
1362
1017
        }
1363
1018
      }
1364
 
#endif  /* __linux__ */
1365
 
      /* Lower privileges */
1366
 
      errno = 0;
1367
 
      ret = seteuid(uid);
1368
 
      if(ret == -1){
1369
 
        perror("seteuid");
1370
 
      }
 
1019
#endif
1371
1020
      goto end;
1372
1021
    }
1373
1022
    strcpy(network.ifr_name, interface);
1381
1030
          perror("klogctl");
1382
1031
        }
1383
1032
      }
1384
 
#endif  /* __linux__ */
 
1033
#endif
1385
1034
      exitcode = EXIT_FAILURE;
1386
 
      /* Lower privileges */
1387
 
      errno = 0;
1388
 
      ret = seteuid(uid);
1389
 
      if(ret == -1){
1390
 
        perror("seteuid");
1391
 
      }
1392
1035
      goto end;
1393
1036
    }
1394
1037
    if((network.ifr_flags & IFF_UP) == 0){
1395
1038
      network.ifr_flags |= IFF_UP;
1396
 
      take_down_interface = true;
1397
1039
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1398
1040
      if(ret == -1){
1399
 
        take_down_interface = false;
1400
 
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
 
1041
        perror("ioctl SIOCSIFFLAGS");
1401
1042
        exitcode = EXIT_FAILURE;
1402
1043
#ifdef __linux__
1403
1044
        if(restore_loglevel){
1406
1047
            perror("klogctl");
1407
1048
          }
1408
1049
        }
1409
 
#endif  /* __linux__ */
1410
 
        /* Lower privileges */
1411
 
        errno = 0;
1412
 
        ret = seteuid(uid);
1413
 
        if(ret == -1){
1414
 
          perror("seteuid");
1415
 
        }
 
1050
#endif
1416
1051
        goto end;
1417
1052
      }
1418
1053
    }
1430
1065
        perror("nanosleep");
1431
1066
      }
1432
1067
    }
1433
 
    if(not take_down_interface){
1434
 
      /* We won't need the socket anymore */
1435
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1436
 
      if(ret == -1){
1437
 
        perror("close");
1438
 
      }
 
1068
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1069
    if(ret == -1){
 
1070
      perror("close");
1439
1071
    }
1440
1072
#ifdef __linux__
1441
1073
    if(restore_loglevel){
1445
1077
        perror("klogctl");
1446
1078
      }
1447
1079
    }
1448
 
#endif  /* __linux__ */
1449
 
    /* Lower privileges */
1450
 
    errno = 0;
1451
 
    if(take_down_interface){
1452
 
      /* Lower privileges */
1453
 
      ret = seteuid(uid);
1454
 
      if(ret == -1){
1455
 
        perror("seteuid");
1456
 
      }
1457
 
    } else {
1458
 
      /* Lower privileges permanently */
1459
 
      ret = setuid(uid);
1460
 
      if(ret == -1){
1461
 
        perror("setuid");
1462
 
      }
1463
 
    }
1464
 
  }
1465
 
  
1466
 
  if(quit_now){
1467
 
    goto end;
1468
 
  }
1469
 
  
1470
 
  ret = init_gnutls_global(pubkey, seckey);
 
1080
#endif
 
1081
  }
 
1082
  
 
1083
  uid = getuid();
 
1084
  gid = getgid();
 
1085
  
 
1086
  errno = 0;
 
1087
  setgid(gid);
 
1088
  if(ret == -1){
 
1089
    perror("setgid");
 
1090
  }
 
1091
  
 
1092
  ret = setuid(uid);
 
1093
  if(ret == -1){
 
1094
    perror("setuid");
 
1095
  }
 
1096
  
 
1097
  ret = init_gnutls_global(&mc, pubkey, seckey);
1471
1098
  if(ret == -1){
1472
1099
    fprintf(stderr, "init_gnutls_global failed\n");
1473
1100
    exitcode = EXIT_FAILURE;
1476
1103
    gnutls_initialized = true;
1477
1104
  }
1478
1105
  
1479
 
  if(quit_now){
1480
 
    goto end;
1481
 
  }
1482
 
  
1483
 
  tempdir_created = true;
1484
1106
  if(mkdtemp(tempdir) == NULL){
1485
 
    tempdir_created = false;
1486
1107
    perror("mkdtemp");
1487
1108
    goto end;
1488
1109
  }
1489
 
  
1490
 
  if(quit_now){
1491
 
    goto end;
1492
 
  }
1493
 
  
1494
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
1110
  tempdir_created = true;
 
1111
  
 
1112
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
1495
1113
    fprintf(stderr, "init_gpgme failed\n");
1496
1114
    exitcode = EXIT_FAILURE;
1497
1115
    goto end;
1499
1117
    gpgme_initialized = true;
1500
1118
  }
1501
1119
  
1502
 
  if(quit_now){
1503
 
    goto end;
 
1120
  if(interface[0] != '\0'){
 
1121
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1122
    if(if_index == 0){
 
1123
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1124
      exitcode = EXIT_FAILURE;
 
1125
      goto end;
 
1126
    }
1504
1127
  }
1505
1128
  
1506
1129
  if(connect_to != NULL){
1512
1135
      exitcode = EXIT_FAILURE;
1513
1136
      goto end;
1514
1137
    }
1515
 
    
1516
 
    if(quit_now){
1517
 
      goto end;
1518
 
    }
1519
 
    
1520
1138
    uint16_t port;
1521
 
    errno = 0;
1522
 
    tmpmax = strtoimax(address+1, &tmp, 10);
1523
 
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1524
 
       or tmpmax != (uint16_t)tmpmax){
 
1139
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
1140
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
 
1141
       or address[numchars+1] != '\0'){
1525
1142
      fprintf(stderr, "Bad port number\n");
1526
1143
      exitcode = EXIT_FAILURE;
1527
1144
      goto end;
1528
1145
    }
1529
 
  
1530
 
    if(quit_now){
1531
 
      goto end;
1532
 
    }
1533
 
    
1534
1146
    port = (uint16_t)tmpmax;
1535
1147
    *address = '\0';
1536
1148
    address = connect_to;
1541
1153
    } else {
1542
1154
      af = AF_INET;
1543
1155
    }
1544
 
    
1545
 
    if(quit_now){
1546
 
      goto end;
1547
 
    }
1548
 
    
1549
 
    ret = start_mandos_communication(address, port, if_index, af);
 
1156
    ret = start_mandos_communication(address, port, if_index, &mc,
 
1157
                                     af);
1550
1158
    if(ret < 0){
1551
1159
      exitcode = EXIT_FAILURE;
1552
1160
    } else {
1555
1163
    goto end;
1556
1164
  }
1557
1165
  
1558
 
  if(quit_now){
 
1166
  if(not debug){
 
1167
    avahi_set_log_function(empty_log);
 
1168
  }
 
1169
  
 
1170
  /* Initialize the pseudo-RNG for Avahi */
 
1171
  srand((unsigned int) time(NULL));
 
1172
  
 
1173
  /* Allocate main Avahi loop object */
 
1174
  mc.simple_poll = avahi_simple_poll_new();
 
1175
  if(mc.simple_poll == NULL){
 
1176
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1177
    exitcode = EXIT_FAILURE;
1559
1178
    goto end;
1560
1179
  }
1561
1180
  
1585
1204
    goto end;
1586
1205
  }
1587
1206
  
1588
 
  if(quit_now){
1589
 
    goto end;
1590
 
  }
1591
 
  
1592
1207
  /* Create the Avahi service browser */
1593
1208
  sb = avahi_s_service_browser_new(mc.server, if_index,
1594
 
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1595
 
                                   NULL, 0, browse_callback, NULL);
 
1209
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
 
1210
                                   NULL, 0, browse_callback, &mc);
1596
1211
  if(sb == NULL){
1597
1212
    fprintf(stderr, "Failed to create service browser: %s\n",
1598
1213
            avahi_strerror(avahi_server_errno(mc.server)));
1600
1215
    goto end;
1601
1216
  }
1602
1217
  
1603
 
  if(quit_now){
1604
 
    goto end;
1605
 
  }
1606
 
  
1607
1218
  /* Run the main loop */
1608
1219
  
1609
1220
  if(debug){
1638
1249
    gpgme_release(mc.ctx);
1639
1250
  }
1640
1251
  
1641
 
  /* Take down the network interface */
1642
 
  if(take_down_interface){
1643
 
    /* Re-raise priviliges */
1644
 
    errno = 0;
1645
 
    ret = seteuid(0);
1646
 
    if(ret == -1){
1647
 
      perror("seteuid");
1648
 
    }
1649
 
    if(geteuid() == 0){
1650
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1651
 
      if(ret == -1){
1652
 
        perror("ioctl SIOCGIFFLAGS");
1653
 
      } else if(network.ifr_flags & IFF_UP) {
1654
 
        network.ifr_flags &= ~IFF_UP; /* clear flag */
1655
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1656
 
        if(ret == -1){
1657
 
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
1658
 
        }
1659
 
      }
1660
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1661
 
      if(ret == -1){
1662
 
        perror("close");
1663
 
      }
1664
 
      /* Lower privileges permanently */
1665
 
      errno = 0;
1666
 
      ret = setuid(uid);
1667
 
      if(ret == -1){
1668
 
        perror("setuid");
1669
 
      }
1670
 
    }
1671
 
  }
1672
 
  
1673
1252
  /* Removes the temp directory used by GPGME */
1674
1253
  if(tempdir_created){
1675
1254
    DIR *d;
1714
1293
    }
1715
1294
  }
1716
1295
  
1717
 
  if(quit_now){
1718
 
    sigemptyset(&old_sigterm_action.sa_mask);
1719
 
    old_sigterm_action.sa_handler = SIG_DFL;
1720
 
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
1721
 
                                            &old_sigterm_action,
1722
 
                                            NULL));
1723
 
    if(ret == -1){
1724
 
      perror("sigaction");
1725
 
    }
1726
 
    do {
1727
 
      ret = raise(signal_received);
1728
 
    } while(ret != 0 and errno == EINTR);
1729
 
    if(ret != 0){
1730
 
      perror("raise");
1731
 
      abort();
1732
 
    }
1733
 
    TEMP_FAILURE_RETRY(pause());
1734
 
  }
1735
 
  
1736
1296
  return exitcode;
1737
1297
}