/mandos/release

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

« back to all changes in this revision

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

Rename all D-Bus properties to conform to D-Bus naming conventions;
all programs changed.

Also rename client setting "approved_delay" to "approval_delay", and
"approved_duration" to "approval_duration"; all programs changed.

* mandos (ClientDBus.NeedApproval): Bug fix: send an UInt64, not a
                                    float.
  (ClientDBus.ApprovedByDefault_dbus_property,
  ClientDBus.ApprovalDelay_dbus_property,
  ClientDBus.ApprovalDuration_dbus_property): Bug fix: send
                                              PropertyChanged signal.

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
117
127
static const char mandos_protocol_version[] = "1";
118
128
const char *argp_program_version = "mandos-client " VERSION;
119
129
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
130
static const char sys_class_net[] = "/sys/class/net";
 
131
char *connect_to = NULL;
120
132
 
121
133
/* Used for passing in values through the Avahi callback functions */
122
134
typedef struct {
129
141
  gpgme_ctx_t ctx;
130
142
} mandos_context;
131
143
 
 
144
/* global context so signal handler can reach it*/
 
145
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
146
                      .dh_bits = 1024, .priority = "SECURE256"
 
147
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
148
 
 
149
sig_atomic_t quit_now = 0;
 
150
int signal_received = 0;
 
151
 
132
152
/*
133
 
 * Make additional room in "buffer" for at least BUFFER_SIZE
134
 
 * additional bytes. "buffer_capacity" is how much is currently
135
 
 * allocated, "buffer_length" is how much is already used.
 
153
 * Make additional room in "buffer" for at least BUFFER_SIZE more
 
154
 * bytes. "buffer_capacity" is how much is currently allocated,
 
155
 * "buffer_length" is how much is already used.
136
156
 */
137
157
size_t incbuffer(char **buffer, size_t buffer_length,
138
158
                  size_t buffer_capacity){
149
169
/* 
150
170
 * Initialize GPGME.
151
171
 */
152
 
static bool init_gpgme(mandos_context *mc, const char *seckey,
 
172
static bool init_gpgme(const char *seckey,
153
173
                       const char *pubkey, const char *tempdir){
154
 
  int ret;
155
174
  gpgme_error_t rc;
156
175
  gpgme_engine_info_t engine_info;
157
176
  
160
179
   * Helper function to insert pub and seckey to the engine keyring.
161
180
   */
162
181
  bool import_key(const char *filename){
 
182
    int ret;
163
183
    int fd;
164
184
    gpgme_data_t pgp_data;
165
185
    
176
196
      return false;
177
197
    }
178
198
    
179
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
199
    rc = gpgme_op_import(mc.ctx, pgp_data);
180
200
    if(rc != GPG_ERR_NO_ERROR){
181
201
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
182
202
              gpgme_strsource(rc), gpgme_strerror(rc));
192
212
  }
193
213
  
194
214
  if(debug){
195
 
    fprintf(stderr, "Initialize gpgme\n");
 
215
    fprintf(stderr, "Initializing GPGME\n");
196
216
  }
197
217
  
198
218
  /* Init GPGME */
225
245
  }
226
246
  
227
247
  /* Create new GPGME "context" */
228
 
  rc = gpgme_new(&(mc->ctx));
 
248
  rc = gpgme_new(&(mc.ctx));
229
249
  if(rc != GPG_ERR_NO_ERROR){
230
250
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
231
251
            gpgme_strsource(rc), gpgme_strerror(rc));
236
256
    return false;
237
257
  }
238
258
  
239
 
  return true; 
 
259
  return true;
240
260
}
241
261
 
242
262
/* 
243
263
 * Decrypt OpenPGP data.
244
264
 * Returns -1 on error
245
265
 */
246
 
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
247
 
                                  const char *cryptotext,
 
266
static ssize_t pgp_packet_decrypt(const char *cryptotext,
248
267
                                  size_t crypto_size,
249
268
                                  char **plaintext){
250
269
  gpgme_data_t dh_crypto, dh_plain;
277
296
  
278
297
  /* Decrypt data from the cryptotext data buffer to the plaintext
279
298
     data buffer */
280
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
299
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
281
300
  if(rc != GPG_ERR_NO_ERROR){
282
301
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
283
302
            gpgme_strsource(rc), gpgme_strerror(rc));
284
303
    plaintext_length = -1;
285
304
    if(debug){
286
305
      gpgme_decrypt_result_t result;
287
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
306
      result = gpgme_op_decrypt_result(mc.ctx);
288
307
      if(result == NULL){
289
308
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
290
309
      } else {
297
316
        }
298
317
        gpgme_recipient_t recipient;
299
318
        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
 
          }
 
319
        while(recipient != NULL){
 
320
          fprintf(stderr, "Public key algorithm: %s\n",
 
321
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
322
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
323
          fprintf(stderr, "Secret key available: %s\n",
 
324
                  recipient->status == GPG_ERR_NO_SECKEY
 
325
                  ? "No" : "Yes");
 
326
          recipient = recipient->next;
310
327
        }
311
328
      }
312
329
    }
382
399
  fprintf(stderr, "GnuTLS: %s", string);
383
400
}
384
401
 
385
 
static int init_gnutls_global(mandos_context *mc,
386
 
                              const char *pubkeyfilename,
 
402
static int init_gnutls_global(const char *pubkeyfilename,
387
403
                              const char *seckeyfilename){
388
404
  int ret;
389
405
  
407
423
  }
408
424
  
409
425
  /* OpenPGP credentials */
410
 
  gnutls_certificate_allocate_credentials(&mc->cred);
 
426
  gnutls_certificate_allocate_credentials(&mc.cred);
411
427
  if(ret != GNUTLS_E_SUCCESS){
412
428
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
413
 
                                                  * from
414
 
                                                  * -Wunreachable-code
415
 
                                                  */
 
429
                                                    from
 
430
                                                    -Wunreachable-code
 
431
                                                 */
416
432
            safer_gnutls_strerror(ret));
417
433
    gnutls_global_deinit();
418
434
    return -1;
425
441
  }
426
442
  
427
443
  ret = gnutls_certificate_set_openpgp_key_file
428
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
444
    (mc.cred, pubkeyfilename, seckeyfilename,
429
445
     GNUTLS_OPENPGP_FMT_BASE64);
