/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: teddy at bsnet
  • Date: 2010-08-11 20:06:18 UTC
  • mto: This revision was merged to the branch mainline in revision 419.
  • Revision ID: teddy@fukt.bsnet.se-20100811200618-1uuv7p6cmrb2cmxu
* plugins.d/mandos-client.c: Added debug output.

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
33
34
#define _LARGEFILE_SOURCE
 
35
#endif
 
36
#ifndef _FILE_OFFSET_BITS
34
37
#define _FILE_OFFSET_BITS 64
 
38
#endif
35
39
 
36
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
37
41
 
38
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
39
 
                                   stdout, ferror(), sscanf(),
40
 
                                   remove() */
 
43
                                   stdout, ferror(), remove() */
41
44
#include <stdint.h>             /* uint16_t, uint32_t */
42
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
43
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
44
 
                                   srand() */
45
 
#include <stdbool.h>            /* bool, true */
 
47
                                   srand(), strtof(), abort() */
 
48
#include <stdbool.h>            /* bool, false, true */
46
49
#include <string.h>             /* memset(), strcmp(), strlen(),
47
50
                                   strerror(), asprintf(), strcpy() */
48
 
#include <sys/ioctl.h>          /* ioctl */
 
51
#include <sys/ioctl.h>          /* ioctl */
49
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
50
53
                                   sockaddr_in6, PF_INET6,
51
 
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
52
 
                                   uid_t, gid_t, open(), opendir(),
53
 
                                   DIR */
 
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
 
55
                                   opendir(), DIR */
54
56
#include <sys/stat.h>           /* open() */
55
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
56
 
                                   struct in6_addr, inet_pton(),
57
 
                                   connect() */
 
58
                                   inet_pton(), connect() */
58
59
#include <fcntl.h>              /* open() */
59
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
60
61
                                 */
61
 
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
 
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
 
63
                                   strtoimax() */
62
64
#include <assert.h>             /* assert() */
63
65
#include <errno.h>              /* perror(), errno */
64
66
#include <time.h>               /* nanosleep(), time() */
65
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
66
68
                                   SIOCSIFFLAGS, if_indextoname(),
67
69
                                   if_nametoindex(), IF_NAMESIZE */
68
 
#include <netinet/in.h>
 
70
#include <netinet/in.h>         /* IN6_IS_ADDR_LINKLOCAL,
 
71
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
 
72
                                */
69
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
70
 
                                   getuid(), getgid(), setuid(),
71
 
                                   setgid() */
 
74
                                   getuid(), getgid(), seteuid(),
 
75
                                   setgid(), pause() */
72
76
#include <arpa/inet.h>          /* inet_pton(), htons */
73
 
#include <iso646.h>             /* not, and, or */
 
77
#include <iso646.h>             /* not, or, and */
74
78
#include <argp.h>               /* struct argp_option, error_t, struct
75
79
                                   argp_state, struct argp,
76
80
                                   argp_parse(), ARGP_KEY_ARG,
77
81
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
82
#include <signal.h>             /* sigemptyset(), sigaddset(),
 
83
                                   sigaction(), SIGTERM, sig_atomic_t,
 
84
                                   raise() */
 
85
 
78
86
#ifdef __linux__
79
87
#include <sys/klog.h>           /* klogctl() */
80
 
#endif
 
88
#endif  /* __linux__ */
81
89
 
82
90
/* Avahi */
83
91
/* All Avahi types, constants and functions
117
125
static const char mandos_protocol_version[] = "1";
118
126
const char *argp_program_version = "mandos-client " VERSION;
119
127
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;
120
130
 
121
131
/* Used for passing in values through the Avahi callback functions */
122
132
typedef struct {
129
139
  gpgme_ctx_t ctx;
130
140
} mandos_context;
131
141
 
 
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
 
132
150
/*
133
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
134
 
 * "buffer_capacity" is how much is currently allocated,
 
151
 * Make additional room in "buffer" for at least BUFFER_SIZE more
 
152
 * bytes. "buffer_capacity" is how much is currently allocated,
135
153
 * "buffer_length" is how much is already used.
136
154
 */
