/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 Hogeborn
  • Date: 2009-09-16 23:28:39 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090916232839-3o7i8qmcdcz5j1ya
* init.d-mandos (Required-Start, Required-Stop): Bug fix: Added
                 "$syslog", thanks to Petter Reinholdtsen
                 <pere@hungry.com> (Debian bug #546928).

* initramfs-tools-script: Removed erroneous comment.

* plugins.d/askpass-fifo.c: Removed TEMP_FAILURE_RETRY since it is
                            not needed.

* plugins.d/mandos-client.c (main): Bug fix: Initialize
                                    "old_sigterm_action".

* plugins.d/splashy.c (main): Bug fix: really check return value from
                              "sigaddset".  Fix some warnings on
                              64-bit systems.

* plugins.d/usplash.c (termination_handler, main): Save received
                                                   signal and
                                                   re-raise it on
                                                   exit.
  (usplash_write): Do not close FIFO, instead, take an additional file
                   descriptor pointer to it and open only when needed
                   (all callers changed).  Abort immediately on EINTR.
                   Bug fix:  Add NUL byte on single-word commands.
                   Ignore "interrupted_by_signal".
  (makeprompt, find_usplash): New; broken out from "main()".
  (find_usplash): Bug fix: close /proc/<pid>/cmdline FD on error.
  (main): Reorganized to jump to a new "failure" label on any error.
          Bug fix: check return values from sigaddset.
          New variable "usplash_accessed" to flag if usplash(8) needs
          to be killed and restarted.  Removed the "an_error_occured"
          variable.

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() */
 
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(),
 
74
                                   getuid(), getgid(), seteuid(),
71
75
                                   setgid() */
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
129
137
  gpgme_ctx_t ctx;
130
138
} mandos_context;
131
139
 
 
140
/* global context so signal handler can reach it*/
 
141
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
142
                      .dh_bits = 1024, .priority = "SECURE256"
 
143
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
144
 
132
145
/*
133
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
134
 
 * "buffer_capacity" is how much is currently allocated,
 
146
 * Make additional room in "buffer" for at least BUFFER_SIZE more
 
147
 * bytes. "buffer_capacity" is how much is currently allocated,
135
148
 * "buffer_length" is how much is already used.
136
149
 */
137
 
size_t adjustbuffer(char **buffer, size_t buffer_length,
 
150
size_t incbuffer(char **buffer, size_t buffer_length,
138
151
                  size_t buffer_capacity){
139
152
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
140
153
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
149
162
/* 
150
163
 * Initialize GPGME.
151
164
 */
152
 
static bool init_gpgme(mandos_context *mc, const char *seckey,
 
165
static bool init_gpgme(const char *seckey,
153
166
                       const char *pubkey, const char *tempdir){
154
 
  int ret;
155
167
  gpgme_error_t rc;
156
168
  gpgme_engine_info_t engine_info;
157
169
  
160
172
   * Helper function to insert pub and seckey to the engine keyring.
161
173
   */
162
174
  bool import_key(const char *filename){
 
175
    int ret;
163
176
    int fd;
164
177
    gpgme_data_t pgp_data;
165
178
    
176
189
      return false;
177
190
    }
178
191
    
179
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
192
    rc = gpgme_op_import(mc.ctx, pgp_data);
180
193
    if(rc != GPG_ERR_NO_ERROR){
181
194
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
182
195
              gpgme_strsource(rc), gpgme_strerror(rc));
192
205
  }
193
206
  
194
207
  if(debug){
195
 
    fprintf(stderr, "Initialize gpgme\n");
 
208
    fprintf(stderr, "Initializing GPGME\n");
196
209
  }
197
210
  
198
211
  /* Init GPGME */
225
238
  }
226
239
  
227
240
  /* Create new GPGME "context" */
228
 
  rc = gpgme_new(&(mc->ctx));
 
241
  rc = gpgme_new(&(mc.ctx));
229
242
  if(rc != GPG_ERR_NO_ERROR){
230
243
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
231
244
            gpgme_strsource(rc), gpgme_strerror(rc));
236
249
    return false;
237
250
  }
238
251
  
239
 
  return true; 
 
252
  return true;
240
253
}
241
254
 
242
255
/* 
243
256
 * Decrypt OpenPGP data.
244
257
 * Returns -1 on error
245
258
 */
246
 
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
247
 
                                  const char *cryptotext,
 