430
446
  if(ret != GNUTLS_E_SUCCESS){
431
447
    fprintf(stderr,
437
453
  }
438
454
  
439
455
  /* GnuTLS server initialization */
440
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
456
  ret = gnutls_dh_params_init(&mc.dh_params);
441
457
  if(ret != GNUTLS_E_SUCCESS){
442
458
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
443
459
            " %s\n", safer_gnutls_strerror(ret));
444
460
    goto globalfail;
445
461
  }
446
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
462
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
447
463
  if(ret != GNUTLS_E_SUCCESS){
448
464
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
449
465
            safer_gnutls_strerror(ret));
450
466
    goto globalfail;
451
467
  }
452
468
  
453
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
469
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
454
470
  
455
471
  return 0;
456
472
  
457
473
 globalfail:
458
474
  
459
 
  gnutls_certificate_free_credentials(mc->cred);
 
475
  gnutls_certificate_free_credentials(mc.cred);
460
476
  gnutls_global_deinit();
461
 
  gnutls_dh_params_deinit(mc->dh_params);
 
477
  gnutls_dh_params_deinit(mc.dh_params);
462
478
  return -1;
463
479
}
464
480
 
465
 
static int init_gnutls_session(mandos_context *mc,
466
 
                               gnutls_session_t *session){
 
481
static int init_gnutls_session(gnutls_session_t *session){
467
482
  int ret;
468
483
  /* GnuTLS session creation */
469
 
  ret = gnutls_init(session, GNUTLS_SERVER);
 
484
  do {
 
485
    ret = gnutls_init(session, GNUTLS_SERVER);
 
486
    if(quit_now){
 
487
      return -1;
 
488
    }
 
489
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
470
490
  if(ret != GNUTLS_E_SUCCESS){
471
491
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
472
492
            safer_gnutls_strerror(ret));
474
494
  
475
495
  {
476
496
    const char *err;
477
 
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
497
    do {
 
498
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
499
      if(quit_now){
 
500
        gnutls_deinit(*session);
 
501
        return -1;
 
502
      }
 
503
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
478
504
    if(ret != GNUTLS_E_SUCCESS){
479
505
      fprintf(stderr, "Syntax error at: %s\n", err);
480
506
      fprintf(stderr, "GnuTLS error: %s\n",
484
510
    }
485
511
  }
486
512
  
487
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
488
 
                               mc->cred);
 
513
  do {
 
514
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
515
                                 mc.cred);
 
516
    if(quit_now){
 
517
      gnutls_deinit(*session);
 
518
      return -1;
 
519
    }
 
520
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
489
521
  if(ret != GNUTLS_E_SUCCESS){
490
522
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
491
523
            safer_gnutls_strerror(ret));
494
526
  }
495
527
  
496
528
  /* ignore client certificate if any. */
497
 
  gnutls_certificate_server_set_request(*session,
498
 
                                        GNUTLS_CERT_IGNORE);
 
529
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
499
530
  
500
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
531
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
501
532
  
502
533
  return 0;
503
534
}
509
540
/* Called when a Mandos server is found */
510
541
static int start_mandos_communication(const char *ip, uint16_t port,
511
542
                                      AvahiIfIndex if_index,
512
 
                                      mandos_context *mc){
513
 
  int ret, tcp_sd;
 
543
                                      int af){
 
544
  int ret, tcp_sd = -1;
514
545
  ssize_t sret;
515
 
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
 
546
  union {
 
547
    struct sockaddr_in in;
 
548
    struct sockaddr_in6 in6;
 
549
  } to;
516
550
  char *buffer = NULL;
517
 
  char *decrypted_buffer;
 
551
  char *decrypted_buffer = NULL;
518
552
  size_t buffer_length = 0;
519
553
  size_t buffer_capacity = 0;
520
 
  ssize_t decrypted_buffer_size;
521
554
  size_t written;
522
 
  int retval = 0;
523
 
  char interface[IF_NAMESIZE];
 
555
  int retval = -1;
524
556
  gnutls_session_t session;
525
 
  
526
 
  ret = init_gnutls_session(mc, &session);
 
557
  int pf;                       /* Protocol family */
 
558
  
 
559
  errno = 0;
 
560
  
 
561
  if(quit_now){
 
562
    errno = EINTR;
 
563
    return -1;
 
564
  }
 
565
  
 
566
  switch(af){
 
567
  case AF_INET6:
 
568
    pf = PF_INET6;
 
569
    break;
 
570
  case AF_INET:
 
571
    pf = PF_INET;
 
572
    break;
 
573
  default:
 
574
    fprintf(stderr, "Bad address family: %d\n", af);
 
575
    errno = EINVAL;
 
576
    return -1;
 
577
  }
 
578
  
 
579
  ret = init_gnutls_session(&session);
527
580
  if(ret != 0){
528
581
    return -1;
529
582
  }
530
583
  
531
584
  if(debug){
532
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
585
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
533
586
            "\n", ip, port);
534
587
  }
535
588
  
536
 
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
 
589
  tcp_sd = socket(pf, SOCK_STREAM, 0);
537
590
  if(tcp_sd < 0){
 
591
    int e = errno;
538
592
    perror("socket");
539
 
    return -1;
 
593
    errno = e;
 
594
    goto mandos_end;
540
595
  }
541
596
  
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);
 
597
  if(quit_now){
 
598
    errno = EINTR;
 
599
    goto mandos_end;
548
600
  }
549
601
  
550
602
  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);
 
603
  if(af == AF_INET6){
 
604
    to.in6.sin6_family = (sa_family_t)af;
 
605
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
606
  } else {                      /* IPv4 */
 
607
    to.in.sin_family = (sa_family_t)af;
 
608
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
609
  }
555
610
  if(ret < 0 ){
 
611
    int e = errno;
556
612
    perror("inet_pton");
557
 
    return -1;
 
613
    errno = e;
 
614
    goto mandos_end;
558
615
  }
559
616
  if(ret == 0){
 
617
    int e = errno;
560
618
    fprintf(stderr, "Bad address: %s\n", ip);
561
 
    return -1;
 
619
    errno = e;
 
620
    goto mandos_end;
562
621
  }