137
 
size_t adjustbuffer(char **buffer, size_t buffer_length,
 
155
size_t incbuffer(char **buffer, size_t buffer_length,
138
156
                  size_t buffer_capacity){
139
157
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
140
158
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
149
167
/* 
150
168
 * Initialize GPGME.
151
169
 */
152
 
static bool init_gpgme(mandos_context *mc, const char *seckey,
 
170
static bool init_gpgme(const char *seckey,
153
171
                       const char *pubkey, const char *tempdir){
154
 
  int ret;
155
172
  gpgme_error_t rc;
156
173
  gpgme_engine_info_t engine_info;
157
174
  
160
177
   * Helper function to insert pub and seckey to the engine keyring.
161
178
   */
162
179
  bool import_key(const char *filename){
 
180
    int ret;
163
181
    int fd;
164
182
    gpgme_data_t pgp_data;
165
183
    
176
194
      return false;
177
195
    }
178
196
    
179
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
197
    rc = gpgme_op_import(mc.ctx, pgp_data);
180
198
    if(rc != GPG_ERR_NO_ERROR){
181
199
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
182
200
              gpgme_strsource(rc), gpgme_strerror(rc));
192
210
  }
193
211
  
194
212
  if(debug){
195
 
    fprintf(stderr, "Initialize gpgme\n");
 
213
    fprintf(stderr, "Initializing GPGME\n");
196
214
  }
197
215
  
198
216
  /* Init GPGME */
225
243
  }
226
244
  
227
245
  /* Create new GPGME "context" */
228
 
  rc = gpgme_new(&(mc->ctx));
 
246
  rc = gpgme_new(&(mc.ctx));
229
247
  if(rc != GPG_ERR_NO_ERROR){
230
248
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
231
249
            gpgme_strsource(rc), gpgme_strerror(rc));
236
254
    return false;
237
255
  }
238
256
  
239
 
  return true; 
 
257
  return true;
240
258
}
241
259
 
242
260
/* 
243
261
 * Decrypt OpenPGP data.
244
262
 * Returns -1 on error
245
263
 */
246
 
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
247
 
                                  const char *cryptotext,
 
264
static ssize_t pgp_packet_decrypt(const char *cryptotext,
248
265
                                  size_t crypto_size,
249
266
                                  char **plaintext){
250
267
  gpgme_data_t dh_crypto, dh_plain;
277
294
  
278
295
  /* Decrypt data from the cryptotext data buffer to the plaintext
279
296
     data buffer */
280
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
297
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
281
298
  if(rc != GPG_ERR_NO_ERROR){
282
299
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
283
300
            gpgme_strsource(rc), gpgme_strerror(rc));
284
301
    plaintext_length = -1;
285
302
    if(debug){
286
303
      gpgme_decrypt_result_t result;
287
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
304
      result = gpgme_op_decrypt_result(mc.ctx);
288
305
      if(result == NULL){
289
306
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
290
307
      } else {
297
314
        }
298
315
        gpgme_recipient_t recipient;
299
316
        recipient = result->recipients;
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
 
          }
 
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;
310
325
        }
311
326
      }
312
327
    }
326
341
  
327
342
  *plaintext = NULL;
