/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

* initramfs-tools-hook: Also fix /lib<qual> and /usr/lib<qual>
                        directories.

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() */
48
 
#include <stdbool.h>            /* bool, false, true */
 
44
                                   srand() */
 
45
#include <stdbool.h>            /* bool, true */
49
46
#include <string.h>             /* memset(), strcmp(), strlen(),
50
47
                                   strerror(), asprintf(), strcpy() */
51
 
#include <sys/ioctl.h>          /* ioctl */
 
48
#include <sys/ioctl.h>          /* ioctl */
52
49
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
50
                                   sockaddr_in6, PF_INET6,
54
 
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
 
                                   opendir(), DIR */
 
51
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
 
52
                                   uid_t, gid_t, open(), opendir(),
 
53
                                   DIR */
56
54
#include <sys/stat.h>           /* open() */
57
55
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect() */
 
56
                                   struct in6_addr, inet_pton(),
 
57
                                   connect() */
59
58
#include <fcntl.h>              /* open() */
60
59
#include <dirent.h>             /* opendir(), struct dirent, readdir()
61
60
                                 */
62
 
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
 
                                   strtoimax() */
 
61
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
64
62
#include <assert.h>             /* assert() */
65
63
#include <errno.h>              /* perror(), errno */
66
64
#include <time.h>               /* nanosleep(), time() */
67
65
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
66
                                   SIOCSIFFLAGS, if_indextoname(),
69
67
                                   if_nametoindex(), IF_NAMESIZE */
70
 
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
71
 
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
72
 
                                */
 
68
#include <netinet/in.h>
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
 
#include <iso646.h>             /* not, or, and */
 
73
#include <iso646.h>             /* not, and, or */
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
 
                                                    from
428
 
                                                    -Wunreachable-code
429
 
                                                 */
 
413
                                                  * from
 
414
                                                  * -Wunreachable-code
 
415
                                                  */
430
416
            safer_gnutls_strerror(ret));
431
417
    gnutls_global_deinit();
432
418
    return -1;
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){
 
513
  int ret, tcp_sd;
543
514
  ssize_t sret;
544
 
  union {
545
 
    struct sockaddr_in in;
546
 
    struct sockaddr_in6 in6;
547
 
  } to;
 
515
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
548
516
  char *buffer = NULL;
549
 
  char *decrypted_buffer = NULL;
 
517
  char *decrypted_buffer;
550
518
  size_t buffer_length = 0;
551
519
  size_t buffer_capacity = 0;
 
520
  ssize_t decrypted_buffer_size;
552
521
  size_t written;
553
 
  int retval = -1;
 
522
  int retval = 0;
 
523
  char interface[IF_NAMESIZE];
554
524
  gnutls_session_t session;
555
 
  int pf;                       /* Protocol family */
556
 
  
557
 
  if(quit_now){
558
 
    return -1;
559
 
  }
560
 
  
561
 
  switch(af){
562
 
  case AF_INET6:
563
 
    pf = PF_INET6;
564
 
    break;
565
 
  case AF_INET:
566
 
    pf = PF_INET;
567
 
    break;
568
 
  default:
569
 
    fprintf(stderr, "Bad address family: %d\n", af);
570
 
    return -1;
571
 
  }
572
 
  
573
 
  ret = init_gnutls_session(&session);
 
525
  
 
526
  ret = init_gnutls_session(mc, &session);
574
527
  if(ret != 0){
575
528
    return -1;
576
529
  }
577
530
  
578
531
  if(debug){
579
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
532
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
580
533
            "\n", ip, port);
581
534
  }
582
535
  
583
 
  tcp_sd = socket(pf, SOCK_STREAM, 0);
 
536
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
584
537
  if(tcp_sd < 0){
585
538
    perror("socket");
586
 
    goto mandos_end;
 
539
    return -1;
587
540
  }
588
541
  