563
 
  to.in6.sin6_port = htons(port); /* Spurious warnings from
 
622
  if(af == AF_INET6){
 
623
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
624
                                       -Wconversion and
 
625
                                       -Wunreachable-code */
 
626
    
 
627
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
628
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
629
                              -Wunreachable-code*/
 
630
      if(if_index == AVAHI_IF_UNSPEC){
 
631
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
632
                " without a network interface\n");
 
633
        errno = EINVAL;
 
634
        goto mandos_end;
 
635
      }
 
636
      /* Set the network interface number as scope */
 
637
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
638
    }
 
639
  } else {
 
640
    to.in.sin_port = htons(port); /* Spurious warnings from
564
641
                                     -Wconversion and
565
642
                                     -Wunreachable-code */
 
643
  }
566
644
  
567
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
645
  if(quit_now){
 
646
    errno = EINTR;
 
647
    goto mandos_end;
 
648
  }
568
649
  
569
650
  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){
 
651
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
 
652
      char interface[IF_NAMESIZE];
 
653
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
654
        perror("if_indextoname");
 
655
      } else {
 
656
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
657
                ip, interface, port);
 
658
      }
 
659
    } else {
 
660
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
661
              port);
 
662
    }
 
663
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
 
664
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
665
    const char *pcret;
 
666
    if(af == AF_INET6){
 
667
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
668
                        sizeof(addrstr));
 
669
    } else {
 
670
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
671
                        sizeof(addrstr));
 
672
    }
 
673
    if(pcret == NULL){
575
674
      perror("inet_ntop");
576
675
    } else {
577
676
      if(strcmp(addrstr, ip) != 0){
580
679
    }
581
680
  }
582
681
  
583
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
682
  if(quit_now){
 
683
    errno = EINTR;
 
684
    goto mandos_end;
 
685
  }
 
686
  
 
687
  if(af == AF_INET6){
 
688
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
689
  } else {
 
690
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
691
  }
584
692
  if(ret < 0){
 
693
    int e = errno;
585
694
    perror("connect");
586
 
    return -1;
 
695
    errno = e;
 
696
    goto mandos_end;
 
697
  }
 
698
  
 
699
  if(quit_now){
 
700
    errno = EINTR;
 
701
    goto mandos_end;
587
702
  }
588
703
  
589
704
  const char *out = mandos_protocol_version;
593
708
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
594
709
                                   out_size - written));
595
710
    if(ret == -1){
 
711
      int e = errno;
596
712
      perror("write");
597
 
      retval = -1;
 
713
      errno = e;
598
714
      goto mandos_end;
599
715
    }
600
716
    written += (size_t)ret;
608
724
        break;
609
725
      }
610
726
    }
 
727
  
 
728
    if(quit_now){
 
729
      errno = EINTR;
 
730
      goto mandos_end;
 
731
    }
611
732
  }
612
733
  
613
734
  if(debug){
614
735
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
615
736
  }
616
737
  
 
738
  if(quit_now){
 
739
    errno = EINTR;
 
740
    goto mandos_end;
 
741
  }
 
742
  
617
743
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
618
744
  
619
 
  do{
 
745
  if(quit_now){
 
746
    errno = EINTR;
 
747
    goto mandos_end;
 
748
  }
 
749
  
 
750
  do {
620
751
    ret = gnutls_handshake(session);
 
752
    if(quit_now){
 
753
      errno = EINTR;
 
754
      goto mandos_end;
 
755
    }
621
756
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
622
757
  
623
758
  if(ret != GNUTLS_E_SUCCESS){
625
760
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
626
761
      gnutls_perror(ret);
627
762
    }
628
 
    retval = -1;
 
763
    errno = EPROTO;
629
764
    goto mandos_end;
630
765
  }
631
766
  
632
767
  /* Read OpenPGP packet that contains the wanted password */
633
768
  
634
769
  if(debug){
635
 
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
 
770
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
636
771
            ip);
637
772
  }
638
773
  