328
343
  while(true){
329
 
    plaintext_capacity = adjustbuffer(plaintext,
 
344
    plaintext_capacity = incbuffer(plaintext,
330
345
                                      (size_t)plaintext_length,
331
346
                                      plaintext_capacity);
332
347
    if(plaintext_capacity == 0){
333
 
        perror("adjustbuffer");
 
348
        perror("incbuffer");
334
349
        plaintext_length = -1;
335
350
        goto decrypt_end;
336
351
    }
382
397
  fprintf(stderr, "GnuTLS: %s", string);
383
398
}
384
399
 
385
 
static int init_gnutls_global(mandos_context *mc,
386
 
                              const char *pubkeyfilename,
 
400
static int init_gnutls_global(const char *pubkeyfilename,
387
401
                              const char *seckeyfilename){
388
402
  int ret;
389
403
  
407
421
  }
408
422
  
409
423
  /* OpenPGP credentials */
410
 
  gnutls_certificate_allocate_credentials(&mc->cred);
 
424
  gnutls_certificate_allocate_credentials(&mc.cred);
411
425
  if(ret != GNUTLS_E_SUCCESS){
412
426
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
413
 
                                                  * from
414
 
                                                  * -Wunreachable-code
415
 
                                                  */
 
427
                                                    from
 
428
                                                    -Wunreachable-code
 
429
                                                 */
416
430
            safer_gnutls_strerror(ret));
417
431
    gnutls_global_deinit();
418
432
    return -1;
425
439
  }
426
440
  
427
441
  ret = gnutls_certificate_set_openpgp_key_file
428
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
442
    (mc.cred, pubkeyfilename, seckeyfilename,
429
443
     GNUTLS_OPENPGP_FMT_BASE64);
430
444
  if(ret != GNUTLS_E_SUCCESS){
431
445
    fprintf(stderr,
437
451
  }
438
452
  
439
453
  /* GnuTLS server initialization */
440
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
454
  ret = gnutls_dh_params_init(&mc.dh_params);
441
455
  if(ret != GNUTLS_E_SUCCESS){
442
456
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
443
457
            " %s\n", safer_gnutls_strerror(ret));
444
458
    goto globalfail;
445
459
  }
446
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
460
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
447
461
  if(ret != GNUTLS_E_SUCCESS){
448
462
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
449
463
            safer_gnutls_strerror(ret));
450
464
    goto globalfail;
451
465
  }
452
466
  
453
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
467
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
454
468
  
455
469
  return 0;
456
470
  
457
471
 globalfail:
458
472
  
459
 
  gnutls_certificate_free_credentials(mc->cred);
 
473
  gnutls_certificate_free_credentials(mc.cred);
460
474
  gnutls_global_deinit();
461
 
  gnutls_dh_params_deinit(mc->dh_params);
 
475
  gnutls_dh_params_deinit(mc.dh_params);
462
476
  return -1;
463
477
}
464
478
 
465
 
static int init_gnutls_session(mandos_context *mc,
466
 
                               gnutls_session_t *session){
 
479
static int init_gnutls_session(gnutls_session_t *session){
467
480
  int ret;
468
481
  /* GnuTLS session creation */
469
 
  ret = gnutls_init(session, GNUTLS_SERVER);
 
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);
470
488
  if(ret != GNUTLS_E_SUCCESS){
471
489
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
472
490
            safer_gnutls_strerror(ret));
474
492
  
475
493
  {
476
494
    const char *err;
477
 
    ret = gnutls_priority_set_direct(*session, mc->priority, &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);
478
502
    if(ret != GNUTLS_E_SUCCESS){
479
503
      fprintf(stderr, "Syntax error at: %s\n", err);
480
504
      fprintf(stderr, "GnuTLS error: %s\n",
484
508
    }
485
509
  }
486
510
  
487
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
488
 
                               mc->cred);
 
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);
489
519
  if(ret != GNUTLS_E_SUCCESS){
490
520
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
491
521
            safer_gnutls_strerror(ret));
494
524
  }
495
525
  
496
526
  /* ignore client certificate if any. */
497
 
  gnutls_certificate_server_set_request(*session,
498
 
                                        GNUTLS_CERT_IGNORE);
 
527
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
499
528
  
500
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
529
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
501
530
  
502
531
  return 0;
