/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-11-05 02:12:57 UTC
  • Revision ID: teddy@fukt.bsnet.se-20091105021257-l2b5nb1v4pc2tupw
* mandos (ClientDBus.disable): Bug fix: complete rename of "log" and
                               "signal" to "quiet".

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
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
44
 
                                   srand() */
45
 
#include <stdbool.h>            /* bool, true */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
 
47
                                   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
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
 
86
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
87
 
78
88
#ifdef __linux__
79
89
#include <sys/klog.h>           /* klogctl() */
80
 
#endif
 
90
#endif  /* __linux__ */
81
91
 
82
92
/* Avahi */
83
93
/* All Avahi types, constants and functions
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
  errno = 0;
 
558
  
 
559
  if(quit_now){
 
560
    errno = EINTR;
 
561
    return -1;
 
562
  }
 
563
  
 
564
  switch(af){
 
565
  case AF_INET6:
 
566
    pf = PF_INET6;
 
567
    break;
 
568
  case AF_INET:
 
569
    pf = PF_INET;
 
570
    break;
 
571
  default:
 
572
    fprintf(stderr, "Bad address family: %d\n", af);
 
573
    errno = EINVAL;
 
574
    return -1;
 
575
  }
 
576
  
 
577
  ret = init_gnutls_session(&session);
527
578
  if(ret != 0){
528
579
    return -1;
529
580
  }
530
581
  
531
582
  if(debug){
532
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
583
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
533
584
            "\n", ip, port);
534
585
  }
535
586
  
536
 
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
 
587
  tcp_sd = socket(pf, SOCK_STREAM, 0);
537
588
  if(tcp_sd < 0){
 
589
    int e = errno;
538
590
    perror("socket");
539
 
    return -1;
 
591
    errno = e;
 
592
    goto mandos_end;
540
593
  }
541
594
  
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);
 
595
  if(quit_now){
 
596
    errno = EINTR;
 
597
    goto mandos_end;
548
598
  }
549
599
  
550
600
  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);
 
601
  if(af == AF_INET6){
 
602
    to.in6.sin6_family = (sa_family_t)af;
 
603
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
604
  } else {                      /* IPv4 */
 
605
    to.in.sin_family = (sa_family_t)af;
 
606
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
607
  }
555
608
  if(ret < 0 ){
 
609
    int e = errno;
556
610
    perror("inet_pton");
557
 
    return -1;
 
611
    errno = e;
 
612
    goto mandos_end;
558
613
  }
559
614
  if(ret == 0){
 
615
    int e = errno;
560
616
    fprintf(stderr, "Bad address: %s\n", ip);
561
 
    return -1;
 
617
    errno = e;
 
618
    goto mandos_end;
562
619
  }
563
 
  to.in6.sin6_port = htons(port); /* Spurious warnings from
 
620
  if(af == AF_INET6){
 
621
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
622
                                       -Wconversion and
 
623
                                       -Wunreachable-code */
 
624
    
 
625
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
626
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
627
                              -Wunreachable-code*/
 
628
      if(if_index == AVAHI_IF_UNSPEC){
 
629
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
630
                " without a network interface\n");
 
631
        errno = EINVAL;
 
632
        goto mandos_end;
 
633
      }
 
634
      /* Set the network interface number as scope */
 
635
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
636
    }
 
637
  } else {
 
638
    to.in.sin_port = htons(port); /* Spurious warnings from
564
639
                                     -Wconversion and
565
640
                                     -Wunreachable-code */
 
641
  }
566
642
  
567
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
643
  if(quit_now){
 
644
    errno = EINTR;
 
645
    goto mandos_end;
 
646
  }
568
647
  
569
648
  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){
 
649
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
 
650
      char interface[IF_NAMESIZE];
 
651
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
652
        perror("if_indextoname");
 
653
      } else {
 
654
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
655
                ip, interface, port);
 
656
      }
 
657
    } else {
 
658
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
659
              port);
 
660
    }
 
661
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
 
662
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
663
    const char *pcret;
 
664
    if(af == AF_INET6){
 
665
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
666
                        sizeof(addrstr));
 
667
    } else {
 
668
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
669
                        sizeof(addrstr));
 
670
    }
 
671
    if(pcret == NULL){
575
672
      perror("inet_ntop");
576
673
    } else {
577
674
      if(strcmp(addrstr, ip) != 0){
580
677
    }
581
678
  }
582
679
  
583
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
680
  if(quit_now){
 
681
    errno = EINTR;
 
682
    goto mandos_end;
 
683
  }
 
684
  
 
685
  if(af == AF_INET6){
 
686
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
687
  } else {
 
688
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
689
  }