589
 
  if(quit_now){
590
 
    goto mandos_end;
 
542
  if(debug){
 
543
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
544
      perror("if_indextoname");
 
545
      return -1;
 
546
    }
 
547
    fprintf(stderr, "Binding to interface %s\n", interface);
591
548
  }
592
549
  
593
550
  memset(&to, 0, sizeof(to));
594
 
  if(af == AF_INET6){
595
 
    to.in6.sin6_family = (sa_family_t)af;
596
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
597
 
  } else {                      /* IPv4 */
598
 
    to.in.sin_family = (sa_family_t)af;
599
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
600
 
  }
 
551
  to.in6.sin6_family = AF_INET6;
 
552
  /* It would be nice to have a way to detect if we were passed an
 
553
     IPv4 address here.   Now we assume an IPv6 address. */
 
554
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
601
555
  if(ret < 0 ){
602
556
    perror("inet_pton");
603
 
    goto mandos_end;
 
557
    return -1;
604
558
  }
605
559
  if(ret == 0){
606
560
    fprintf(stderr, "Bad address: %s\n", ip);
607
 
    goto mandos_end;
 
561
    return -1;
608
562
  }
609
 
  if(af == AF_INET6){
610
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
611
 
                                       -Wconversion and
612
 
                                       -Wunreachable-code */
613
 
    
614
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
615
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
616
 
                              -Wunreachable-code*/
617
 
      if(if_index == AVAHI_IF_UNSPEC){
618
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
619
 
                " without a network interface\n");
620
 
        goto mandos_end;
621
 
      }
622
 
      /* Set the network interface number as scope */
623
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
624
 
    }
625
 
  } else {
626
 
    to.in.sin_port = htons(port); /* Spurious warnings from
 
563
  to.in6.sin6_port = htons(port); /* Spurious warnings from
627
564
                                     -Wconversion and
628
565
                                     -Wunreachable-code */
629
 
  }
630
566
  
631
 
  if(quit_now){
632
 
    goto mandos_end;
633
 
  }
 
567
  to.in6.sin6_scope_id = (uint32_t)if_index;
634
568
  
635
569
  if(debug){
636
 
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
637
 
      char interface[IF_NAMESIZE];
638
 
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
639
 
        perror("if_indextoname");
640
 
      } else {
641
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
642
 
                ip, interface, port);
643
 
      }
644
 
    } else {
645
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
646
 
              port);
647
 
    }
648
 
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
649
 
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
650
 
    const char *pcret;
651
 
    if(af == AF_INET6){
652
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
653
 
                        sizeof(addrstr));
654
 
    } else {
655
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
656
 
                        sizeof(addrstr));
657
 
    }
658
 
    if(pcret == NULL){
 
570
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
571
            port);
 
572
    char addrstr[INET6_ADDRSTRLEN] = "";
 
573
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
 
574
                 sizeof(addrstr)) == NULL){
659
575
      perror("inet_ntop");
660
576
    } else {
661
577
      if(strcmp(addrstr, ip) != 0){
664
580
    }
665
581
  }
666
582
  
667
 
  if(quit_now){
668
 
    goto mandos_end;
669
 
  }
670
 
  
671
 
  if(af == AF_INET6){
672
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
673
 
  } else {
674
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
675
 
  }
 
583
  ret = connect(tcp_sd, &to.in, sizeof(to));
676
584
  if(ret < 0){
677
585
    perror("connect");
678
 
    goto mandos_end;
679
 
  }
680
 
  
681
 
  if(quit_now){
682
 
    goto mandos_end;
 
586
    return -1;
683
587
  }
684
588
  
685
589
  const char *out = mandos_protocol_version;
690
594
                                   out_size - written));
691
595
    if(ret == -1){
692
596
      perror("write");
 
597
      retval = -1;
693
598
      goto mandos_end;
694
599
    }
695
600
    written += (size_t)ret;
703
608
        break;
704
609
      }
705
610
    }