259
static ssize_t pgp_packet_decrypt(const char *cryptotext,
248
260
                                  size_t crypto_size,
249
261
                                  char **plaintext){
250
262
  gpgme_data_t dh_crypto, dh_plain;
277
289
  
278
290
  /* Decrypt data from the cryptotext data buffer to the plaintext
279
291
     data buffer */
280
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
292
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
281
293
  if(rc != GPG_ERR_NO_ERROR){
282
294
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
283
295
            gpgme_strsource(rc), gpgme_strerror(rc));
284
296
    plaintext_length = -1;
285
297
    if(debug){
286
298
      gpgme_decrypt_result_t result;
287
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
299
      result = gpgme_op_decrypt_result(mc.ctx);
288
300
      if(result == NULL){
289
301
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
290
302
      } else {
297
309
        }
298
310
        gpgme_recipient_t recipient;
299
311
        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
 
          }
 
312
        while(recipient != NULL){
 
313
          fprintf(stderr, "Public key algorithm: %s\n",
 
314
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
315
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
316
          fprintf(stderr, "Secret key available: %s\n",
 
317
                  recipient->status == GPG_ERR_NO_SECKEY
 
318
                  ? "No" : "Yes");
 
319
          recipient = recipient->next;
310
320
        }
311
321
      }
312
322
    }
326
336
  
327
337
  *plaintext = NULL;
328
338
  while(true){
329
 
    plaintext_capacity = adjustbuffer(plaintext,
 
339
    plaintext_capacity = incbuffer(plaintext,
330
340
                                      (size_t)plaintext_length,
331
341
                                      plaintext_capacity);
332
342
    if(plaintext_capacity == 0){
333
 
        perror("adjustbuffer");
 
343
        perror("incbuffer");
334
344
        plaintext_length = -1;
335
345
        goto decrypt_end;
336
346
    }
382
392
  fprintf(stderr, "GnuTLS: %s", string);
383
393
}
384
394
 
385
 
static int init_gnutls_global(mandos_context *mc,
386
 
                              const char *pubkeyfilename,
 
395
static int init_gnutls_global(const char *pubkeyfilename,
387
396
                              const char *seckeyfilename){
388
397
  int ret;
389
398
  
407
416
  }
408
417
  
409
418
  /* OpenPGP credentials */
410
 
  gnutls_certificate_allocate_credentials(&mc->cred);
 
419
  gnutls_certificate_allocate_credentials(&mc.cred);
411
420
  if(ret != GNUTLS_E_SUCCESS){
412
421
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
413
 
                                                  * from
414
 
                                                  * -Wunreachable-code
415
 
                                                  */
 
422
                                                    from
 
423
                                                    -Wunreachable-code
 
424
                                                 */
416
425
            safer_gnutls_strerror(ret));
417
426
    gnutls_global_deinit();
418
427
    return -1;
425
434
  }
426
435
  
427
436
  ret = gnutls_certificate_set_openpgp_key_file
428
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
437
    (mc.cred, pubkeyfilename, seckeyfilename,
429
438
     GNUTLS_OPENPGP_FMT_BASE64);
430
439
  if(ret != GNUTLS_E_SUCCESS){
431
440
    fprintf(stderr,
437
446
  }
438
447
  
439
448
  /* GnuTLS server initialization */
440
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
449
  ret = gnutls_dh_params_init(&mc.dh_params);
441
450
  if(ret != GNUTLS_E_SUCCESS){
442
451
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
443
452
            " %s\n", safer_gnutls_strerror(ret));
444
453
    goto globalfail;
445
454
  }
446
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
455
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
447
456
  if(ret != GNUTLS_E_SUCCESS){
448
457
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
449
458
            safer_gnutls_strerror(ret));
450
459
    goto globalfail;
451
460
  }
452
461
  
453
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
462
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
454
463
  
455
464
  return 0;
456
465
  
457
466
 globalfail:
458
467
  
459
 
  gnutls_certificate_free_credentials(mc->cred);
 
468
  gnutls_certificate_free_credentials(mc.cred);
460
469
  gnutls_global_deinit();
461
 
  gnutls_dh_params_deinit(mc->dh_params);
 
470
  gnutls_dh_params_deinit(mc.dh_params);
462
471
  return -1;
463
472
}
464
473
 
465
 