584
690
  if(ret < 0){
 
691
    int e = errno;
585
692
    perror("connect");
586
 
    return -1;
 
693
    errno = e;
 
694
    goto mandos_end;
 
695
  }
 
696
  
 
697
  if(quit_now){
 
698
    errno = EINTR;
 
699
    goto mandos_end;
587
700
  }
588
701
  
589
702
  const char *out = mandos_protocol_version;
593
706
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
594
707
                                   out_size - written));
595
708
    if(ret == -1){
 
709
      int e = errno;
596
710
      perror("write");
597
 
      retval = -1;
 
711
      errno = e;
598
712
      goto mandos_end;
599
713
    }
600
714
    written += (size_t)ret;
608
722
        break;
609
723
      }
610
724
    }
 
725
  
 
726
    if(quit_now){
 
727
      errno = EINTR;
 
728
      goto mandos_end;
 
729
    }
611
730
  }
612
731
  
613
732
  if(debug){
614
733
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
615
734
  }
616
735
  
 
736
  if(quit_now){
 
737
    errno = EINTR;
 
738
    goto mandos_end;
 
739
  }
 
740
  
617
741
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
618
742
  
619
 
  do{
 
743
  if(quit_now){
 
744
    errno = EINTR;
 
745
    goto mandos_end;
 
746
  }
 
747
  
 
748
  do {
620
749
    ret = gnutls_handshake(session);
 
750
    if(quit_now){
 
751
      errno = EINTR;
 
752
      goto mandos_end;
 
753
    }
621
754
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
622
755
  
623
756
  if(ret != GNUTLS_E_SUCCESS){
625
758
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
626
759
      gnutls_perror(ret);
627
760
    }
628
 
    retval = -1;
 
761
    errno = EPROTO;
629
762
    goto mandos_end;
630
763
  }
631
764
  
632
765
  /* Read OpenPGP packet that contains the wanted password */
633
766
  
634
767
  if(debug){
635
 
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
 
768
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
636
769
            ip);
637
770
  }
638
771
  