706
 
  
707
 
    if(quit_now){
708
 
      goto mandos_end;
709
 
    }
710
611
  }
711
612
  
712
613
  if(debug){
713
614
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
714
615
  }
715
616
  
716
 
  if(quit_now){
717
 
    goto mandos_end;
718
 
  }
719
 
  
720
617
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
721
618
  
722
 
  if(quit_now){
723
 
    goto mandos_end;
724
 
  }
725
 
  
726
 
  do {
 
619
  do{
727
620
    ret = gnutls_handshake(session);
728
 
    if(quit_now){
729
 
      goto mandos_end;
730
 
    }
731
621
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
732
622
  
733
623
  if(ret != GNUTLS_E_SUCCESS){
735
625
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
736
626
      gnutls_perror(ret);
737
627
    }
 
628
    retval = -1;
738
629
    goto mandos_end;
739
630
  }
740
631
  
741
632
  /* Read OpenPGP packet that contains the wanted password */
742
633
  
743
634
  if(debug){
744
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
635
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
745
636
            ip);
746
637
  }
747
638
  
748
639
  while(true){
749
 
    
750
 
    if(quit_now){
751
 
      goto mandos_end;
752
 
    }
753
 
    
754
 
    buffer_capacity = incbuffer(&buffer, buffer_length,
 
640
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
755
641
                                   buffer_capacity);
756
642
    if(buffer_capacity == 0){
757
 
      perror("incbuffer");
758
 
      goto mandos_end;
759
 
    }
760
 
    
761
 
    if(quit_now){
 
643
      perror("adjustbuffer");
 
644
      retval = -1;
762
645
      goto mandos_end;
763
646
    }
764
647
    
773
656
      case GNUTLS_E_AGAIN:
774
657
        break;
775
658
      case GNUTLS_E_REHANDSHAKE:
776
 
        do {
 
659
        do{
777
660
          ret = gnutls_handshake(session);
778
 
          
779
 
          if(quit_now){
780
 
            goto mandos_end;
781
 
          }
782
661
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
783
662
        if(ret < 0){
784
663
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
785
664
          gnutls_perror(ret);
 
665
          retval = -1;
786
666
          goto mandos_end;
787
667
        }
788
668
        break;
789
669
      default:
790
670
        fprintf(stderr, "Unknown error while reading data from"
791
671
                " encrypted session with Mandos server\n");
 
672
        retval = -1;
792
673
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
793
674
        goto mandos_end;
794
675
      }
801
682
    fprintf(stderr, "Closing TLS session\n");
802
683
  }
803
684
  
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);
 
685
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
814
686
  
815
687
  if(buffer_length > 0){
816
 
    ssize_t decrypted_buffer_size;
817
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
688
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
818
689
                                               buffer_length,
819
690
                                               &decrypted_buffer);
820
691
    if(decrypted_buffer_size >= 0){
821
 
      
822
692
      written = 0;
823
693
      while(written < (size_t) decrypted_buffer_size){
824
 
        if(quit_now){
825
 
          goto mandos_end;
826
 
        }
827
 
        
828
694
        ret = (int)fwrite(decrypted_buffer + written, 1,
829
695
                          (size_t)decrypted_buffer_size - written,
830
696
                          stdout);
833
699
            fprintf(stderr, "Error writing encrypted data: %s\n",
834
700
                    strerror(errno));
835
701
          }
836
 
          goto mandos_end;
 
702
          retval = -1;
 
703
          break;
837
704
        }
838
705
        written += (size_t)ret;
839
706
      }
840
 
      retval = 0;
 
707
      free(decrypted_buffer);
 
708
    } else {
 
709
      retval = -1;
841
710
    }
 
711
  } else {
 
712
    retval = -1;
842
713
  }
843
714
  
844
715
  /* Shutdown procedure */
845
716
  
846
717
 mandos_end:
847
 
  free(decrypted_buffer);
848
718
  free(buffer);
849
 
  if(tcp_sd >= 0){
850
 
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
851
 
  }
 