static int init_gnutls_session(mandos_context *mc,
466
 
                               gnutls_session_t *session){
 
474
static int init_gnutls_session(gnutls_session_t *session){
467
475
  int ret;
468
476
  /* GnuTLS session creation */
469
 
  ret = gnutls_init(session, GNUTLS_SERVER);
 
477
  do {
 
478
    ret = gnutls_init(session, GNUTLS_SERVER);
 
479
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
470
480
  if(ret != GNUTLS_E_SUCCESS){
471
481
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
472
482
            safer_gnutls_strerror(ret));
474
484
  
475
485
  {
476
486
    const char *err;
477
 
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
487
    do {
 
488
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
489
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
478
490
    if(ret != GNUTLS_E_SUCCESS){
479
491
      fprintf(stderr, "Syntax error at: %s\n", err);
480
492
      fprintf(stderr, "GnuTLS error: %s\n",
484
496
    }
485
497
  }
486
498
  
487
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
488
 
                               mc->cred);
 
499
  do {
 
500
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
501
                                 mc.cred);
 
502
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
489
503
  if(ret != GNUTLS_E_SUCCESS){
490
504
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
491
505
            safer_gnutls_strerror(ret));
494
508
  }
495
509
  
496
510
  /* ignore client certificate if any. */
497
 
  gnutls_certificate_server_set_request(*session,
498
 
                                        GNUTLS_CERT_IGNORE);
 
511
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
499
512
  
500
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
513
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
501
514
  
502
515
  return 0;
503
516
}
506
519
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
507
520
                      __attribute__((unused)) const char *txt){}
508
521
 
 
522
sig_atomic_t quit_now = 0;
 
523
int signal_received = 0;
 
524
 
509
525
/* Called when a Mandos server is found */
510
526
static int start_mandos_communication(const char *ip, uint16_t port,
511
527
                                      AvahiIfIndex if_index,
512
 
                                      mandos_context *mc){
513
 
  int ret, tcp_sd;
 
528
                                      int af){
 
529
  int ret, tcp_sd = -1;
514
530
  ssize_t sret;
515
 
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
 
531
  union {
 
532
    struct sockaddr_in in;
 
533
    struct sockaddr_in6 in6;
 
534
  } to;
516
535
  char *buffer = NULL;
517
536
  char *decrypted_buffer;
518
537
  size_t buffer_length = 0;
519
538
  size_t buffer_capacity = 0;
520
 
  ssize_t decrypted_buffer_size;
521
539
  size_t written;
522
540
  int retval = 0;
523
 
  char interface[IF_NAMESIZE];
524
541
  gnutls_session_t session;
525
 
  
526
 
  ret = init_gnutls_session(mc, &session);
 
542
  int pf;                       /* Protocol family */
 
543
  
 
544
  if(quit_now){
 
545
    return -1;
 
546
  }
 
547
  
 
548
  switch(af){
 
549
  case AF_INET6:
 
550
    pf = PF_INET6;
 
551
    break;
 
552
  case AF_INET:
 
553
    pf = PF_INET;
 
554
    break;
 
555
  default:
 
556
    fprintf(stderr, "Bad address family: %d\n", af);
 
557
    return -1;
 
558
  }
 
559
  
 
560
  ret = init_gnutls_session(&session);
527
561
  if(ret != 0){
528
562
    return -1;
529
563
  }
530
564
  
531
565
  if(debug){
532
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
566
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
533
567
            "\n", ip, port);
534
568
  }
535
569
  
536
 
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
 
570
  tcp_sd = socket(pf, SOCK_STREAM, 0);
537
571
  if(tcp_sd < 0){
538
572
    perror("socket");
539
 
    return -1;
 
573
    retval = -1;
 
574
    goto mandos_end;
540
575
  }
541
576
  
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);
 
577
  if(quit_now){
 
578
    goto mandos_end;
548
579
  }
549
580
  
550
581
  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);
 
582
  if(af == AF_INET6){
 
583
    to.in6.sin6_family = (sa_family_t)af;
 
584
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
585
  } else {                      /* IPv4 */
 
586
    to.in.sin_family = (sa_family_t)af;
 
587
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
588
  }
555
589
  if(ret < 0 ){
556
590
    perror("inet_pton");
557
 
    return -1;
 
591
    retval = -1;
 
592
    goto mandos_end;
558
593
  }
559
594
  if(ret == 0){
560
595
    fprintf(stderr, "Bad address: %s\n", ip);
561
 
    return -1;
 
596
    retval = -1;
 
597
    goto mandos_end;
562
598
  }
563
 
  to.in6.sin6_port = htons(port); /* Spurious warnings from
 
599
  if(af == AF_INET6){
 
600
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
601
                                       -Wconversion and
 
602
                                       -Wunreachable-code */
 