503
532
}
509
538
/* Called when a Mandos server is found */
510
539
static int start_mandos_communication(const char *ip, uint16_t port,
511
540
                                      AvahiIfIndex if_index,
512
 
                                      mandos_context *mc){
513
 
  int ret, tcp_sd;
 
541
                                      int af){
 
542
  int ret, tcp_sd = -1;
514
543
  ssize_t sret;
515
 
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
 
544
  union {
 
545
    struct sockaddr_in in;
 
546
    struct sockaddr_in6 in6;
 
547
  } to;
516
548
  char *buffer = NULL;
517
 
  char *decrypted_buffer;
 
549
  char *decrypted_buffer = NULL;
518
550
  size_t buffer_length = 0;
519
551
  size_t buffer_capacity = 0;
520
 
  ssize_t decrypted_buffer_size;
521
552
  size_t written;
522
 
  int retval = 0;
523
 
  char interface[IF_NAMESIZE];
 
553
  int retval = -1;
524
554
  gnutls_session_t session;
525
 
  
526
 
  ret = init_gnutls_session(mc, &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);
527
574
  if(ret != 0){
528
575
    return -1;
529
576
  }
530
577
  
531
578
  if(debug){
532
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
579
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
533
580
            "\n", ip, port);
534
581
  }
535
582
  
536
 
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
 
583
  tcp_sd = socket(pf, SOCK_STREAM, 0);
537
584
  if(tcp_sd < 0){
538
585
    perror("socket");
539
 
    return -1;
 
586
    goto mandos_end;
540
587
  }
541
588
  
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);
 
589
  if(quit_now){
 
590
    goto mandos_end;
548
591
  }
549
592
  
550
593
  memset(&to, 0, sizeof(to));
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);
 
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
  }
555
601
  if(ret < 0 ){
556
602
    perror("inet_pton");
557
 
    return -1;
 
603
    goto mandos_end;
558
604
  }
559
605
  if(ret == 0){
560
606
    fprintf(stderr, "Bad address: %s\n", ip);
561
 
    return -1;
 
607
    goto mandos_end;
562
608
  }
563
 
  to.in6.sin6_port = htons(port); /* Spurious warnings from
 
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
564
627
                                     -Wconversion and
565
628
                                     -Wunreachable-code */
 
629
  }
566
630
  
567
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
631
  if(quit_now){
 
632
    goto mandos_end;
 
633
  }
568
634
  
569
635
  if(debug){
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){
 
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){
575
659
      perror("inet_ntop");
576
660
    } else {
577
661
      if(strcmp(addrstr, ip) != 0){
580
664
    }
581
665
  }
582
666
  
583
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
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
  }
584
676
  if(ret < 0){
585
677
    perror("connect");
586
 
    return -1;
 
678
    goto mandos_end;
 
679
  }
 
680
  
 
681
  if(quit_now){
 
682
    goto mandos_end;
587
683
  }
588
684
  
589
685
  const char *out = mandos_protocol_version;
594
690
                                   out_size - written));
595
691
    if(ret == -1){
596
692
      perror("write");
597
 
      retval = -1;
598
693
      goto mandos_end;
599
694
    }
600
695
    written += (size_t)ret;
608
703
        break;
609
704
      }
610
705
    }
 
706
  
 
707
    if(quit_now){
 
708
      goto mandos_end;
 
709
    }
611
710
  }
612
711
  
613
712
  if(debug){
614
713
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
615
714
  }
616
715
  
 
716
  if(quit_now){
 
717
    goto mandos_end;
 
718
  }
 
719
  
617
720
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
618
721
  
619
 
  do{
 
722
  if(quit_now){
 
723
    goto mandos_end;
 
724
  }
 
725
  
 
726
  do {
620
727
    ret = gnutls_handshake(session);
 
728
    if(quit_now){
 
729
      goto mandos_end;
 
730
    }
621
731
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
622
732
  
623
733
  if(ret != GNUTLS_E_SUCCESS){
625
735
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
626
736
      gnutls_perror(ret);
627
737
    }
628
 
    retval = -1;
629
738
    goto mandos_end;
630
739
  }
631
740
  
632
741
  /* Read OpenPGP packet that contains the wanted password */
633
742
  
634
743
  if(debug){
635
 
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
 
744
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
636
745
            ip);
637
746
  }
638
747
  