639
772
  while(true){
640
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
 
773
    
 
774
    if(quit_now){
 
775
      errno = EINTR;
 
776
      goto mandos_end;
 
777
    }
 
778
    
 
779
    buffer_capacity = incbuffer(&buffer, buffer_length,
641
780
                                   buffer_capacity);
642
781
    if(buffer_capacity == 0){
643
 
      perror("adjustbuffer");
644
 
      retval = -1;
 
782
      int e = errno;
 
783
      perror("incbuffer");
 
784
      errno = e;
 
785
      goto mandos_end;
 
786
    }
 
787
    
 
788
    if(quit_now){
 
789
      errno = EINTR;
645
790
      goto mandos_end;
646
791
    }
647
792
    
656
801
      case GNUTLS_E_AGAIN:
657
802
        break;
658
803
      case GNUTLS_E_REHANDSHAKE:
659
 
        do{
 
804
        do {
660
805
          ret = gnutls_handshake(session);
 
806
          
 
807
          if(quit_now){
 
808
            errno = EINTR;
 
809
            goto mandos_end;
 
810
          }
661
811
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
662
812
        if(ret < 0){
663
813
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
664
814
          gnutls_perror(ret);
665
 
          retval = -1;
 
815
          errno = EPROTO;
666
816
          goto mandos_end;
667
817
        }
668
818
        break;
669
819
      default:
670
820
        fprintf(stderr, "Unknown error while reading data from"
671
821
                " encrypted session with Mandos server\n");
672
 
        retval = -1;
673
822
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
823
        errno = EIO;
674
824
        goto mandos_end;
675
825
      }
676
826
    } else {
682
832
    fprintf(stderr, "Closing TLS session\n");
683
833
  }
684
834
  
685
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
835
  if(quit_now){
 
836
    errno = EINTR;
 
837
    goto mandos_end;
 
838
  }
 
839
  
 
840
  do {
 
841
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
842
    if(quit_now){
 
843
      errno = EINTR;
 
844
      goto mandos_end;
 
845
    }
 
846
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
686
847
  
687
848
  if(buffer_length > 0){
688
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
 
849
    ssize_t decrypted_buffer_size;
 
850
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
689
851
                                               buffer_length,
690
852
                                               &decrypted_buffer);
691
853
    if(decrypted_buffer_size >= 0){
 
854
      
692
855
      written = 0;
693
856
      while(written < (size_t) decrypted_buffer_size){
 
857
        if(quit_now){
 
858
          errno = EINTR;
 
859
          goto mandos_end;
 
860
        }
 
861
        
694
862
        ret = (int)fwrite(decrypted_buffer + written, 1,
695
863
                          (size_t)decrypted_buffer_size - written,
696
864
                          stdout);
697
865
        if(ret == 0 and ferror(stdout)){
 
866
          int e = errno;
698
867
          if(debug){
699
868
            fprintf(stderr, "Error writing encrypted data: %s\n",
700
869
                    strerror(errno));
701
870
          }
702
 
          retval = -1;
703
 
          break;
 
871
          errno = e;
 
872
          goto mandos_end;
704
873
        }
705
874
        written += (size_t)ret;
706
875
      }
707
 
      free(decrypted_buffer);
708
 
    } else {
709
 
      retval = -1;
 
876
      retval = 0;
710
877
    }
711
 
  } else {
712
 
    retval = -1;
713
878
  }
714
879
  
715
880
  /* Shutdown procedure */
716
881
  
717
882
 mandos_end:
718
 
  free(buffer);
719
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
720
 
  if(ret == -1){
721
 
    perror("close");
 
883
  {
 
884
    int e = errno;
 
885
    free(decrypted_buffer);
 
886
    free(buffer);
 
887
    if(tcp_sd >= 0){
 
888
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
889
    }
 
890
    if(ret == -1){
 
891
      if(e == 0){
 
892
        e = errno;
 
893
      }
 
894
      perror("close");
 
895
    }
 
896
    gnutls_deinit(session);
 
897
    if(quit_now){
 
898
      e = EINTR;
 
899
      retval = -1;
 
900
    }
 
901
    errno = e;
722
902
  }
723
 
  gnutls_deinit(session);
724
903
  return retval;
725
904
}
726
905
 
727
906
static void resolve_callback(AvahiSServiceResolver *r,
728
907
                             AvahiIfIndex interface,
729
 
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
908
                             AvahiProtocol proto,
730
909
                             AvahiResolverEvent event,
731
910
                             const char *name,
732
911
                             const char *type,
737
916
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
738
917
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
739
918
                             flags,
740
 
                             void* userdata){
741
 
  mandos_context *mc = userdata;
 
919
                             AVAHI_GCC_UNUSED void* userdata){
742
920
  assert(r);
743
921
  
744
922
  /* Called whenever a service has been resolved successfully or
745
923
     timed out */
746
924
  
 
925
  if(quit_now){
 
926
    return;
 
927
  }
 
928
  
747
929
  switch(event){
748
930
  default:
749
931
  case AVAHI_RESOLVER_FAILURE:
750
932
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
751
933
            " of type '%s' in domain '%s': %s\n", name, type, domain,
752
 
            avahi_strerror(avahi_server_errno(mc->server)));
 
934
            avahi_strerror(avahi_server_errno(mc.server)));
753
935
    break;
754
936
    
755
937
  case AVAHI_RESOLVER_FOUND:
761
943
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
762
944
                ip, (intmax_t)interface, port);
763
945
      }
764
 
      int ret = start_mandos_communication(ip, port, interface, mc);
 
946
      int ret = start_mandos_communication(ip, port, interface,
 
947
                                           avahi_proto_to_af(proto));
765
948
      if(ret == 0){
766
 
        avahi_simple_poll_quit(mc->simple_poll);
 
949
        avahi_simple_poll_quit(mc.simple_poll);
767
950
      }
768
951
    }
769
952
  }
779
962
                            const char *domain,
780
963
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
781
964
                            flags,
782
 
                            void* userdata){
783
 
  mandos_context *mc = userdata;
 
965
                            AVAHI_GCC_UNUSED void* userdata){
784
966
  assert(b);
785
967
  
786
968
  /* Called whenever a new services becomes available on the LAN or
787
969
     is removed from the LAN */
788
970
  
 
971
  if(quit_now){
 
972
    return;
 
973
  }
 
974
  
789
975
  switch(event){
790
976
  default:
791
977
  case AVAHI_BROWSER_FAILURE:
792
978
    
793
979
    fprintf(stderr, "(Avahi browser) %s\n",
794
 
            avahi_strerror(avahi_server_errno(mc->server)));
795
 
    avahi_simple_poll_quit(mc->simple_poll);
 
980
            avahi_strerror(avahi_server_errno(mc.server)));
 
981
    avahi_simple_poll_quit(mc.simple_poll);
796
982
    return;
797
983
    
798
984
  case AVAHI_BROWSER_NEW:
801
987
       the callback function is called the Avahi server will free the
802
988
       resolver for us. */
803
989
    
804
 
    if(!(avahi_s_service_resolver_new(mc->server, interface,
805
 
                                       protocol, name, type, domain,
806
 
                                       AVAHI_PROTO_INET6, 0,
807
 
                                       resolve_callback, mc)))
 
990
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
991
                                    name, type, domain, protocol, 0,
 
992
                                    resolve_callback, NULL) == NULL)