719
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
852
720
  if(ret == -1){
853
721
    perror("close");
854
722
  }
855
723
  gnutls_deinit(session);
856
 
  if(quit_now){
857
 
    retval = -1;
858
 
  }
859
724
  return retval;
860
725
}
861
726
 
862
727
static void resolve_callback(AvahiSServiceResolver *r,
863
728
                             AvahiIfIndex interface,
864
 
                             AvahiProtocol proto,
 
729
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
865
730
                             AvahiResolverEvent event,
866
731
                             const char *name,
867
732
                             const char *type,
872
737
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
873
738
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
874
739
                             flags,
875
 
                             AVAHI_GCC_UNUSED void* userdata){
 
740
                             void* userdata){
 
741
  mandos_context *mc = userdata;
876
742
  assert(r);
877
743
  
878
744
  /* Called whenever a service has been resolved successfully or
879
745
     timed out */
880
746
  
881
 
  if(quit_now){
882
 
    return;
883
 
  }
884
 
  
885
747
  switch(event){
886
748
  default:
887
749
  case AVAHI_RESOLVER_FAILURE:
888
750
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
889
751
            " of type '%s' in domain '%s': %s\n", name, type, domain,
890
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
752
            avahi_strerror(avahi_server_errno(mc->server)));
891
753
    break;
892
754
    
893
755
  case AVAHI_RESOLVER_FOUND:
899
761
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
900
762
                ip, (intmax_t)interface, port);
901
763
      }
902
 
      int ret = start_mandos_communication(ip, port, interface,
903
 
                                           avahi_proto_to_af(proto));
 
764
      int ret = start_mandos_communication(ip, port, interface, mc);
904
765
      if(ret == 0){
905
 
        avahi_simple_poll_quit(mc.simple_poll);
 
766
        avahi_simple_poll_quit(mc->simple_poll);
906
767
      }
907
768
    }
908
769
  }
918
779
                            const char *domain,
919
780
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
920
781
                            flags,
921
 
                            AVAHI_GCC_UNUSED void* userdata){
 
782
                            void* userdata){
 
783
  mandos_context *mc = userdata;
922
784
  assert(b);
923
785
  
924
786
  /* Called whenever a new services becomes available on the LAN or
925
787
     is removed from the LAN */
926
788
  
927
 
  if(quit_now){
928
 
    return;
929
 
  }
930
 
  
931
789
  switch(event){
932
790
  default:
933
791
  case AVAHI_BROWSER_FAILURE:
934
792
    
935
793
    fprintf(stderr, "(Avahi browser) %s\n",
936
 
            avahi_strerror(avahi_server_errno(mc.server)));
937
 
    avahi_simple_poll_quit(mc.simple_poll);
 
794
            avahi_strerror(avahi_server_errno(mc->server)));
 
795
    avahi_simple_poll_quit(mc->simple_poll);
938
796
    return;
939
797
    
940
798
  case AVAHI_BROWSER_NEW:
943
801
       the callback function is called the Avahi server will free the
944
802
       resolver for us. */
945
803
    
946
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
947
 
                                    name, type, domain, protocol, 0,
948
 
                                    resolve_callback, NULL) == NULL)
 
804
    if(!(avahi_s_service_resolver_new(mc->server, interface,
 
805
                                       protocol, name, type, domain,
 
806
                                       AVAHI_PROTO_INET6, 0,
 
807
                                       resolve_callback, mc)))
949
808
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
950
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
809
              name, avahi_strerror(avahi_server_errno(mc->server)));
951
810
    break;
952
811
    
953
812
  case AVAHI_BROWSER_REMOVE:
962
821
  }