639
748
  while(true){
640
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
 
749
    
 
750
    if(quit_now){
 
751
      goto mandos_end;
 
752
    }
 
753
    
 
754
    buffer_capacity = incbuffer(&buffer, buffer_length,
641
755
                                   buffer_capacity);
642
756
    if(buffer_capacity == 0){
643
 
      perror("adjustbuffer");
644
 
      retval = -1;
 
757
      perror("incbuffer");
 
758
      goto mandos_end;
 
759
    }
 
760
    
 
761
    if(quit_now){
645
762
      goto mandos_end;
646
763
    }
647
764
    
656
773
      case GNUTLS_E_AGAIN:
657
774
        break;
658
775
      case GNUTLS_E_REHANDSHAKE:
659
 
        do{
 
776
        do {
660
777
          ret = gnutls_handshake(session);
 
778
          
 
779
          if(quit_now){
 
780
            goto mandos_end;
 
781
          }
661
782
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
662
783
        if(ret < 0){
663
784
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
664
785
          gnutls_perror(ret);
665
 
          retval = -1;
666
786
          goto mandos_end;
667
787
        }
668
788
        break;
669
789
      default:
670
790
        fprintf(stderr, "Unknown error while reading data from"
671
791
                " encrypted session with Mandos server\n");
672
 
        retval = -1;
673
792
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
674
793
        goto mandos_end;
675
794
      }
682
801
    fprintf(stderr, "Closing TLS session\n");
683
802
  }
684
803
  
685
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
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);
686
814
  
687
815
  if(buffer_length > 0){
688
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
 
816
    ssize_t decrypted_buffer_size;
 
817
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
689
818
                                               buffer_length,
690
819
                                               &decrypted_buffer);
691
820
    if(decrypted_buffer_size >= 0){
 
821
      
692
822
      written = 0;
693
823
      while(written < (size_t) decrypted_buffer_size){
 
824
        if(quit_now){
 
825
          goto mandos_end;
 
826
        }
 
827
        
694
828
        ret = (int)fwrite(decrypted_buffer + written, 1,
695
829
                          (size_t)decrypted_buffer_size - written,
696
830
                          stdout);
699
833
            fprintf(stderr, "Error writing encrypted data: %s\n",
700
834
                    strerror(errno));
701
835
          }
702
 
          retval = -1;
703
 
          break;
 
836
          goto mandos_end;
704
837
        }
705
838
        written += (size_t)ret;
706
839
      }
707
 
      free(decrypted_buffer);
708
 
    } else {
709
 
      retval = -1;
 
840
      retval = 0;
710
841
    }
711
 
  } else {
712
 
    retval = -1;
713
842
  }
714
843
  
715
844
  /* Shutdown procedure */
716
845
  
717
846
 mandos_end:
 
847
  free(decrypted_buffer);
718
848
  free(buffer);
719
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
849
  if(tcp_sd >= 0){
 
850
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
851
  }
720
852
  if(ret == -1){
721
853
    perror("close");
722
854
  }
723
855
  gnutls_deinit(session);
 
856
  if(quit_now){
 
857
    retval = -1;
 
858
  }
724
859
  return retval;
725
860
}
726
861
 
727
862
static void resolve_callback(AvahiSServiceResolver *r,
728
863
                             AvahiIfIndex interface,
729
 
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
864
                             AvahiProtocol proto,
730
865
                             AvahiResolverEvent event,
731
866
                             const char *name,
732
867
                             const char *type,
737
872
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
738
873
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
739
874
                             flags,
740
 
                             void* userdata){
741
 
  mandos_context *mc = userdata;
 
875
                             AVAHI_GCC_UNUSED void* userdata){
742
876
  assert(r);
743
877
  
744
878
  /* Called whenever a service has been resolved successfully or
745
879
     timed out */
746
880
  
 
881
  if(quit_now){
 
882
    return;
 
883
  }
 
884
  
747
885
  switch(event){
748
886
  default:
749
887
  case AVAHI_RESOLVER_FAILURE:
750
888
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
751
889
            " of type '%s' in domain '%s': %s\n", name, type, domain,
752
 
            avahi_strerror(avahi_server_errno(mc->server)));
 
890
            avahi_strerror(avahi_server_errno(mc.server)));
753
891
    break;
754
892
    
755
893
  case AVAHI_RESOLVER_FOUND:
761
899
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
762
900
                ip, (intmax_t)interface, port);
763
901
      }
764
 
      int ret = start_mandos_communication(ip, port, interface, mc);
 
902
      int ret = start_mandos_communication(ip, port, interface,
 
903
                                           avahi_proto_to_af(proto));
765
904
      if(ret == 0){
766
 
        avahi_simple_poll_quit(mc->simple_poll);
 
905
        avahi_simple_poll_quit(mc.simple_poll);
767
906
      }
768
907
    }
769
908
  }
779
918
                            const char *domain,
780
919
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
781
920
                            flags,
782
 
                            void* userdata){
783
 
  mandos_context *mc = userdata;
 
921
                            AVAHI_GCC_UNUSED void* userdata){
784
922
  assert(b);
785
923
  
786
924
  /* Called whenever a new services becomes available on the LAN or
787
925
     is removed from the LAN */
788
926
  
 
927
  if(quit_now){
 
928
    return;
 
929
  }
 
930
  
789
931
  switch(event){
790
932
  default:
791
933
  case AVAHI_BROWSER_FAILURE:
792
934
    
793
935
    fprintf(stderr, "(Avahi browser) %s\n",
794
 
            avahi_strerror(avahi_server_errno(mc->server)));
795
 
    avahi_simple_poll_quit(mc->simple_poll);
 
936
            avahi_strerror(avahi_server_errno(mc.server)));
 
937
    avahi_simple_poll_quit(mc.simple_poll);
796
938
    return;
797
939
    
798
940
  case AVAHI_BROWSER_NEW:
801
943
       the callback function is called the Avahi server will free the
802
944
       resolver for us. */
803
945
    
804
 
    if(!(avahi_s_service_resolver_new(mc->server, interface,
805
 
                                       protocol, name, type, domain,
806
 
                                       AVAHI_PROTO_INET6, 0,
807
 
                                       resolve_callback, mc)))
 
946
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
947
                                    name, type, domain, protocol, 0,
 
948
                                    resolve_callback, NULL) == NULL)
808
949
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
809
 
              name, avahi_strerror(avahi_server_errno(mc->server)));
 
950
              name, avahi_strerror(avahi_server_errno(mc.server)));
810
951
    break;
811
952
    
812
953
  case AVAHI_BROWSER_REMOVE:
821
962
  }
822
963
}
823
964
 
 
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
 
824
1074
int main(int argc, char *argv[]){
825
1075
  AvahiSServiceBrowser *sb = NULL;
826
1076
  int error;
827
1077
  int ret;
828
1078
  intmax_t tmpmax;
829
 
  int numchars;
 
1079
  char *tmp;
830
1080
  int exitcode = EXIT_SUCCESS;
831
 
  const char *interface = "eth0";
 
1081
  const char *interface = "";
832
1082
  struct ifreq network;
833
 
  int sd;
 
1083
  int sd = -1;
 
1084
  bool take_down_interface = false;
834
1085
  uid_t uid;
835
1086
  gid_t gid;
836
 
  char *connect_to = NULL;
837
1087
  char tempdir[] = "/tmp/mandosXXXXXX";
838
1088
  bool tempdir_created = false;
839
1089
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
840
1090
  const char *seckey = PATHDIR "/" SECKEY;
841
1091
  const char *pubkey = PATHDIR "/" PUBKEY;
842
1092
  
843
 
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
844
 
                        .dh_bits = 1024, .priority = "SECURE256"
845
 
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
846
1093
  bool gnutls_initialized = false;
847
1094
  bool gpgme_initialized = false;
848
 
  double delay = 2.5;
 
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
  }
849
1120
  