808
993
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
809
 
              name, avahi_strerror(avahi_server_errno(mc->server)));
 
994
              name, avahi_strerror(avahi_server_errno(mc.server)));
810
995
    break;
811
996
    
812
997
  case AVAHI_BROWSER_REMOVE:
821
1006
  }
822
1007
}
823
1008
 
 
1009
/* stop main loop after sigterm has been called */
 
1010
static void handle_sigterm(int sig){
 
1011
  if(quit_now){
 
1012
    return;
 
1013
  }
 
1014
  quit_now = 1;
 
1015
  signal_received = sig;
 
1016
  int old_errno = errno;
 
1017
  if(mc.simple_poll != NULL){
 
1018
    avahi_simple_poll_quit(mc.simple_poll);
 
1019
  }
 
1020
  errno = old_errno;
 
1021
}
 
1022
 
824
1023
int main(int argc, char *argv[]){
825
1024
  AvahiSServiceBrowser *sb = NULL;
826
1025
  int error;
827
1026
  int ret;
828
1027
  intmax_t tmpmax;
829
 
  int numchars;
 
1028
  char *tmp;
830
1029
  int exitcode = EXIT_SUCCESS;
831
1030
  const char *interface = "eth0";
832
1031
  struct ifreq network;
833
 
  int sd;
 
1032
  int sd = -1;
 
1033
  bool take_down_interface = false;
834
1034
  uid_t uid;
835
1035
  gid_t gid;
836
1036
  char *connect_to = NULL;
840
1040
  const char *seckey = PATHDIR "/" SECKEY;
841
1041
  const char *pubkey = PATHDIR "/" PUBKEY;
842
1042
  
843
 
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
844
 
                        .dh_bits = 1024, .priority = "SECURE256"
845
 
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
846
1043
  bool gnutls_initialized = false;
847
1044
  bool gpgme_initialized = false;
848
 
  double delay = 2.5;
 
1045
  float delay = 2.5f;
 
1046
  
 
1047
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
 
1048
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
 
1049
  
 
1050
  uid = getuid();
 
1051
  gid = getgid();
 
1052
  
 
1053
  /* Lower any group privileges we might have, just to be safe */
 
1054
  errno = 0;
 
1055
  ret = setgid(gid);
 
1056
  if(ret == -1){
 
1057
    perror("setgid");
 
1058
  }
 
1059
  
 
1060
  /* Lower user privileges (temporarily) */
 
1061
  errno = 0;
 
1062
  ret = seteuid(uid);
 
1063
  if(ret == -1){
 
1064
    perror("seteuid");
 
1065
  }
 
1066
  
 
1067
  if(quit_now){
 
1068
    goto end;
 
1069
  }
849
1070
  
850
1071
  {
851
1072
    struct argp_option options[] = {
857
1078
        .group = 1 },
858
1079
      { .name = "interface", .key = 'i',
859
1080
        .arg = "NAME",
860
 
        .doc = "Interface that will be used to search for Mandos"
861
 
        " servers",
 
1081
        .doc = "Network interface that will be used to search for"
 
1082
        " Mandos servers",
862
1083
        .group = 1 },
863
1084
      { .name = "seckey", .key = 's',
864
1085
        .arg = "FILE",
881
1102
        .arg = "SECONDS",
882
1103
        .doc = "Maximum delay to wait for interface startup",
883
1104
        .group = 2 },
 
1105
      /*
 
1106
       * These reproduce what we would get without ARGP_NO_HELP
 
1107
       */
 
1108
      { .name = "help", .key = '?',
 
1109
        .doc = "Give this help list", .group = -1 },
 
1110
      { .name = "usage", .key = -3,
 
1111
        .doc = "Give a short usage message", .group = -1 },
 
1112
      { .name = "version", .key = 'V',
 
1113
        .doc = "Print program version", .group = -1 },
884
1114
      { .name = NULL }
885
1115
    };
886
1116
    
887
1117
    error_t parse_opt(int key, char *arg,
888
1118
                      struct argp_state *state){
 
1119
      errno = 0;
889
1120
      switch(key){
890
1121
      case 128:                 /* --debug */
891
1122
        debug = true;
903
1134
        pubkey = arg;
904
1135
        break;
905
1136
      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'){
909
 
          fprintf(stderr, "Bad number of DH bits\n");
910
 
          exit(EXIT_FAILURE);
 
1137
        errno = 0;
 
1138
        tmpmax = strtoimax(arg, &tmp, 10);
 
1139
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1140
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
 
1141
          argp_error(state, "Bad number of DH bits");
911
1142
        }
912
1143
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
913
1144
        break;
915
1146
        mc.priority = arg;
916
1147
        break;
917
1148
      case 131:                 /* --delay */
918
 
        ret = sscanf(arg, "%lf%n", &delay, &numchars);
919
 
        if(ret < 1 or arg[numchars] != '\0'){
920
 
          fprintf(stderr, "Bad delay\n");
921
 
          exit(EXIT_FAILURE);
 
1149
        errno = 0;
 
1150
        delay = strtof(arg, &tmp);
 
1151
        if(errno != 0 or tmp == arg or *tmp != '\0'){
 
1152
          argp_error(state, "Bad delay");
922
1153
        }
923
1154
        break;
924
 
      case ARGP_KEY_ARG:
925
 
        argp_usage(state);
926
 
      case ARGP_KEY_END:
 
1155
        /*
 
1156
         * These reproduce what we would get without ARGP_NO_HELP
 
1157
         */
 
1158
      case '?':                 /* --help */
 
1159
        argp_state_help(state, state->out_stream,
 
1160
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
 
1161
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
 
1162
      case -3:                  /* --usage */
 
1163
        argp_state_help(state, state->out_stream,
 
1164
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
 
1165
      case 'V':                 /* --version */
 
1166
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1167
        exit(argp_err_exit_status);
927
1168
        break;
928
1169
      default:
929
1170
        return ARGP_ERR_UNKNOWN;
930
1171
      }
931
 
      return 0;
 
1172
      return errno;
932
1173
    }
933
1174
    
934
1175
    struct argp argp = { .options = options, .parser = parse_opt,
935
1176
                         .args_doc = "",
936
1177
                         .doc = "Mandos client -- Get and decrypt"
937
1178
                         " passwords from a Mandos server" };
938
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
939
 
    if(ret == ARGP_ERR_UNKNOWN){
940
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
941
 
      exitcode = EXIT_FAILURE;
 
1179
    ret = argp_parse(&argp, argc, argv,
 
1180
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1181
    switch(ret){
 
1182
    case 0:
 
1183
      break;
 
1184
    case ENOMEM:
 
1185
    default:
 
1186
      errno = ret;
 
1187
      perror("argp_parse");
 
1188
      exitcode = EX_OSERR;
 
1189
      goto end;
 
1190
    case EINVAL:
 
1191
      exitcode = EX_USAGE;
 
1192
      goto end;
 
1193
    }
 
1194
  }
 
1195
  
 
1196
  if(not debug){
 
1197
    avahi_set_log_function(empty_log);
 
1198
  }
 
1199
  
 
1200
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
 
1201
     from the signal handler */
 
1202
  /* Initialize the pseudo-RNG for Avahi */
 
1203
  srand((unsigned int) time(NULL));
 
1204
  mc.simple_poll = avahi_simple_poll_new();
 
1205
  if(mc.simple_poll == NULL){
 
1206
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1207
    exitcode = EX_UNAVAILABLE;
 
1208
    goto end;
 
1209
  }
 
1210
  
 
1211
  sigemptyset(&sigterm_action.sa_mask);
 
1212
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
 
1213
  if(ret == -1){
 
1214
    perror("sigaddset");
 
1215
    exitcode = EX_OSERR;
 
1216
    goto end;
 
1217
  }
 
1218
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
 
1219
  if(ret == -1){
 
1220
    perror("sigaddset");
 
1221
    exitcode = EX_OSERR;
 
1222
    goto end;
 
1223
  }
 
1224
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
 
1225
  if(ret == -1){
 
1226
    perror("sigaddset");
 
1227
    exitcode = EX_OSERR;
 
1228
    goto end;
 
1229
  }
 
1230
  /* Need to check if the handler is SIG_IGN before handling:
 
1231
     | [[info:libc:Initial Signal Actions]] |
 
1232
     | [[info:libc:Basic Signal Handling]]  |
 
1233
  */
 
1234
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
 
1235
  if(ret == -1){
 
1236
    perror("sigaction");
 
1237
    return EX_OSERR;
 
1238
  }
 
1239
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1240
    ret = sigaction(SIGINT, &sigterm_action, NULL);
 
1241
    if(ret == -1){
 
1242
      perror("sigaction");
 
1243
      exitcode = EX_OSERR;
 
1244
      goto end;
 
1245
    }
 
1246
  }
 
1247
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
 
1248
  if(ret == -1){
 
1249
    perror("sigaction");
 
1250
    return EX_OSERR;
 
1251
  }
 
1252
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1253
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
 
1254
    if(ret == -1){
 
1255
      perror("sigaction");
 
1256
      exitcode = EX_OSERR;
 
1257
      goto end;
 
1258
    }
 
1259
  }
 
1260
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
 
1261
  if(ret == -1){
 
1262
    perror("sigaction");
 
1263
    return EX_OSERR;
 
1264
  }
 
1265
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1266
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
 
1267
    if(ret == -1){
 
1268
      perror("sigaction");
 
1269
      exitcode = EX_OSERR;
942
1270
      goto end;
943
1271
    }
944
1272
  }
945
1273
  
946
1274
  /* If the interface is down, bring it up */
947
 
  {
 
1275
  if(interface[0] != '\0'){
 
1276
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1277
    if(if_index == 0){
 
1278
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1279
      exitcode = EX_UNAVAILABLE;
 
1280
      goto end;
 
1281
    }
 
1282
    
 
1283
    if(quit_now){
 
1284
      goto end;
 
1285
    }
 
1286
    
 
1287
    /* Re-raise priviliges */
 
1288
    errno = 0;
 
1289
    ret = seteuid(0);
 
1290
    if(ret == -1){
 
1291
      perror("seteuid");
 
1292
    }
 
1293
    
948
1294
#ifdef __linux__
949
1295
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
950
 
       messages to mess up the prompt */
 
1296
       messages about the network interface to mess up the prompt */
951
1297
    ret = klogctl(8, NULL, 5);
 
1298
    bool restore_loglevel = true;
952
1299
    if(ret == -1){
 
1300
      restore_loglevel = false;
953
1301
      perror("klogctl");
954
1302
    }
955
 
#endif
 
1303
#endif  /* __linux__ */
956
1304
    
957
1305
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
958
1306
    if(sd < 0){
959
1307
      perror("socket");
960
 
      exitcode = EXIT_FAILURE;
 
1308
      exitcode = EX_OSERR;
961
1309
#ifdef __linux__
962
 
      ret = klogctl(7, NULL, 0);
 
1310
      if(restore_loglevel){
 
1311
        ret = klogctl(7, NULL, 0);
 
1312
        if(ret == -1){
 
1313
          perror("klogctl");
 
1314
        }
 
1315
      }
 
1316
#endif  /* __linux__ */
 
1317
      /* Lower privileges */
 
1318
      errno = 0;
 
1319
      ret = seteuid(uid);
963
1320
      if(ret == -1){
964
 
        perror("klogctl");
 
1321
        perror("seteuid");
965
1322
      }
966
 
#endif
967
1323
      goto end;
968
1324
    }
969
1325
    strcpy(network.ifr_name, interface);
971
1327
    if(ret == -1){
972
1328
      perror("ioctl SIOCGIFFLAGS");
973
1329
#ifdef __linux__
974
 
      ret = klogctl(7, NULL, 0);
 
1330
      if(restore_loglevel){
 
1331
        ret = klogctl(7, NULL, 0);
 
1332
        if(ret == -1){
 
1333
          perror("klogctl");
 
1334
        }
 
1335
      }
 
1336
#endif  /* __linux__ */
 
1337
      exitcode = EX_OSERR;
 
1338
      /* Lower privileges */
 
1339
      errno = 0;
 
1340
      ret = seteuid(uid);
975
1341
      if(ret == -1){
976
 
        perror("klogctl");
 
1342
        perror("seteuid");
977
1343
      }
978
 
#endif
979
 
      exitcode = EXIT_FAILURE;
980
1344
      goto end;
981
1345
    }
982
1346
    if((network.ifr_flags & IFF_UP) == 0){
983
1347
      network.ifr_flags |= IFF_UP;
 
1348
      take_down_interface = true;
984
1349
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
985
1350
      if(ret == -1){
 
1351
        take_down_interface = false;
986
1352
        perror("ioctl SIOCSIFFLAGS");
987
 
        exitcode = EXIT_FAILURE;
 
1353
        exitcode = EX_OSERR;
988
1354
#ifdef __linux__
989
 
        ret = klogctl(7, NULL, 0);
 
1355
        if(restore_loglevel){
 
1356
          ret = klogctl(7, NULL, 0);
 
1357
          if(ret == -1){
 
1358
            perror("klogctl");
 
1359
          }
 
1360
        }
 
1361
#endif  /* __linux__ */
 
1362
        /* Lower privileges */
 
1363
        errno = 0;
 
1364
        ret = seteuid(uid);
990
1365
        if(ret == -1){
991
 
          perror("klogctl");
 
1366
          perror("seteuid");
992
1367
        }
993
 
#endif
994
1368
        goto end;
995
1369
      }
996
1370
    }
1008
1382
        perror("nanosleep");
1009
1383
      }
1010
1384
    }
1011
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1012
 
    if(ret == -1){
1013
 
      perror("close");
 
1385
    if(not take_down_interface){
 
1386
      /* We won't need the socket anymore */
 
1387
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1388
      if(ret == -1){
 
1389
        perror("close");
 
1390
      }
1014
1391
    }
1015
1392
#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);
 
1393
    if(restore_loglevel){
 
1394
      /* Restores kernel loglevel to default */
 
1395
      ret = klogctl(7, NULL, 0);
 
1396
      if(ret == -1){
 
1397
        perror("klogctl");
 
1398
      }
 
1399
    }
 
1400
#endif  /* __linux__ */
 
1401
    /* Lower privileges */
 
1402
    errno = 0;
 
1403
    if(take_down_interface){
 
1404
      /* Lower privileges */
 
1405
      ret = seteuid(uid);
 
1406
      if(ret == -1){
 
1407
        perror("seteuid");
 
1408
      }
 
1409
    } else {
 
1410
      /* Lower privileges permanently */
 
1411
      ret = setuid(uid);
 
1412
      if(ret == -1){
 
1413
        perror("setuid");
 
1414
      }
 
1415
    }
 
1416
  }
 
1417
  
 
1418
  if(quit_now){
 
1419
    goto end;
 
1420
  }
 
1421
  
 
1422
  ret = init_gnutls_global(pubkey, seckey);
1038
1423
  if(ret == -1){
1039
1424
    fprintf(stderr, "init_gnutls_global failed\n");
1040
 
    exitcode = EXIT_FAILURE;
 
1425
    exitcode = EX_UNAVAILABLE;
1041
1426
    goto end;
1042
1427
  } else {
1043
1428
    gnutls_initialized = true;
1044
1429
  }
1045
1430
  
 
1431
  if(quit_now){
 
1432
    goto end;
 
1433
  }
 
1434
  
 
1435
  tempdir_created = true;
1046
1436
  if(mkdtemp(tempdir) == NULL){
 
1437
    tempdir_created = false;
1047
1438
    perror("mkdtemp");
1048
1439
    goto end;
1049
1440
  }
1050
 
  tempdir_created = true;
1051
 
  
1052
 
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
 
1441
  
 
1442
  if(quit_now){
 
1443
    goto end;
 
1444
  }
 
1445
  
 
1446
  if(not init_gpgme(pubkey, seckey, tempdir)){
1053
1447
    fprintf(stderr, "init_gpgme failed\n");
1054
 
    exitcode = EXIT_FAILURE;
 
1448
    exitcode = EX_UNAVAILABLE;
1055
1449
    goto end;
1056
1450
  } else {
1057
1451
    gpgme_initialized = true;
1058
1452
  }
1059
1453
  
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;
 
1454
  if(quit_now){
1064
1455
    goto end;
1065
1456
  }
1066
1457
  
1070
1461
    char *address = strrchr(connect_to, ':');
1071
1462
    if(address == NULL){
1072
1463
      fprintf(stderr, "No colon in address\n");
1073
 
      exitcode = EXIT_FAILURE;
1074
 
      goto end;
1075
 
    }
 
1464
      exitcode = EX_USAGE;
 
1465
      goto end;
 
1466
    }
 