639
774
  while(true){
 
775
    
 
776
    if(quit_now){
 
777
      errno = EINTR;
 
778
      goto mandos_end;
 
779
    }
 
780
    
640
781
    buffer_capacity = incbuffer(&buffer, buffer_length,
641
782
                                   buffer_capacity);
642
783
    if(buffer_capacity == 0){
 
784
      int e = errno;
643
785
      perror("incbuffer");
644
 
      retval = -1;
 
786
      errno = e;
 
787
      goto mandos_end;
 
788
    }
 
789
    
 
790
    if(quit_now){
 
791
      errno = EINTR;
645
792
      goto mandos_end;
646
793
    }
647
794
    
656
803
      case GNUTLS_E_AGAIN:
657
804
        break;
658
805
      case GNUTLS_E_REHANDSHAKE:
659
 
        do{
 
806
        do {
660
807
          ret = gnutls_handshake(session);
 
808
          
 
809
          if(quit_now){
 
810
            errno = EINTR;
 
811
            goto mandos_end;
 
812
          }
661
813
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
662
814
        if(ret < 0){
663
815
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
664
816
          gnutls_perror(ret);
665
 
          retval = -1;
 
817
          errno = EPROTO;
666
818
          goto mandos_end;
667
819
        }
668
820
        break;
669
821
      default:
670
822
        fprintf(stderr, "Unknown error while reading data from"
671
823
                " encrypted session with Mandos server\n");
672
 
        retval = -1;
673
824
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
825
        errno = EIO;
674
826
        goto mandos_end;
675
827
      }
676
828
    } else {
682
834
    fprintf(stderr, "Closing TLS session\n");
683
835
  }
684
836
  
685
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
837
  if(quit_now){
 
838
    errno = EINTR;
 
839
    goto mandos_end;
 
840
  }
 
841
  
 
842
  do {
 
843
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
844
    if(quit_now){
 
845
      errno = EINTR;
 
846
      goto mandos_end;
 
847
    }
 
848
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
686
849
  
687
850
  if(buffer_length > 0){
688
 
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
 
851
    ssize_t decrypted_buffer_size;
 
852
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
689
853
                                               buffer_length,
690
854
                                               &decrypted_buffer);
691
855
    if(decrypted_buffer_size >= 0){
 
856
      
692
857
      written = 0;
693
858
      while(written < (size_t) decrypted_buffer_size){
 
859
        if(quit_now){
 
860
          errno = EINTR;
 
861
          goto mandos_end;
 
862
        }
 
863
        
694
864
        ret = (int)fwrite(decrypted_buffer + written, 1,
695
865
                          (size_t)decrypted_buffer_size - written,
696
866
                          stdout);
697
867
        if(ret == 0 and ferror(stdout)){
 
868
          int e = errno;
698
869
          if(debug){
699
870
            fprintf(stderr, "Error writing encrypted data: %s\n",
700
871
                    strerror(errno));
701
872
          }
702
 
          retval = -1;
703
 
          break;
 
873
          errno = e;
 
874
          goto mandos_end;
704
875
        }
705
876
        written += (size_t)ret;
706
877
      }
707
 
      free(decrypted_buffer);
708
 
    } else {
709
 
      retval = -1;
 
878
      retval = 0;
710
879
    }
711
 
  } else {
712
 
    retval = -1;
713
880
  }
714
881
  
715
882
  /* Shutdown procedure */
716
883
  
717
884
 mandos_end:
718
 
  free(buffer);
719
 
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
720
 
  if(ret == -1){
721
 
    perror("close");
 
885
  {
 
886
    int e = errno;
 
887
    free(decrypted_buffer);
 
888
    free(buffer);
 
889
    if(tcp_sd >= 0){
 
890
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
891
    }
 
892
    if(ret == -1){
 
893
      if(e == 0){
 
894
        e = errno;
 
895
      }
 
896
      perror("close");
 
897
    }
 
898
    gnutls_deinit(session);
 
899
    if(quit_now){
 
900
      e = EINTR;
 
901
      retval = -1;
 
902
    }
 
903
    errno = e;
722
904
  }
723
 
  gnutls_deinit(session);
724
905
  return retval;
725
906
}
726
907
 
727
908
static void resolve_callback(AvahiSServiceResolver *r,
728
909
                             AvahiIfIndex interface,
729
 
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
910
                             AvahiProtocol proto,
730
911
                             AvahiResolverEvent event,
731
912
                             const char *name,
732
913
                             const char *type,
737
918
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
738
919
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
739
920
                             flags,
740
 
                             void* userdata){
741
 
  mandos_context *mc = userdata;
 
921
                             AVAHI_GCC_UNUSED void* userdata){
742
922
  assert(r);
743
923
  
744
924
  /* Called whenever a service has been resolved successfully or
745
925
     timed out */
746
926
  
 
927
  if(quit_now){
 
928
    return;
 
929
  }
 
930
  
747
931
  switch(event){
748
932
  default:
749
933
  case AVAHI_RESOLVER_FAILURE:
750
934
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
751
935
            " of type '%s' in domain '%s': %s\n", name, type, domain,
752
 
            avahi_strerror(avahi_server_errno(mc->server)));
 
936
            avahi_strerror(avahi_server_errno(mc.server)));
753
937
    break;
754
938
    
755
939
  case AVAHI_RESOLVER_FOUND:
761
945
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
762
946
                ip, (intmax_t)interface, port);
763
947
      }
764
 
      int ret = start_mandos_communication(ip, port, interface, mc);
 
948
      int ret = start_mandos_communication(ip, port, interface,
 
949
                                           avahi_proto_to_af(proto));
765
950
      if(ret == 0){
766
 
        avahi_simple_poll_quit(mc->simple_poll);
 
951
        avahi_simple_poll_quit(mc.simple_poll);
767
952
      }
768
953
    }
769
954
  }
779
964
                            const char *domain,
780
965
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
781
966
                            flags,
782
 
                            void* userdata){
783
 
  mandos_context *mc = userdata;
 
967
                            AVAHI_GCC_UNUSED void* userdata){
784
968
  assert(b);
785
969
  
786
970
  /* Called whenever a new services becomes available on the LAN or
787
971
     is removed from the LAN */
788
972
  
 
973
  if(quit_now){
 
974
    return;
 
975
  }
 
976
  
789
977
  switch(event){
790
978
  default:
791
979
  case AVAHI_BROWSER_FAILURE:
792
980
    
793
981
    fprintf(stderr, "(Avahi browser) %s\n",
794
 
            avahi_strerror(avahi_server_errno(mc->server)));
795
 
    avahi_simple_poll_quit(mc->simple_poll);
 
982
            avahi_strerror(avahi_server_errno(mc.server)));
 
983
    avahi_simple_poll_quit(mc.simple_poll);
796
984
    return;
797
985
    
798
986
  case AVAHI_BROWSER_NEW:
801
989
       the callback function is called the Avahi server will free the
802
990
       resolver for us. */
803
991
    
804
 
    if(!(avahi_s_service_resolver_new(mc->server, interface,
805
 
                                       protocol, name, type, domain,
806
 
                                       AVAHI_PROTO_INET6, 0,
807
 
                                       resolve_callback, mc)))
 
992
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
993
                                    name, type, domain, protocol, 0,
 
994
                                    resolve_callback, NULL) == NULL)
808
995
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
809
 
              name, avahi_strerror(avahi_server_errno(mc->server)));
 
996
              name, avahi_strerror(avahi_server_errno(mc.server)));
810
997
    break;
811
998
    
812
999
  case AVAHI_BROWSER_REMOVE:
821
1008
  }
822
1009
}
823
1010
 
 
1011
/* stop main loop after sigterm has been called */
 
1012
static void handle_sigterm(int sig){
 
1013
  if(quit_now){
 
1014
    return;
 
1015
  }
 
1016
  quit_now = 1;
 
1017
  signal_received = sig;
 
1018
  int old_errno = errno;
 
1019
  if(mc.simple_poll != NULL){
 
1020
    avahi_simple_poll_quit(mc.simple_poll);
 
1021
  }
 
1022
  errno = old_errno;
 
1023
}
 
1024
 
 
1025
/* 
 
1026
 * This function determines if a directory entry in /sys/class/net
 
1027
 * corresponds to an acceptable network device.
 
1028
 * (This function is passed to scandir(3) as a filter function.)
 
1029
 */
 
1030
int good_interface(const struct dirent *if_entry){
 
1031
  ssize_t ssret;
 
1032
  char *flagname = NULL;
 
1033
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1034
                     if_entry->d_name);
 
1035
  if(ret < 0){
 
1036
    perror("asprintf");
 
1037
    return 0;
 
1038
  }
 