850
1121
  {
851
1122
    struct argp_option options[] = {
857
1128
        .group = 1 },
858
1129
      { .name = "interface", .key = 'i',
859
1130
        .arg = "NAME",
860
 
        .doc = "Interface that will be used to search for Mandos"
861
 
        " servers",
 
1131
        .doc = "Network interface that will be used to search for"
 
1132
        " Mandos servers",
862
1133
        .group = 1 },
863
1134
      { .name = "seckey", .key = 's',
864
1135
        .arg = "FILE",
903
1174
        pubkey = arg;
904
1175
        break;
905
1176
      case 129:                 /* --dh-bits */
906
 
        ret = sscanf(arg, "%" SCNdMAX "%n", &tmpmax, &numchars);
907
 
        if(ret < 1 or tmpmax != (typeof(mc.dh_bits))tmpmax
908
 
           or arg[numchars] != '\0'){
 
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){
909
1181
          fprintf(stderr, "Bad number of DH bits\n");
910
1182
          exit(EXIT_FAILURE);
911
1183
        }
915
1187
        mc.priority = arg;
916
1188
        break;
917
1189
      case 131:                 /* --delay */
918
 
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
919
 
        if(ret < 1 or arg[numchars] != '\0'){
 
1190
        errno = 0;
 
1191
        delay = strtof(arg, &tmp);
 
1192
        if(errno != 0 or tmp == arg or *tmp != '\0'){
920
1193
          fprintf(stderr, "Bad delay\n");
921
1194
          exit(EXIT_FAILURE);
922
1195
        }
943
1216
    }
944
1217
  }
945
1218
  
 
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
  
946
1322
  /* If the interface is down, bring it up */
947
 
  {
 
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
    
948
1342
#ifdef __linux__
949
1343
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
950
1344
       messages to mess up the prompt */
951
1345
    ret = klogctl(8, NULL, 5);
 
1346
    bool restore_loglevel = true;
952
1347
    if(ret == -1){
 
1348
      restore_loglevel = false;
953
1349
      perror("klogctl");
954
1350
    }
955
 
#endif
 
1351
#endif  /* __linux__ */
956
1352
    
957
1353
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
958
1354
    if(sd < 0){
959
1355
      perror("socket");
960
1356
      exitcode = EXIT_FAILURE;
961
1357
#ifdef __linux__
962
 
      ret = klogctl(7, NULL, 0);
 
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);
963
1368
      if(ret == -1){
964
 
        perror("klogctl");
 
1369
        perror("seteuid");
965
1370
      }
966
 
#endif
967
1371
      goto end;
968
1372
    }
969
1373
    strcpy(network.ifr_name, interface);
971
1375
    if(ret == -1){
972
1376
      perror("ioctl SIOCGIFFLAGS");
973
1377
#ifdef __linux__
974
 
      ret = klogctl(7, NULL, 0);
 
1378
      if(restore_loglevel){
 
1379
        ret = klogctl(7, NULL, 0);
 
1380
        if(ret == -1){
 
1381
          perror("klogctl");
 
1382
        }
 
1383
      }
 
1384
#endif  /* __linux__ */
 
1385
      exitcode = EXIT_FAILURE;
 
1386
      /* Lower privileges */
 
1387
      errno = 0;
 
1388
      ret = seteuid(uid);
975
1389
      if(ret == -1){
976
 
        perror("klogctl");
 
1390
        perror("seteuid");
977
1391
      }
978
 
#endif
979
 
      exitcode = EXIT_FAILURE;
980
1392
      goto end;
981
1393
    }
982
1394
    if((network.ifr_flags & IFF_UP) == 0){
983
1395
      network.ifr_flags |= IFF_UP;
 
1396
      take_down_interface = true;
984
1397
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
985
1398
      if(ret == -1){
986
 
        perror("ioctl SIOCSIFFLAGS");
 
1399
        take_down_interface = false;
 
1400
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
987
1401
        exitcode = EXIT_FAILURE;
988
1402
#ifdef __linux__
989
 
        ret = klogctl(7, NULL, 0);
 
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);
990
1413
        if(ret == -1){
991
 
          perror("klogctl");
 
1414
          perror("seteuid");
992
1415
        }
993
 
#endif
994
1416
        goto end;
995
1417
      }
996
1418
    }
1008
1430
        perror("nanosleep");
1009
1431
      }
1010
1432
    }
1011
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1012
 
    if(ret == -1){
1013
 
      perror("close");
 
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
      }