1467
    
 
1468
    if(quit_now){
 
1469
      goto end;
 
1470
    }
 
1471
    
1076
1472
    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'){
 
1473
    errno = 0;
 
1474
    tmpmax = strtoimax(address+1, &tmp, 10);
 
1475
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
 
1476
       or tmpmax != (uint16_t)tmpmax){
1080
1477
      fprintf(stderr, "Bad port number\n");
1081
 
      exitcode = EXIT_FAILURE;
1082
 
      goto end;
1083
 
    }
 
1478
      exitcode = EX_USAGE;
 
1479
      goto end;
 
1480
    }
 
1481
  
 
1482
    if(quit_now){
 
1483
      goto end;
 
1484
    }
 
1485
    
1084
1486
    port = (uint16_t)tmpmax;
1085
1487
    *address = '\0';
1086
1488
    address = connect_to;
1087
 
    ret = start_mandos_communication(address, port, if_index, &mc);
 
1489
    /* Colon in address indicates IPv6 */
 
1490
    int af;
 
1491
    if(strchr(address, ':') != NULL){
 
1492
      af = AF_INET6;
 
1493
    } else {
 
1494
      af = AF_INET;
 
1495
    }
 
1496
    
 
1497
    if(quit_now){
 
1498
      goto end;
 
1499
    }
 