963
822
}
964
823
 
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
824
int main(int argc, char *argv[]){
1075
825
  AvahiSServiceBrowser *sb = NULL;
1076
826
  int error;
1077
827
  int ret;
1078
828
  intmax_t tmpmax;
1079
 
  char *tmp;
 
829
  int numchars;
1080
830
  int exitcode = EXIT_SUCCESS;
1081
 
  const char *interface = "";
 
831
  const char *interface = "eth0";
1082
832
  struct ifreq network;
1083
 
  int sd = -1;
1084
 
  bool take_down_interface = false;
 
833
  int sd;
1085
834
  uid_t uid;
1086
835
  gid_t gid;
 
836
  char *connect_to = NULL;
1087
837
  char tempdir[] = "/tmp/mandosXXXXXX";
1088
838
  bool tempdir_created = false;
1089
839
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1090
840
  const char *seckey = PATHDIR "/" SECKEY;
1091
841
  const char *pubkey = PATHDIR "/" PUBKEY;
1092
842
  
 
843
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
844
                        .dh_bits = 1024, .priority = "SECURE256"
 
845
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
1093
846
  bool gnutls_initialized = false;
1094
847
  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
 
  }
 
848
  double delay = 2.5;
1120
849
  
1121
850
  {
1122
851
    struct argp_option options[] = {
1128
857
        .group = 1 },
1129
858
      { .name = "interface", .key = 'i',
1130
859
        .arg = "NAME",
1131
 
        .doc = "Network interface that will be used to search for"
1132
 
        " Mandos servers",
 
860
        .doc = "Interface that will be used to search for Mandos"
 
861
        " servers",
1133
862
        .group = 1 },
1134
863
      { .name = "seckey", .key = 's',
1135
864
        .arg = "FILE",
1174
903
        pubkey = arg;
1175
904
        break;
1176
905
      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){
 
906
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
907
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
 
908
           or arg[numchars] != '\0'){
1181
909
          fprintf(stderr, "Bad number of DH bits\n");
1182
910
          exit(EXIT_FAILURE);
1183
911
        }
1187
915
        mc.priority = arg;
1188
916
        break;
1189
917
      case 131:                 /* --delay */
1190
 
        errno = 0;
1191
 
        delay = strtof(arg, &tmp);
1192
 
        if(errno != 0 or tmp == arg or *tmp != '\0'){
 
918
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
 
919
        if(ret < 1 or arg[numchars] != '\0'){
1193
920
          fprintf(stderr, "Bad delay\n");
1194
921
          exit(EXIT_FAILURE);
1195
922
        }
1216
943
    }
1217
944
  }
1218
945
  
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
946
  /* 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
 
    
 
947
  {
1342
948
#ifdef __linux__
1343
949
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1344
950
       messages to mess up the prompt */
1345
951
    ret = klogctl(8, NULL, 5);
1346
 
    bool restore_loglevel = true;
1347
952
    if(ret == -1){
1348
 
      restore_loglevel = false;
1349
953
      perror("klogctl");
1350
954
    }
1351
 
#endif  /* __linux__ */
 
955
#endif
1352
956
    
1353
957
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1354
958
    if(sd < 0){
1355
959
      perror("socket");
1356
960
      exitcode = EXIT_FAILURE;
1357
961
#ifdef __linux__
1358
 
      if(restore_loglevel){
1359
 
        ret = klogctl(7, NULL, 0);
1360
 
        if(ret == -1){
1361
 
          perror("klogctl");
1362
 
        }
1363
 
      }
1364
 
#endif  /* __linux__ */
1365
 
      /* Lower privileges */
1366
 
      errno = 0;
1367
 
      ret = seteuid(uid);
 
962
      ret = klogctl(7, NULL, 0);
1368
963
      if(ret == -1){
1369
 
        perror("seteuid");
 
964
        perror("klogctl");
1370
965
      }
 
966
#endif
1371
967
      goto end;
1372
968
    }
1373
969
    strcpy(network.ifr_name, interface);