1039
  if(if_entry->d_name[0] == '.'){
 
1040
    return 0;
 
1041
  }
 
1042
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1043
  if(flags_fd == -1){
 
1044
    perror("open");
 
1045
    return 0;
 
1046
  }
 
1047
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1048
  /* read line from flags_fd */
 
1049
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
 
1050
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1051
  flagstring[(size_t)to_read] = '\0';
 
1052
  if(flagstring == NULL){
 
1053
    perror("malloc");
 
1054
    close(flags_fd);
 
1055
    return 0;
 
1056
  }
 
1057
  while(to_read > 0){
 
1058
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1059
                                             (size_t)to_read));
 
1060
    if(ssret == -1){
 
1061
      perror("read");
 
1062
      free(flagstring);
 
1063
      close(flags_fd);
 
1064
      return 0;
 
1065
    }
 
1066
    to_read -= ssret;
 
1067
    if(ssret == 0){
 
1068
      break;
 
1069
    }
 
1070
  }
 
1071
  close(flags_fd);
 
1072
  intmax_t tmpmax;
 
1073
  char *tmp;
 
1074
  errno = 0;
 
1075
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1076
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1077
                                         and not (isspace(*tmp)))
 
1078
     or tmpmax != (ifreq_flags)tmpmax){
 
1079
    if(debug){
 
1080
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1081
              flagstring, if_entry->d_name);
 
1082
    }
 
1083
    free(flagstring);
 
1084
    return 0;
 
1085
  }
 
1086
  free(flagstring);
 
1087
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1088
  /* Reject the loopback device */
 
1089
  if(flags & IFF_LOOPBACK){
 
1090
    if(debug){
 
1091
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1092
              if_entry->d_name);
 
1093
    }
 
1094
    return 0;
 
1095
  }
 
1096
  /* Accept point-to-point devices only if connect_to is specified */
 
1097
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1098
    if(debug){
 
1099
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1100
              if_entry->d_name);
 
1101
    }
 
1102
    return 1;
 
1103
  }
 
1104
  /* Otherwise, reject non-broadcast-capable devices */
 
1105
  if(not (flags & IFF_BROADCAST)){
 
1106
    if(debug){
 
1107
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1108
              if_entry->d_name);
 
1109
    }
 
1110
    return 0;
 
1111
  }
 
1112
  /* Accept this device */
 
1113
  if(debug){
 
1114
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1115
            if_entry->d_name);
 
1116
  }
 
1117
  return 1;
 
1118
}
 
1119
 
824
1120
int main(int argc, char *argv[]){
825
1121
  AvahiSServiceBrowser *sb = NULL;
826
1122
  int error;
827
1123
  int ret;
828
1124
  intmax_t tmpmax;
829
 
  int numchars;
 
1125
  char *tmp;
830
1126
  int exitcode = EXIT_SUCCESS;
831
 
  const char *interface = "eth0";
 
1127
  const char *interface = "";
832
1128
  struct ifreq network;
833
 
  int sd;
 
1129
  int sd = -1;
 
1130
  bool take_down_interface = false;
834
1131
  uid_t uid;
835
1132
  gid_t gid;
836
 
  char *connect_to = NULL;
837
1133
  char tempdir[] = "/tmp/mandosXXXXXX";
838
1134
  bool tempdir_created = false;
839
1135
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
840
1136
  const char *seckey = PATHDIR "/" SECKEY;
841
1137
  const char *pubkey = PATHDIR "/" PUBKEY;
842
1138
  
843
 
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
844
 
                        .dh_bits = 1024, .priority = "SECURE256"
845
 
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
846
1139
  bool gnutls_initialized = false;
847
1140
  bool gpgme_initialized = false;
848
 
  double delay = 2.5;
 
1141
  float delay = 2.5f;
 
1142
  
 
1143
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
 
1144
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
 
1145
  
 
1146
  uid = getuid();
 
1147
  gid = getgid();
 
1148
  
 
1149
  /* Lower any group privileges we might have, just to be safe */
 
1150
  errno = 0;
 
1151
  ret = setgid(gid);
 
1152
  if(ret == -1){
 
1153
    perror("setgid");
 
1154
  }
 
1155
  
 
1156
  /* Lower user privileges (temporarily) */
 
1157
  errno = 0;
 
1158
  ret = seteuid(uid);
 
1159
  if(ret == -1){
 
1160
    perror("seteuid");
 
1161
  }
 
1162
  
 
1163
  if(quit_now){
 
1164
    goto end;
 
1165
  }
849
1166
  
850
1167
  {
851
1168
    struct argp_option options[] = {
857
1174
        .group = 1 },
858
1175
      { .name = "interface", .key = 'i',
859
1176
        .arg = "NAME",
860
 
        .doc = "Interface that will be used to search for Mandos"
861
 
        " servers",
 
1177
        .doc = "Network interface that will be used to search for"
 
1178
        " Mandos servers",
862
1179
        .group = 1 },
863
1180
      { .name = "seckey", .key = 's',
864
1181
        .arg = "FILE",
881
1198
        .arg = "SECONDS",
882
1199
        .doc = "Maximum delay to wait for interface startup",
883
1200
        .group = 2 },
 
1201
      /*
 
1202
       * These reproduce what we would get without ARGP_NO_HELP
 
1203
       */
 
1204
      { .name = "help", .key = '?',
 
1205
        .doc = "Give this help list", .group = -1 },
 
1206
      { .name = "usage", .key = -3,
 
1207
        .doc = "Give a short usage message", .group = -1 },
 
1208
      { .name = "version", .key = 'V',
 
1209
        .doc = "Print program version", .group = -1 },
884
1210
      { .name = NULL }
885
1211
    };
886
1212
    
887
1213
    error_t parse_opt(int key, char *arg,
888
1214
                      struct argp_state *state){
 
1215
      errno = 0;
889
1216
      switch(key){
890
1217
      case 128:                 /* --debug */
891
1218
        debug = true;
903
1230
        pubkey = arg;
904
1231
        break;
905
1232
      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);
 
1233
        errno = 0;
 
1234
        tmpmax = strtoimax(arg, &tmp, 10);
 
1235
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1236
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
 
1237
          argp_error(state, "Bad number of DH bits");
911
1238
        }
912
1239
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
913
1240
        break;
915
1242
        mc.priority = arg;
916
1243
        break;
917
1244
      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);
 