1500
    
 
1501
    ret = start_mandos_communication(address, port, if_index, af);
1088
1502
    if(ret < 0){
1089
 
      exitcode = EXIT_FAILURE;
 
1503
      switch(errno){
 
1504
      case ENETUNREACH:
 
1505
      case EHOSTDOWN:
 
1506
      case EHOSTUNREACH:
 
1507
        exitcode = EX_NOHOST;
 
1508
        break;
 
1509
      case EINVAL:
 
1510
        exitcode = EX_USAGE;
 
1511
        break;
 
1512
      case EIO:
 
1513
        exitcode = EX_IOERR;
 
1514
        break;
 
1515
      case EPROTO:
 
1516
        exitcode = EX_PROTOCOL;
 
1517
        break;
 
1518
      default:
 
1519
        exitcode = EX_OSERR;
 
1520
        break;
 
1521
      }
1090
1522
    } else {
1091
1523
      exitcode = EXIT_SUCCESS;
1092
1524
    }
1093
1525
    goto end;
1094
1526
  }
1095
1527
  
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;
 
1528
  if(quit_now){
1108
1529
    goto end;
1109
1530
  }
1110
1531
  
1130
1551
  if(mc.server == NULL){
1131
1552
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1132
1553
            avahi_strerror(error));
1133
 
    exitcode = EXIT_FAILURE;
 