603
    
 
604
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
605
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
606
                              -Wunreachable-code*/
 
607
      if(if_index == AVAHI_IF_UNSPEC){
 
608
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
609
                " without a network interface\n");
 
610
        retval = -1;
 
611
        goto mandos_end;
 
612
      }
 
613
      /* Set the network interface number as scope */
 
614
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
615
    }
 
616
  } else {
 
617
    to.in.sin_port = htons(port); /* Spurious warnings from
564
618
                                     -Wconversion and
565
619
                                     -Wunreachable-code */
 
620
  }
566
621
  
567
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
622
  if(quit_now){
 
623
    goto mandos_end;
 
624
  }
568
625
  
569
626
  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){
 
627
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
 
628
      char interface[IF_NAMESIZE];
 
629
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
630
        perror("if_indextoname");
 
631
      } else {
 
632
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
633
                ip, interface, port);
 
634
      }
 
635
    } else {
 
636
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
637
              port);
 
638
    }
 
639
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
 
640
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
641
    const char *pcret;
 
642
    if(af == AF_INET6){
 
643
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
644
                        sizeof(addrstr));
 
645
    } else {
 
646
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
647
                        sizeof(addrstr));
 
648
    }
 
649
    if(pcret == NULL){
575
650
      perror("inet_ntop");
576
651
    } else {
577
652
      if(strcmp(addrstr, ip) != 0){
580
655
    }
581
656
  }
582
657
  
583
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
658
  if(quit_now){
 
659
    goto mandos_end;
 
660
  }
 
661
  
 
662
  if(af == AF_INET6){
 
663
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
664
  } else {
 
665
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
666
  }
584
667
  if(ret < 0){
585
668
    perror("connect");
586
 
    return -1;
 
669
    retval = -1;
 
670
    goto mandos_end;
 
671
  }
 
672
  
 
673
  if(quit_now){
 
674
    goto mandos_end;
587
675
  }
588
676
  
589
677
  const char *out = mandos_protocol_version;
608
696
        break;
609
697
      }
610
698
    }
 
699
  
 
700
    if(quit_now){
 
701
      goto mandos_end;
 
702
    }
611
703
  }
612
704
  
613
705
  if(debug){
614
706
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
615
707
  }
616
708
  
 
709
  if(quit_now){
 
710
    goto mandos_end;
 
711
  }
 
712
  
617
713
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
618
714
  