1375
971
    if(ret == -1){
1376
972
      perror("ioctl SIOCGIFFLAGS");
1377
973
#ifdef __linux__
1378
 
      if(restore_loglevel){
1379
 
        ret = klogctl(7, NULL, 0);
1380
 
        if(ret == -1){
1381
 
          perror("klogctl");
1382
 
        }
 
974
      ret = klogctl(7, NULL, 0);
 
975
      if(ret == -1){
 
976
        perror("klogctl");
1383
977
      }
1384
 
#endif  /* __linux__ */
 
978
#endif
1385
979
      exitcode = EXIT_FAILURE;
1386
 
      /* Lower privileges */
1387
 
      errno = 0;
1388
 
      ret = seteuid(uid);
1389
 
      if(ret == -1){
1390
 
        perror("seteuid");
1391
 
      }
1392
980
      goto end;
1393
981
    }
1394
982
    if((network.ifr_flags & IFF_UP) == 0){
1395
983
      network.ifr_flags |= IFF_UP;
1396
 
      take_down_interface = true;
1397
984
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1398
985
      if(ret == -1){
1399
 
        take_down_interface = false;
1400
 
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
 
986
        perror("ioctl SIOCSIFFLAGS");
1401
987
        exitcode = EXIT_FAILURE;
1402
988
#ifdef __linux__
1403
 
        if(restore_loglevel){
1404
 
          ret = klogctl(7, NULL, 0);
1405
 
          if(ret == -1){
1406
 
            perror("klogctl");
1407
 
          }
1408
 
        }
1409
 
#endif  /* __linux__ */
1410
 
        /* Lower privileges */
1411
 
        errno = 0;
1412
 
        ret = seteuid(uid);
 
989
        ret = klogctl(7, NULL, 0);
1413
990
        if(ret == -1){
1414
 
          perror("seteuid");
 
991
          perror("klogctl");
1415
992
        }
 
993
#endif
1416
994
        goto end;
1417
995
      }
1418
996
    }
1430
1008
        perror("nanosleep");
1431
1009
      }
1432
1010
    }
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
 
      }
 
1011
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1012
    if(ret == -1){
 
1013
      perror("close");
1439
1014
    }
1440
1015
#ifdef __linux__
1441
 
    if(restore_loglevel){
1442
 
      /* Restores kernel loglevel to default */
1443
 
      ret = klogctl(7, NULL, 0);
1444
 
      if(ret == -1){
1445
 
        perror("klogctl");
1446
 
      }
1447
 
    }
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);
 
1016
    /* Restores kernel loglevel to default */
 
1017
    ret = klogctl(7, NULL, 0);
 
1018
    if(ret == -1){
 
1019
      perror("klogctl");
 
1020
    }
 
1021
#endif
 
1022
  }
 
1023
  
 
1024
  uid = getuid();
 
1025
  gid = getgid();
 
1026
  
 
1027
  setgid(gid);
 
1028
  if(ret == -1){
 
1029
    perror("setgid");
 
1030
  }
 
1031
  
 
1032
  ret = setuid(uid);
 
1033
  if(ret == -1){
 
1034
    perror("setuid");
 
1035
  }
 
1036
  
 
1037
  ret = init_gnutls_global(&mc, pubkey, seckey);
1471
1038
  if(ret == -1){
1472
1039
    fprintf(stderr, "init_gnutls_global failed\n");
1473
1040
    exitcode = EXIT_FAILURE;
1476
1043
    gnutls_initialized = true;
1477
1044
  }
1478
1045
  
1479
 
  if(quit_now){
1480
 
    goto end;
1481
 
  }
1482
 
  
1483
 
  tempdir_created = true;
1484
1046
  if(mkdtemp(tempdir) == NULL){
1485
 
    tempdir_created = false;
1486
1047
    perror("mkdtemp");
1487
1048
    goto end;
1488
1049
  }
1489
 
  
1490
 
  if(quit_now){
1491
 
    goto end;
1492
 
  }
1493
 
  
1494
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
1050
  tempdir_created = true;
 