1554
    exitcode = EX_UNAVAILABLE;
 
1555
    goto end;
 
1556
  }
 
1557
  
 
1558
  if(quit_now){
1134
1559
    goto end;
1135
1560
  }
1136
1561
  
1137
1562
  /* Create the Avahi service browser */
1138
1563
  sb = avahi_s_service_browser_new(mc.server, if_index,
1139
 
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
1140
 
                                   NULL, 0, browse_callback, &mc);
 
1564
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
 
1565
                                   NULL, 0, browse_callback, NULL);
1141
1566
  if(sb == NULL){
1142
1567
    fprintf(stderr, "Failed to create service browser: %s\n",
1143
1568
            avahi_strerror(avahi_server_errno(mc.server)));
1144
 
    exitcode = EXIT_FAILURE;
 
1569
    exitcode = EX_UNAVAILABLE;
 
1570
    goto end;
 
1571
  }
 
1572
  
 
1573
  if(quit_now){
1145
1574
    goto end;
1146
1575
  }
1147
1576
  
1179
1608
    gpgme_release(mc.ctx);
1180
1609
  }
1181
1610
  
 
1611
  /* Take down the network interface */
 
1612
  if(take_down_interface){
 
1613
    /* Re-raise priviliges */
 
1614
    errno = 0;
 
1615
    ret = seteuid(0);
 
1616
    if(ret == -1){
 
1617
      perror("seteuid");
 
1618
    }
 
1619
    if(geteuid() == 0){
 
1620
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1621
      if(ret == -1){
 
1622
        perror("ioctl SIOCGIFFLAGS");
 
1623
      } else if(network.ifr_flags & IFF_UP) {
 
1624
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1625
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1626
        if(ret == -1){
 
1627
          perror("ioctl SIOCSIFFLAGS");
 
1628
        }
 
1629
      }
 
1630
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1631
      if(ret == -1){
 
1632
        perror("close");
 
1633
      }
 
1634
      /* Lower privileges permanently */
 
1635
      errno = 0;
 
1636
      ret = setuid(uid);
 
1637
      if(ret == -1){
 
1638
        perror("setuid");
 
1639
      }
 
1640
    }
 
1641
  }
 
1642
  
1182
1643
  /* Removes the temp directory used by GPGME */
1183
1644
  if(tempdir_created){
1184
1645
    DIR *d;
1223
1684
    }
1224
1685
  }
1225
1686
  
 
1687
  if(quit_now){
 
1688
    sigemptyset(&old_sigterm_action.sa_mask);
 
1689
    old_sigterm_action.sa_handler = SIG_DFL;
 
1690
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
 
1691
                                            &old_sigterm_action,
 
1692
                                            NULL));
 
1693
    if(ret == -1){
 
1694
      perror("sigaction");
 
1695
    }
 
1696
    do {
 
1697
      ret = raise(signal_received);
 
1698
    } while(ret != 0 and errno == EINTR);
 
1699
    if(ret != 0){
 
1700
      perror("raise");
 
1701
      abort();
 
1702
    }
 
1703
    TEMP_FAILURE_RETRY(pause());
 
1704
  }
 
1705
  
1226
1706
  return exitcode;
1227
1707
}