1245
        errno = 0;
 
1246
        delay = strtof(arg, &tmp);
 
1247
        if(errno != 0 or tmp == arg or *tmp != '\0'){
 
1248
          argp_error(state, "Bad delay");
922
1249
        }
923
1250
        break;
924
 
      case ARGP_KEY_ARG:
925
 
        argp_usage(state);
926
 
      case ARGP_KEY_END:
 
1251
        /*
 
1252
         * These reproduce what we would get without ARGP_NO_HELP
 
1253
         */
 
1254
      case '?':                 /* --help */
 
1255
        argp_state_help(state, state->out_stream,
 
1256
                        (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR)
 
1257
                        & ~(unsigned int)ARGP_HELP_EXIT_OK);
 
1258
      case -3:                  /* --usage */
 
1259
        argp_state_help(state, state->out_stream,
 
1260
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
 
1261
      case 'V':                 /* --version */
 
1262
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1263
        exit(argp_err_exit_status);
927
1264
        break;
928
1265
      default:
929
1266
        return ARGP_ERR_UNKNOWN;
930
1267
      }
931
 
      return 0;
 
1268
      return errno;
932
1269
    }
933
1270
    
934
1271
    struct argp argp = { .options = options, .parser = parse_opt,
935
1272
                         .args_doc = "",
936
1273
                         .doc = "Mandos client -- Get and decrypt"
937
1274
                         " 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");
 
1275
    ret = argp_parse(&argp, argc, argv,
 
1276
                     ARGP_IN_ORDER | ARGP_NO_HELP, 0, NULL);
 
1277
    switch(ret){
 
1278
    case 0:
 
1279
      break;
 
1280
    case ENOMEM:
 
1281
    default:
 
1282
      errno = ret;
 
1283
      perror("argp_parse");
 
1284
      exitcode = EX_OSERR;
 
1285
      goto end;
 
1286
    case EINVAL:
 
1287
      exitcode = EX_USAGE;
 
1288
      goto end;
 
1289
    }
 
1290
  }
 
1291
  
 
1292
  if(not debug){
 
1293
    avahi_set_log_function(empty_log);
 
1294
  }
 
1295
 
 
1296
  if(interface[0] == '\0'){
 
1297
    struct dirent **direntries;
 
1298
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1299
                  alphasort);
 
1300
    if(ret >= 1){
 
1301
      /* Pick the first good interface */
 
1302
      interface = strdup(direntries[0]->d_name);
 
1303
      if(debug){
 
1304
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1305
      }
 
1306
      if(interface == NULL){
 
1307
        perror("malloc");
 
1308
        free(direntries);
 
1309
        exitcode = EXIT_FAILURE;
 
1310
        goto end;
 
1311
      }
 
1312
      free(direntries);
 
1313
    } else {
 
1314
      free(direntries);
 
1315
      fprintf(stderr, "Could not find a network interface\n");
941
1316
      exitcode = EXIT_FAILURE;
942
1317
      goto end;
943
1318
    }
944
1319
  }
945
1320
  
 
1321
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
 
1322
     from the signal handler */
 
1323
  /* Initialize the pseudo-RNG for Avahi */
 
1324
  srand((unsigned int) time(NULL));
 
1325
  mc.simple_poll = avahi_simple_poll_new();
 
1326
  if(mc.simple_poll == NULL){
 
1327
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1328
    exitcode = EX_UNAVAILABLE;
 
1329
    goto end;
 
1330
  }
 
1331
  
 
1332
  sigemptyset(&sigterm_action.sa_mask);
 
1333
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
 
1334
  if(ret == -1){
 
1335
    perror("sigaddset");
 
1336
    exitcode = EX_OSERR;
 
1337
    goto end;
 
1338
  }
 
1339
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
 
1340
  if(ret == -1){
 
1341
    perror("sigaddset");
 
1342
    exitcode = EX_OSERR;
 
1343
    goto end;
 
1344
  }
 
1345
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
 
1346
  if(ret == -1){
 
1347
    perror("sigaddset");
 
1348
    exitcode = EX_OSERR;
 
1349
    goto end;
 
1350
  }
 
1351
  /* Need to check if the handler is SIG_IGN before handling:
 
1352
     | [[info:libc:Initial Signal Actions]] |
 
1353
     | [[info:libc:Basic Signal Handling]]  |
 
1354
  */
 
1355
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
 
1356
  if(ret == -1){
 
1357
    perror("sigaction");
 
1358
    return EX_OSERR;
 
1359
  }
 
1360
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1361
    ret = sigaction(SIGINT, &sigterm_action, NULL);
 
1362
    if(ret == -1){
 
1363
      perror("sigaction");
 
1364
      exitcode = EX_OSERR;
 
1365
      goto end;
 
1366
    }
 
1367
  }
 
1368
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
 
1369
  if(ret == -1){
 
1370
    perror("sigaction");
 
1371
    return EX_OSERR;
 
1372
  }
 
1373
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1374
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
 
1375
    if(ret == -1){
 
1376
      perror("sigaction");
 
1377
      exitcode = EX_OSERR;
 
1378
      goto end;
 
1379
    }
 
1380
  }
 
1381
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
 
1382
  if(ret == -1){
 
1383
    perror("sigaction");
 
1384
    return EX_OSERR;
 
1385
  }
 
1386
  if(old_sigterm_action.sa_handler != SIG_IGN){
 
1387
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
 
1388
    if(ret == -1){
 
1389
      perror("sigaction");
 
1390
      exitcode = EX_OSERR;
 
1391
      goto end;
 
1392
    }
 
1393
  }
 
1394
  
946
1395
  /* If the interface is down, bring it up */