619
 
  do{
 
715
  if(quit_now){
 
716
    goto mandos_end;
 
717
  }
 
718
  
 
719
  do {
620
720
    ret = gnutls_handshake(session);
 
721
    if(quit_now){
 
722
      goto mandos_end;
 
723
    }
621
724
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
622
725
  
623
726
  if(ret != GNUTLS_E_SUCCESS){
632
735
  /* Read OpenPGP packet that contains the wanted password */
633
736
  
634
737
  if(debug){
635
 
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
 
738
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
636
739
            ip);
637
740
  }
638
741
  
639
742
  while(true){
640
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
 
743
    
 
744
    if(quit_now){
 
745
      goto mandos_end;
 
746
    }
 
747
    
 
748
    buffer_capacity = incbuffer(&buffer, buffer_length,
641
749
                                   buffer_capacity);
642
750
    if(buffer_capacity == 0){
643
 
      perror("adjustbuffer");
 
751
      perror("incbuffer");
644
752
      retval = -1;
645
753
      goto mandos_end;
646
754
    }
647
755
    
 
756
    if(quit_now){
 
757
      goto mandos_end;
 
758
    }
 
759
    
648
760
    sret = gnutls_record_recv(session, buffer+buffer_length,
649
761
                              BUFFER_SIZE);
650
762
    if(sret == 0){
656
768
      case GNUTLS_E_AGAIN:
657
769
        break;
658
770
      case GNUTLS_E_REHANDSHAKE:
659
 
        do{
 
771
        do {
660
772
          ret = gnutls_handshake(session);
 
773
          
 
774
          if(quit_now){
 
775
            goto mandos_end;
 
776
          }
661
777
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
662
778
        if(ret < 0){
663
779
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
682
798
    fprintf(stderr, "Closing TLS session\n");
683
799
  }
684
800
  
 
801
  if(quit_now){
 
802
    goto mandos_end;
 
803
  }
 
804
  
685
805
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
686
806
  
 
807
  if(quit_now){
 
808
    goto mandos_end;
 
809
  }
 
810
  
687
811
  if(buffer_length > 0){
688
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
 
812
    ssize_t decrypted_buffer_size;
 
813
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
689
814
                                               buffer_length,
690
815
                                               &decrypted_buffer);
691
816
    if(decrypted_buffer_size >= 0){
 
817
      
692
818
      written = 0;
693
819
      while(written < (size_t) decrypted_buffer_size){
 
820
        if(quit_now){
 
821
          goto mandos_end;
 
822
        }
 
823
        
694
824
        ret = (int)fwrite(decrypted_buffer + written, 1,
695
825
                          (size_t)decrypted_buffer_size - written,
696
826
                          stdout);
716
846
  
717
847
 mandos_end:
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
 
824
979
int main(int argc, char *argv[]){
825
980
  AvahiSServiceBrowser *sb = NULL;
826
981
  int error;
827
982
  int ret;
828
983
  intmax_t tmpmax;
829
 
  int numchars;
 
984
  char *tmp;
830
985
  int exitcode = EXIT_SUCCESS;
831
986
  const char *interface = "eth0";
832
987
  struct ifreq network;
833
 
  int sd;
 
988
  int sd = -1;
 
989
  bool take_down_interface = false;
834
990
  uid_t uid;
835
991
  gid_t gid;
836
992
  char *connect_to = NULL;
840
996
  const char *seckey = PATHDIR "/" SECKEY;
841
997
  const char *pubkey = PATHDIR "/" PUBKEY;
842
998
  
843
 
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
844
 
                        .dh_bits = 1024, .priority = "SECURE256"
845
 
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
846
999
  bool gnutls_initialized = false;
847
1000
  bool gpgme_initialized = false;
848
 
  double delay = 2.5;
 
1001
  float delay = 2.5f;
 
1002
  
 
1003
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
 
1004
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
 
1005
  
 
1006
  uid = getuid();
 
1007
  gid = getgid();
 
1008
  
 
1009
  /* Lower any group privileges we might have, just to be safe */
 
1010
  errno = 0;
 
1011
  ret = setgid(gid);
 
1012
  if(ret == -1){
 
1013
    perror("setgid");
 
1014
  }
 
1015
  
 
1016
  /* Lower user privileges (temporarily) */
 
1017
  errno = 0;
 
1018
  ret = seteuid(uid);
 
1019
  if(ret == -1){
 
1020
    perror("seteuid");
 
1021
  }
 
1022
  
 
1023
  if(quit_now){
 
1024
    goto end;
 
1025
  }
849
1026
  
850
1027
  {
851
1028
    struct argp_option options[] = {
857
1034
        .group = 1 },
858
1035
      { .name = "interface", .key = 'i',
859
1036
        .arg = "NAME",
860
 
        .doc = "Interface that will be used to search for Mandos"
861
 
        " servers",
 
1037
        .doc = "Network interface that will be used to search for"
 
1038
        " Mandos servers",
862
1039
        .group = 1 },
863
1040
      { .name = "seckey", .key = 's',
864
1041
        .arg = "FILE",
903
1080
        pubkey = arg;
904
1081
        break;
905
1082
      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'){
 
1083
        errno = 0;
 
1084
        tmpmax = strtoimax(arg, &tmp, 10);
 
1085
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1086
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
909
1087
          fprintf(stderr, "Bad number of DH bits\n");
910
1088
          exit(EXIT_FAILURE);
911
1089
        }
915
1093
        mc.priority = arg;
916
1094
        break;
917
1095
      case 131:                 /* --delay */
918
 
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
919
 
        if(ret < 1 or arg[numchars] != '\0'){
 
1096
        errno = 0;
 
1097
        delay = strtof(arg, &tmp);
 
1098
        if(errno != 0 or tmp == arg or *tmp != '\0'){
920
1099
          fprintf(stderr, "Bad delay\n");
921
1100
          exit(EXIT_FAILURE);
922
1101
        }
943
1122
    }
944
1123
  }
945
1124
  
 
1125
  if(not debug){
 
1126
    avahi_set_log_function(empty_log);
 
1127
  }
 
1128
  
 
1129
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
 
1130
     from the signal handler */
 
1131
  /* Initialize the pseudo-RNG for Avahi */
 
1132
  srand((unsigned int) time(NULL));
 
1133
  mc.simple_poll = avahi_simple_poll_new();
 
1134
  if(mc.simple_poll == NULL){
 
1135
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1136
    exitcode = EXIT_FAILURE;
 
1137
    goto end;
 
1138
  }
 
1139
  
 
1140
  sigemptyset(&sigterm_action.sa_mask);
 
1141
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
 
1142
  if(ret == -1){
 
1143
    perror("sigaddset");
 
1144
    exitcode = EXIT_FAILURE;
 
1145
    goto end;
 
1146
  }
 
1147
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
 
1148
  if(ret == -1){
 
1149
    perror("sigaddset");
 
1150
    exitcode = EXIT_FAILURE;
 
1151
    goto end;
 
1152
  }
 
1153
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
 
1154
  if(ret == -1){
 
1155
    perror("sigaddset");
 
1156
    exitcode = EXIT_FAILURE;
 
1157
    goto end;
 
1158
  }
 
1159
  /* Need to check if the handler is SIG_IGN before handling:
 
1160
     | [[info:libc:Initial Signal Actions]] |
 
1161
     | [[info:libc:Basic Signal Handling]]  |
 
1162
  */
 
1163
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
 
1164
  if(ret == -1){
 
1165
    perror("sigaction");
 
1166
    return EXIT_FAILURE;
 
1167
  }
 
1168
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1169
    ret = sigaction(SIGINT, &sigterm_action, NULL);
 
1170
    if(ret == -1){
 
1171
      perror("sigaction");
 
1172
      exitcode = EXIT_FAILURE;
 
1173
      goto end;
 
1174
    }
 
1175
  }
 
1176
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
 
1177
  if(ret == -1){
 
1178
    perror("sigaction");
 
1179
    return EXIT_FAILURE;
 
1180
  }
 
1181
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1182
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
 
1183
    if(ret == -1){
 
1184
      perror("sigaction");
 
1185
      exitcode = EXIT_FAILURE;
 
1186
      goto end;
 
1187
    }
 
1188
  }
 
1189
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
 
1190
  if(ret == -1){
 
1191
    perror("sigaction");
 
1192
    return EXIT_FAILURE;
 
1193
  }
 
1194
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1195
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
 
1196
    if(ret == -1){
 
1197
      perror("sigaction");
 
1198
      exitcode = EXIT_FAILURE;
 
1199
      goto end;
 
1200
    }
 
1201
  }
 
1202
  
946
1203
  /* If the interface is down, bring it up */
947
 
  {
 
1204
  if(interface[0] != '\0'){
 
1205
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1206
    if(if_index == 0){
 
1207
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1208
      exitcode = EXIT_FAILURE;
 
1209
      goto end;
 
1210
    }
 
1211
    
 
1212
    if(quit_now){
 
1213
      goto end;
 
1214
    }
 
1215
    
 
1216
    /* Re-raise priviliges */
 
1217
    errno = 0;
 
1218
    ret = seteuid(0);
 
1219
    if(ret == -1){
 
1220
      perror("seteuid");
 
1221
    }
 
1222
    
948
1223
#ifdef __linux__
949
1224
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
950
1225
       messages to mess up the prompt */
951
1226
    ret = klogctl(8, NULL, 5);
 
1227
    bool restore_loglevel = true;
952
1228
    if(ret == -1){
 
1229
      restore_loglevel = false;
953
1230
      perror("klogctl");
954
1231
    }
955
 
#endif
 
1232
#endif  /* __linux__ */
956
1233
    
957
1234
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
958
1235
    if(sd < 0){
959
1236
      perror("socket");
960
1237
      exitcode = EXIT_FAILURE;
961
1238
#ifdef __linux__
962
 
      ret = klogctl(7, NULL, 0);
 
1239
      if(restore_loglevel){
 
1240
        ret = klogctl(7, NULL, 0);
 
1241
        if(ret == -1){
 
1242
          perror("klogctl");
 
1243
        }
 
1244
      }
 
1245
#endif  /* __linux__ */
 
1246
      /* Lower privileges */
 
1247
      errno = 0;
 
1248
      ret = seteuid(uid);
963
1249
      if(ret == -1){
964
 
        perror("klogctl");
 
1250
        perror("seteuid");
965
1251
      }
966
 
#endif
967
1252
      goto end;
968
1253
    }
969
1254
    strcpy(network.ifr_name, interface);
971
1256
    if(ret == -1){
972
1257
      perror("ioctl SIOCGIFFLAGS");
973
1258
#ifdef __linux__
974
 
      ret = klogctl(7, NULL, 0);
 
1259
      if(restore_loglevel){
 
1260
        ret = klogctl(7, NULL, 0);
 
1261
        if(ret == -1){
 
1262
          perror("klogctl");
 
1263
        }
 
1264
      }
 
1265
#endif  /* __linux__ */
 
1266
      exitcode = EXIT_FAILURE;
 
1267
      /* Lower privileges */
 
1268
      errno = 0;
 
1269
      ret = seteuid(uid);
975
1270
      if(ret == -1){
976
 
        perror("klogctl");
 
1271
        perror("seteuid");
977
1272
      }
978
 
#endif
979
 
      exitcode = EXIT_FAILURE;
980
1273
      goto end;
981
1274
    }
982
1275
    if((network.ifr_flags & IFF_UP) == 0){
983
1276
      network.ifr_flags |= IFF_UP;
 
1277
      take_down_interface = true;
984
1278
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
985
1279
      if(ret == -1){
 
1280
        take_down_interface = false;
986
1281
        perror("ioctl SIOCSIFFLAGS");
987
1282
        exitcode = EXIT_FAILURE;
988
1283
#ifdef __linux__
989
 
        ret = klogctl(7, NULL, 0);
 
1284
        if(restore_loglevel){
 
1285
          ret = klogctl(7, NULL, 0);
 
1286
          if(ret == -1){
 
1287
            perror("klogctl");
 
1288
          }
 
1289
        }
 
1290
#endif  /* __linux__ */
 
1291
        /* Lower privileges */
 
1292
        errno = 0;
 
1293
        ret = seteuid(uid);
990
1294
        if(ret == -1){
991
 
          perror("klogctl");
 
1295
          perror("seteuid");
992
1296
        }
993
 
#endif
994
1297
        goto end;
995
1298
      }
996
1299
    }
1008
1311
        perror("nanosleep");
1009
1312
      }
1010
1313
    }
1011
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1012
 
    if(ret == -1){
1013
 
      perror("close");
 
1314
    if(not take_down_interface){
 
1315
      /* We won't need the socket anymore */
 
1316
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1317
      if(ret == -1){
 
1318
        perror("close");
 
1319
      }
1014
1320
    }
1015
1321
#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);
 
1322
    if(restore_loglevel){
 
1323
      /* Restores kernel loglevel to default */
 
1324
      ret = klogctl(7, NULL, 0);
 
1325
      if(ret == -1){
 
1326
        perror("klogctl");
 
1327
      }
 
1328
    }
 
1329
#endif  /* __linux__ */
 
1330
    /* Lower privileges */
 
1331
    errno = 0;
 
1332
    if(take_down_interface){
 
1333
      /* Lower privileges */
 
1334
      ret = seteuid(uid);
 
1335
      if(ret == -1){
 
1336
        perror("seteuid");
 
1337
      }
 
1338
    } else {
 
1339
      /* Lower privileges permanently */
 
1340
      ret = setuid(uid);
 
1341
      if(ret == -1){
 
1342
        perror("setuid");
 
1343
      }
 
1344
    }
 
1345
  }
 
1346
  
 
1347
  if(quit_now){
 
1348
    goto end;
 
1349
  }
 
1350
  
 
1351
  ret = init_gnutls_global(pubkey, seckey);
1038
1352
  if(ret == -1){
1039
1353
    fprintf(stderr, "init_gnutls_global failed\n");
1040
1354
    exitcode = EXIT_FAILURE;
1043
1357
    gnutls_initialized = true;
1044
1358
  }
1045
1359
  
 
1360
  if(quit_now){
 
1361
    goto end;
 
1362
  }
 
1363
  
 
1364
  tempdir_created = true;
1046
1365
  if(mkdtemp(tempdir) == NULL){
 
1366
    tempdir_created = false;
1047
1367
    perror("mkdtemp");
1048
1368
    goto end;
1049
1369
  }
1050
 
  tempdir_created = true;
1051
 
  
1052
 
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
 
1370
  
 
1371
  if(quit_now){
 
1372
    goto end;
 
1373
  }
 
1374
  
 
1375
  if(not init_gpgme(pubkey, seckey, tempdir)){
1053
1376
    fprintf(stderr, "init_gpgme failed\n");
1054
1377
    exitcode = EXIT_FAILURE;
1055
1378
    goto end;
1057
1380
    gpgme_initialized = true;
1058
1381
  }
1059
1382
  
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;
 
1383
  if(quit_now){
1064
1384
    goto end;
1065
1385
  }
1066
1386
  
1073
1393
      exitcode = EXIT_FAILURE;
1074
1394
      goto end;
1075
1395
    }
 
1396
    
 
1397
    if(quit_now){
 
1398
      goto end;
 
1399
    }
 
1400
    
1076
1401
    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'){
 
1402
    errno = 0;
 
1403
    tmpmax = strtoimax(address+1, &tmp, 10);
 
1404
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
 
1405
       or tmpmax != (uint16_t)tmpmax){
1080
1406
      fprintf(stderr, "Bad port number\n");
1081
1407
      exitcode = EXIT_FAILURE;
1082
1408
      goto end;
1083
1409
    }
 
1410
  
 
1411
    if(quit_now){
 
1412
      goto end;
 
1413
    }
 
1414
    
1084
1415
    port = (uint16_t)tmpmax;
1085
1416
    *address = '\0';
1086
1417
    address = connect_to;
1087
 
    ret = start_mandos_communication(address, port, if_index, &mc);
 
1418
    /* Colon in address indicates IPv6 */
 
1419
    int af;
 
1420
    if(strchr(address, ':') != NULL){
 
1421
      af = AF_INET6;
 
1422
    } else {
 
1423
      af = AF_INET;
 
1424
    }
 
1425
    
 
1426
    if(quit_now){
 
1427
      goto end;
 
1428
    }
 
1429
    
 
1430
    ret = start_mandos_communication(address, port, if_index, af);
1088
1431
    if(ret < 0){
1089
1432
      exitcode = EXIT_FAILURE;
1090
1433
    } else {
1093
1436
    goto end;
1094
1437
  }
1095
1438
  
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;
 
1439
  if(quit_now){
1108
1440
    goto end;
1109
1441
  }
1110
1442
  
1134
1466
    goto end;
1135
1467
  }
1136
1468
  
 
1469
  if(quit_now){
 
1470
    goto end;
 
1471
  }
 
1472
  
1137
1473
  /* Create the Avahi service browser */
1138
1474
  sb = avahi_s_service_browser_new(mc.server, if_index,
1139
 
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
1140
 
                                   NULL, 0, browse_callback, &mc);
 
1475
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
 
1476
                                   NULL, 0, browse_callback, NULL);
1141
1477
  if(sb == NULL){
1142
1478
    fprintf(stderr, "Failed to create service browser: %s\n",
1143
1479
            avahi_strerror(avahi_server_errno(mc.server)));
1145
1481
    goto end;
1146
1482
  }
1147
1483
  
 
1484
  if(quit_now){
 
1485
    goto end;
 
1486
  }
 
1487
  
1148
1488
  /* Run the main loop */
1149
1489
  
1150
1490
  if(debug){
1179
1519
    gpgme_release(mc.ctx);
1180
1520
  }
1181
1521
  
 
1522
  /* Take down the network interface */
 
1523
  if(take_down_interface){
 
1524
    /* Re-raise priviliges */
 
1525
    errno = 0;
 
1526
    ret = seteuid(0);
 
1527
    if(ret == -1){
 
1528
      perror("seteuid");
 
1529
    }
 
1530
    if(geteuid() == 0){
 
1531
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1532
      if(ret == -1){
 
1533
        perror("ioctl SIOCGIFFLAGS");
 
1534
      } else if(network.ifr_flags & IFF_UP) {
 
1535
        network.ifr_flags &= ~IFF_UP; /* clear flag */
 
1536
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1537
        if(ret == -1){
 
1538
          perror("ioctl SIOCSIFFLAGS");
 
1539
        }
 
1540
      }
 
1541
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1542
      if(ret == -1){
 
1543
        perror("close");
 
1544
      }
 
1545
      /* Lower privileges permanently */
 
1546
      errno = 0;
 
1547
      ret = setuid(uid);
 
1548
      if(ret == -1){
 
1549
        perror("setuid");
 
1550
      }
 
1551
    }
 
1552
  }
 
1553
  
1182
1554
  /* Removes the temp directory used by GPGME */
1183
1555
  if(tempdir_created){
1184
1556
    DIR *d;
1223
1595
    }
1224
1596
  }
1225
1597
  
 
1598
  if(quit_now){
 
1599
    sigemptyset(&old_sigterm_action.sa_mask);
 
1600
    old_sigterm_action.sa_handler = SIG_DFL;
 
1601
    ret = sigaction(signal_received, &old_sigterm_action, NULL);
 
1602
    if(ret == -1){
 
1603
      perror("sigaction");
 
1604
    }
 
1605
    raise(signal_received);
 
1606
  }
 
1607
  
1226
1608
  return exitcode;
1227
1609
}