1014
1439
    }
1015
1440
#ifdef __linux__
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);
 
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);
1038
1471
  if(ret == -1){
1039
1472
    fprintf(stderr, "init_gnutls_global failed\n");
1040
1473
    exitcode = EXIT_FAILURE;
1043
1476
    gnutls_initialized = true;
1044
1477
  }
1045
1478
  
 
1479
  if(quit_now){
 
1480
    goto end;
 
1481
  }
 
1482
  
 
1483
  tempdir_created = true;
1046
1484
  if(mkdtemp(tempdir) == NULL){
 
1485
    tempdir_created = false;
1047
1486
    perror("mkdtemp");
1048
1487
    goto end;
1049
1488
  }
1050
 
  tempdir_created = true;
1051
 
  
1052
 
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
 
1489
  
 
1490
  if(quit_now){
 
1491
    goto end;
 
1492
  }
 
1493
  
 
1494
  if(not init_gpgme(pubkey, seckey, tempdir)){
1053
1495
    fprintf(stderr, "init_gpgme failed\n");
1054
1496
    exitcode = EXIT_FAILURE;
1055
1497
    goto end;
1057
1499
    gpgme_initialized = true;
1058
1500
  }
1059
1501
  
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;
 
1502
  if(quit_now){
1064
1503
    goto end;
1065
1504
  }
1066
1505
  
1073
1512
      exitcode = EXIT_FAILURE;
1074
1513
      goto end;
1075
1514
    }
 
1515
    
 
1516
    if(quit_now){
 
1517
      goto end;
 
1518
    }
 
1519
    
1076
1520
    uint16_t port;
1077
 
    ret = sscanf(address+1, "%" SCNdMAX "%n", &tmpmax, &numchars);
1078
 
    if(ret < 1 or tmpmax != (uint16_t)tmpmax
1079
 
       or address[numchars+1] != '\0'){
 
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){
1080
1525
      fprintf(stderr, "Bad port number\n");
1081
1526
      exitcode = EXIT_FAILURE;
1082
1527
      goto end;
1083
1528
    }
 
1529
  
 
1530
    if(quit_now){
 
1531
      goto end;
 
1532
    }
 
1533
    
1084
1534
    port = (uint16_t)tmpmax;
1085
1535
    *address = '\0';
1086
1536
    address = connect_to;
1087
 
    ret = start_mandos_communication(address, port, if_index, &mc);
 
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);
1088
1550
    if(ret < 0){
1089
1551
      exitcode = EXIT_FAILURE;
1090
1552
    } else {
1093
1555
    goto end;
1094
1556
  }
1095
1557
  
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;
 
1558
  if(quit_now){
1108
1559
    goto end;
1109
1560
  }
1110
1561
  
1134
1585
    goto end;
1135
1586
  }
1136
1587
  
 
1588
  if(quit_now){
 
1589
    goto end;
 
1590
  }
 
1591
  
1137
1592
  /* Create the Avahi service browser */
1138
1593
  sb = avahi_s_service_browser_new(mc.server, if_index,
1139
 
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
1140
 
                                   NULL, 0, browse_callback, &mc);
 
1594
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
 
1595
                                   NULL, 0, browse_callback, NULL);
1141
1596
  if(sb == NULL){
1142
1597
    fprintf(stderr, "Failed to create service browser: %s\n",
1143
1598
            avahi_strerror(avahi_server_errno(mc.server)));
1145
1600
    goto end;
1146
1601
  }
1147
1602
  
 
1603
  if(quit_now){
 
1604
    goto end;
 
1605
  }
 
1606
  
1148
1607
  /* Run the main loop */
1149
1608
  
1150
1609
  if(debug){
1179
1638
    gpgme_release(mc.ctx);
1180
1639
  }
1181
1640
  
 
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
  
1182
1673
  /* Removes the temp directory used by GPGME */
1183
1674
  if(tempdir_created){
1184
1675
    DIR *d;
1223
1714
    }
1224
1715
  }
1225
1716
  
 
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
  
1226
1736
  return exitcode;
1227
1737
}