947
 
  {
 
1396
  if(strcmp(interface, "none") != 0){
 
1397
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1398
    if(if_index == 0){
 
1399
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1400
      exitcode = EX_UNAVAILABLE;
 
1401
      goto end;
 
1402
    }
 
1403
    
 
1404
    if(quit_now){
 
1405
      goto end;
 
1406
    }
 
1407
    
 
1408
    /* Re-raise priviliges */
 
1409
    errno = 0;
 
1410
    ret = seteuid(0);
 
1411
    if(ret == -1){
 
1412
      perror("seteuid");
 
1413
    }
 
1414
    
948
1415
#ifdef __linux__
949
1416
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
950
 
       messages to mess up the prompt */
 
1417
       messages about the network interface to mess up the prompt */
951
1418
    ret = klogctl(8, NULL, 5);
 
1419
    bool restore_loglevel = true;
952
1420
    if(ret == -1){
 
1421
      restore_loglevel = false;
953
1422
      perror("klogctl");
954
1423
    }
955
 
#endif
 
1424
#endif  /* __linux__ */
956
1425
    
957
1426
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
958
1427
    if(sd < 0){
959
1428
      perror("socket");
960
 
      exitcode = EXIT_FAILURE;
 
1429
      exitcode = EX_OSERR;
961
1430
#ifdef __linux__
962
 
      ret = klogctl(7, NULL, 0);
 
1431
      if(restore_loglevel){
 
1432
        ret = klogctl(7, NULL, 0);
 
1433
        if(ret == -1){
 
1434
          perror("klogctl");
 
1435
        }
 
1436
      }
 
1437
#endif  /* __linux__ */
 
1438
      /* Lower privileges */
 
1439
      errno = 0;
 
1440
      ret = seteuid(uid);
963
1441
      if(ret == -1){
964
 
        perror("klogctl");
 
1442
        perror("seteuid");
965
1443
      }
966
 
#endif
967
1444
      goto end;
968
1445
    }
969
1446
    strcpy(network.ifr_name, interface);
971
1448
    if(ret == -1){
972
1449
      perror("ioctl SIOCGIFFLAGS");
973
1450
#ifdef __linux__
974
 
      ret = klogctl(7, NULL, 0);
 
1451
      if(restore_loglevel){
 
1452
        ret = klogctl(7, NULL, 0);
 
1453
        if(ret == -1){
 
1454
          perror("klogctl");
 
1455
        }
 
1456
      }
 
1457
#endif  /* __linux__ */
 
1458
      exitcode = EX_OSERR;
 
1459
      /* Lower privileges */
 
1460
      errno = 0;
 
1461
      ret = seteuid(uid);
975
1462
      if(ret == -1){
976
 
        perror("klogctl");
 
1463
        perror("seteuid");
977
1464
      }
978
 
#endif
979
 
      exitcode = EXIT_FAILURE;
980
1465
      goto end;
981
1466
    }
982
1467
    if((network.ifr_flags & IFF_UP) == 0){
983
1468
      network.ifr_flags |= IFF_UP;
 
1469
      take_down_interface = true;
984
1470
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
985
1471
      if(ret == -1){
986
 
        perror("ioctl SIOCSIFFLAGS");
987
 
        exitcode = EXIT_FAILURE;
 
1472
        take_down_interface = false;
 
1473
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
 
1474
        exitcode = EX_OSERR;
988
1475
#ifdef __linux__
989
 
        ret = klogctl(7, NULL, 0);
 
1476
        if(restore_loglevel){
 
1477
          ret = klogctl(7, NULL, 0);
 
1478
          if(ret == -1){
 
1479
            perror("klogctl");
 
1480
          }
 
1481
        }
 
1482
#endif  /* __linux__ */
 
1483
        /* Lower privileges */
 
1484
        errno = 0;
 
1485
        ret = seteuid(uid);
990
1486
        if(ret == -1){
991
 
          perror("klogctl");
 
1487
          perror("seteuid");
992
1488
        }
993
 
#endif
994
1489
        goto end;
995
1490
      }
996
1491
    }
1008
1503
        perror("nanosleep");
1009
1504
      }
1010
1505
    }
1011
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1012
 
    if(ret == -1){
1013
 
      perror("close");
 
1506
    if(not take_down_interface){
 
1507
      /* We won't need the socket anymore */
 
1508
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1509
      if(ret == -1){
 
1510
        perror("close");
 
1511
      }
1014
1512
    }
1015
1513
#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);
 
1514
    if(restore_loglevel){
 
1515
      /* Restores kernel loglevel to default */
 
1516
      ret = klogctl(7, NULL, 0);
 
1517
      if(ret == -1){
 
1518
        perror("klogctl");
 
1519
      }
 
1520
    }
 
1521
#endif  /* __linux__ */
 
1522
    /* Lower privileges */
 
1523
    errno = 0;
 
1524
    if(take_down_interface){
 
1525
      /* Lower privileges */
 
1526
      ret = seteuid(uid);
 
1527
      if(ret == -1){
 
1528
        perror("seteuid");
 
1529
      }
 
1530
    } else {
 
1531
      /* Lower privileges permanently */
 
1532
      ret = setuid(uid);
 
1533
      if(ret == -1){
 
1534
        perror("setuid");
 
1535
      }
 
1536
    }
 
1537
  }
 
1538
  
 
1539
  if(quit_now){
 
1540
    goto end;
 
1541
  }
 
1542
  
 
1543
  ret = init_gnutls_global(pubkey, seckey);
1038
1544
  if(ret == -1){
1039
1545
    fprintf(stderr, "init_gnutls_global failed\n");
1040
 
    exitcode = EXIT_FAILURE;
 
1546
    exitcode = EX_UNAVAILABLE;
1041
1547
    goto end;
1042
1548
  } else {
1043
1549
    gnutls_initialized = true;
1044
1550
  }
1045
1551
  
 
1552
  if(quit_now){
 
1553
    goto end;
 
1554
  }
 
1555
  
 
1556
  tempdir_created = true;
1046
1557
  if(mkdtemp(tempdir) == NULL){
 
1558
    tempdir_created = false;
1047
1559
    perror("mkdtemp");
1048
1560
    goto end;
1049
1561
  }
1050
 
  tempdir_created = true;
1051
 
  
1052
 
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
 
1562
  
 
1563
  if(quit_now){
 
1564
    goto end;
 
1565
  }
 
1566
  
 
1567
  if(not init_gpgme(pubkey, seckey, tempdir)){
1053
1568
    fprintf(stderr, "init_gpgme failed\n");
1054
 
    exitcode = EXIT_FAILURE;
 
1569
    exitcode = EX_UNAVAILABLE;
1055
1570
    goto end;
1056
1571
  } else {
1057
1572
    gpgme_initialized = true;
1058
1573
  }