1051
  
 
1052
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
1495
1053
    fprintf(stderr, "init_gpgme failed\n");
1496
1054
    exitcode = EXIT_FAILURE;
1497
1055
    goto end;
1499
1057
    gpgme_initialized = true;
1500
1058
  }
1501
1059
  
1502
 
  if(quit_now){
 
1060
  if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1061
  if(if_index == 0){
 
1062
    fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1063
    exitcode = EXIT_FAILURE;
1503
1064
    goto end;
1504
1065
  }
1505
1066
  
1512
1073
      exitcode = EXIT_FAILURE;
1513
1074
      goto end;
1514
1075
    }
1515
 
    
1516
 
    if(quit_now){
1517
 
      goto end;
1518
 
    }
1519
 
    
1520
1076
    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){
 
1077
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
 
1078
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
 
1079
       or address[numchars+1] != '\0'){
1525
1080
      fprintf(stderr, "Bad port number\n");
1526
1081
      exitcode = EXIT_FAILURE;
1527
1082
      goto end;
1528
1083
    }
1529
 
  
1530
 
    if(quit_now){
1531
 
      goto end;
1532
 
    }
1533
 
    
1534
1084
    port = (uint16_t)tmpmax;
1535
1085
    *address = '\0';
1536
1086
    address = connect_to;
1537
 
    /* Colon in address indicates IPv6 */
1538
 
    int af;
1539
 
    if(strchr(address, ':') != NULL){
1540
 
      af = AF_INET6;
1541
 
    } else {
1542
 
      af = AF_INET;
1543
 
    }
1544
 
    
1545
 
    if(quit_now){
1546
 
      goto end;
1547
 
    }
1548
 
    
1549
 
    ret = start_mandos_communication(address, port, if_index, af);
 
1087
    ret = start_mandos_communication(address, port, if_index, &mc);
1550
1088
    if(ret < 0){
1551
1089
      exitcode = EXIT_FAILURE;
1552
1090
    } else {
1555
1093
    goto end;
1556
1094
  }
1557
1095
  
1558
 
  if(quit_now){
 
1096
  if(not debug){
 
1097
    avahi_set_log_function(empty_log);
 
1098
  }
 
1099
  
 
1100
  /* Initialize the pseudo-RNG for Avahi */
 
1101
  srand((unsigned int) time(NULL));
 
1102
  
 
1103
  /* Allocate main Avahi loop object */
 
1104
  mc.simple_poll = avahi_simple_poll_new();
 
1105
  if(mc.simple_poll == NULL){
 
1106
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1107
    exitcode = EXIT_FAILURE;
1559
1108
    goto end;
1560
1109
  }
1561
1110
  
1585
1134
    goto end;
1586
1135
  }
1587
1136
  
1588
 
  if(quit_now){
1589
 
    goto end;
1590
 
  }
1591
 
  
1592
1137
  /* Create the Avahi service browser */
1593
1138
  sb = avahi_s_service_browser_new(mc.server, if_index,
1594
 
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1595
 
                                   NULL, 0, browse_callback, NULL);
 
1139
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
 
1140
                                   NULL, 0, browse_callback, &mc);
1596
1141
  if(sb == NULL){
1597
1142
    fprintf(stderr, "Failed to create service browser: %s\n",
1598
1143
            avahi_strerror(avahi_server_errno(mc.server)));
1600
1145
    goto end;
1601
1146
  }
1602
1147
  
1603
 
  if(quit_now){
1604
 
    goto end;
1605
 
  }
1606
 
  
1607
1148
  /* Run the main loop */
1608
1149
  
1609
1150
  if(debug){
1638
1179
    gpgme_release(mc.ctx);
1639
1180
  }
1640
1181
  
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
1182
  /* Removes the temp directory used by GPGME */
1674
1183
  if(tempdir_created){
1675
1184
    DIR *d;
1714
1223
    }
1715
1224
  }
1716
1225
  
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
1226
  return exitcode;
1737
1227
}