1059
1574
  
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;
 
1575
  if(quit_now){
1064
1576
    goto end;
1065
1577
  }
1066
1578
  
1070
1582
    char *address = strrchr(connect_to, ':');
1071
1583
    if(address == NULL){
1072
1584
      fprintf(stderr, "No colon in address\n");
1073
 
      exitcode = EXIT_FAILURE;
1074
 
      goto end;
1075
 
    }
 
1585
      exitcode = EX_USAGE;
 
1586
      goto end;
 
1587
    }
 
1588
    
 
1589
    if(quit_now){
 
1590
      goto end;
 
1591
    }
 
1592
    
1076
1593
    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'){
 
1594
    errno = 0;
 
1595
    tmpmax = strtoimax(address+1, &tmp, 10);
 
1596
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
 
1597
       or tmpmax != (uint16_t)tmpmax){
1080
1598
      fprintf(stderr, "Bad port number\n");
1081
 
      exitcode = EXIT_FAILURE;
1082
 
      goto end;
1083
 
    }
 
1599
      exitcode = EX_USAGE;
 
1600
      goto end;
 
1601
    }
 
1602
  
 
1603
    if(quit_now){
 
1604
      goto end;
 
1605
    }
 
1606
    
1084
1607
    port = (uint16_t)tmpmax;
1085
1608
    *address = '\0';
1086
1609
    address = connect_to;
1087
 
    ret = start_mandos_communication(address, port, if_index, &mc);
 
1610
    /* Colon in address indicates IPv6 */
 
1611
    int af;
 
1612
    if(strchr(address, ':') != NULL){
 
1613
      af = AF_INET6;
 
1614
    } else {
 
1615
      af = AF_INET;
 
1616
    }
 
1617
    
 
1618
    if(quit_now){
 
1619
      goto end;
 
1620
    }
 
1621
    
 
1622
    ret = start_mandos_communication(address, port, if_index, af);
1088
1623
    if(ret < 0){
1089
 
      exitcode = EXIT_FAILURE;
 
1624
      switch(errno){
 
1625
      case ENETUNREACH:
 
1626
      case EHOSTDOWN:
 
1627
      case EHOSTUNREACH:
 
1628
        exitcode = EX_NOHOST;
 
1629
        break;
 
1630
      case EINVAL:
 
1631
        exitcode = EX_USAGE;
 
1632
        break;
 
1633
      case EIO:
 
1634
        exitcode = EX_IOERR;
 
1635
        break;
 
1636
      case EPROTO:
 
1637
        exitcode = EX_PROTOCOL;
 
1638
        break;
 
1639
      default:
 
1640
        exitcode = EX_OSERR;
 
1641
        break;
 
1642
      }
1090
1643
    } else {
1091
1644
      exitcode = EXIT_SUCCESS;
1092
1645
    }
1093
1646
    goto end;
1094
1647
  }
1095
1648
  
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;
 
1649
  if(quit_now){
1108
1650
    goto end;
1109
1651
  }
1110
1652
  
1130
1672
  if(mc.server == NULL){
1131
1673
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1132
1674
            avahi_strerror(error));
1133
 
    exitcode = EXIT_FAILURE;
 
1675
    exitcode = EX_UNAVAILABLE;
 
1676
    goto end;
 
1677
  }
 
1678
  
 
1679
  if(quit_now){
1134
1680
    goto end;
1135
1681
  }
1136
1682
  
1137
1683
  /* Create the Avahi service browser */
1138
1684
  sb = avahi_s_service_browser_new(mc.server, if_index,
1139
 
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
1140
 
                                   NULL, 0, browse_callback, &mc);
 
1685
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
 
1686
                                   NULL, 0, browse_callback, NULL);
1141
1687
  if(sb == NULL){
1142
1688
    fprintf(stderr, "Failed to create service browser: %s\n",
1143
1689
            avahi_strerror(avahi_server_errno(mc.server)));
1144
 
    exitcode = EXIT_FAILURE;
 
1690
    exitcode = EX_UNAVAILABLE;
 
1691
    goto end;
 
1692
  }
 
1693
  
 
1694
  if(quit_now){
1145
1695
    goto end;
1146
1696
  }
1147
1697
  
1179
1729
    gpgme_release(mc.ctx);
1180
1730
  }
1181
1731
  
 
1732
  /* Take down the network interface */
 
1733
  if(take_down_interface){
 
1734
    /* Re-raise priviliges */
 
1735
    errno = 0;
 
1736
    ret = seteuid(0);
 
1737
    if(ret == -1){
 
1738
      perror("seteuid");
 
1739
    }
 
1740
    if(geteuid() == 0){
 
1741
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1742
      if(ret == -1){
 
1743
        perror("ioctl SIOCGIFFLAGS");
 
1744
      } else if(network.ifr_flags & IFF_UP) {
 
1745
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1746
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1747
        if(ret == -1){
 
1748
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
 
1749
        }
 
1750
      }
 
1751
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1752
      if(ret == -1){
 
1753
        perror("close");
 
1754
      }
 
1755
      /* Lower privileges permanently */
 
1756
      errno = 0;
 
1757
      ret = setuid(uid);
 
1758
      if(ret == -1){
 
1759
        perror("setuid");
 
1760
      }
 
1761
    }
 
1762
  }
 
1763
  
1182
1764
  /* Removes the temp directory used by GPGME */
1183
1765
  if(tempdir_created){
1184
1766
    DIR *d;
1223
1805
    }
1224
1806
  }
1225
1807
  
 
1808
  if(quit_now){
 
1809
    sigemptyset(&old_sigterm_action.sa_mask);
 
1810
    old_sigterm_action.sa_handler = SIG_DFL;
 
1811
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
 
1812
                                            &old_sigterm_action,
 
1813
                                            NULL));
 
1814
    if(ret == -1){
 
1815
      perror("sigaction");
 
1816
    }
 
1817
    do {
 
1818
      ret = raise(signal_received);
 
1819
    } while(ret != 0 and errno == EINTR);
 
1820
    if(ret != 0){
 
1821
      perror("raise");
 
1822
      abort();
 
1823
    }
 
1824
    TEMP_FAILURE_RETRY(pause());
 
1825
  }
 
1826
  
1226
1827
  return exitcode;
1227
1828
}