/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-02-07 03:28:24 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090207032824-5eg756uscdr3gend
* initramfs-tools-hook: Also fix /lib<qual> and /usr/lib<qual>
                        directories.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
/*  -*- coding: utf-8 -*- */
2
2
/*
3
 
 * Mandos client - get and decrypt data from a Mandos server
 
3
 * Mandos-client - get and decrypt data from a Mandos server
4
4
 *
5
5
 * This program is partly derived from an example program for an Avahi
6
6
 * service browser, downloaded from
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2007-2008 Teddy Hogeborn & Björn Påhlsson
 
12
 * Copyright © 2008,2009 Teddy Hogeborn
 
13
 * Copyright © 2008,2009 Björn Påhlsson
13
14
 * 
14
15
 * This program is free software: you can redistribute it and/or
15
16
 * modify it under the terms of the GNU General Public License as
35
36
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
36
37
 
37
38
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
38
 
                                   stdout, ferror() */
 
39
                                   stdout, ferror(), sscanf(),
 
40
                                   remove() */
39
41
#include <stdint.h>             /* uint16_t, uint32_t */
40
42
#include <stddef.h>             /* NULL, size_t, ssize_t */
41
43
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
47
49
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
48
50
                                   sockaddr_in6, PF_INET6,
49
51
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
50
 
                                   uid_t, gid_t, open(), opendir(), DIR */
 
52
                                   uid_t, gid_t, open(), opendir(),
 
53
                                   DIR */
51
54
#include <sys/stat.h>           /* open() */
52
55
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
53
56
                                   struct in6_addr, inet_pton(),
54
57
                                   connect() */
55
58
#include <fcntl.h>              /* open() */
56
 
#include <dirent.h>             /* opendir(), struct dirent, readdir() */
57
 
#include <inttypes.h>           /* PRIu16 */
 
59
#include <dirent.h>             /* opendir(), struct dirent, readdir()
 
60
                                 */
 
61
#include <inttypes.h>           /* PRIu16, intmax_t, SCNdMAX */
58
62
#include <assert.h>             /* assert() */
59
63
#include <errno.h>              /* perror(), errno */
60
 
#include <time.h>               /* time() */
 
64
#include <time.h>               /* nanosleep(), time() */
61
65
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
62
66
                                   SIOCSIFFLAGS, if_indextoname(),
63
67
                                   if_nametoindex(), IF_NAMESIZE */
66
70
                                   getuid(), getgid(), setuid(),
67
71
                                   setgid() */
68
72
#include <arpa/inet.h>          /* inet_pton(), htons */
69
 
#include <iso646.h>             /* not, and */
 
73
#include <iso646.h>             /* not, and, or */
70
74
#include <argp.h>               /* struct argp_option, error_t, struct
71
75
                                   argp_state, struct argp,
72
76
                                   argp_parse(), ARGP_KEY_ARG,
73
77
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
78
#ifdef __linux__
 
79
#include <sys/klog.h>           /* klogctl() */
 
80
#endif
74
81
 
75
82
/* Avahi */
76
83
/* All Avahi types, constants and functions
89
96
                                   gnutls_*
90
97
                                   init_gnutls_session(),
91
98
                                   GNUTLS_* */
92
 
#include <gnutls/openpgp.h>     /* gnutls_certificate_set_openpgp_key_file(),
 
99
#include <gnutls/openpgp.h>
 
100
                          /* gnutls_certificate_set_openpgp_key_file(),
93
101
                                   GNUTLS_OPENPGP_FMT_BASE64 */
94
102
 
95
103
/* GPGME */
101
109
 
102
110
#define BUFFER_SIZE 256
103
111
 
104
 
/*
105
 
  #define PATHDIR "/conf/conf.d/mandos"
106
 
*/
107
 
 
108
112
#define PATHDIR "/conf/conf.d/mandos"
109
113
#define SECKEY "seckey.txt"
110
 
#define PUBKEY "pupkey.txt"
 
114
#define PUBKEY "pubkey.txt"
111
115
 
112
116
bool debug = false;
113
117
static const char mandos_protocol_version[] = "1";
114
 
const char *argp_program_version = "password-request 1.0";
 
118
const char *argp_program_version = "mandos-client " VERSION;
115
119
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
116
120
 
117
121
/* Used for passing in values through the Avahi callback functions */
132
136
 */
133
137
size_t adjustbuffer(char **buffer, size_t buffer_length,
134
138
                  size_t buffer_capacity){
135
 
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
 
139
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
136
140
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
137
 
    if (buffer == NULL){
 
141
    if(buffer == NULL){
138
142
      return 0;
139
143
    }
140
144
    buffer_capacity += BUFFER_SIZE;
150
154
  int ret;
151
155
  gpgme_error_t rc;
152
156
  gpgme_engine_info_t engine_info;
153
 
 
 
157
  
154
158
  
155
159
  /*
156
 
   * Helper function to insert pub and seckey to the enigne keyring.
 
160
   * Helper function to insert pub and seckey to the engine keyring.
157
161
   */
158
162
  bool import_key(const char *filename){
159
163
    int fd;
160
164
    gpgme_data_t pgp_data;
161
165
    
162
 
    fd = TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
 
166
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
163
167
    if(fd == -1){
164
168
      perror("open");
165
169
      return false;
166
170
    }
167
171
    
168
172
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
169
 
    if (rc != GPG_ERR_NO_ERROR){
 
173
    if(rc != GPG_ERR_NO_ERROR){
170
174
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
171
175
              gpgme_strsource(rc), gpgme_strerror(rc));
172
176
      return false;
173
177
    }
174
 
 
 
178
    
175
179
    rc = gpgme_op_import(mc->ctx, pgp_data);
176
 
    if (rc != GPG_ERR_NO_ERROR){
 
180
    if(rc != GPG_ERR_NO_ERROR){
177
181
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
178
182
              gpgme_strsource(rc), gpgme_strerror(rc));
179
183
      return false;
180
184
    }
181
 
 
182
 
    ret = TEMP_FAILURE_RETRY(close(fd));
 
185
    
 
186
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
183
187
    if(ret == -1){
184
188
      perror("close");
185
189
    }
187
191
    return true;
188
192
  }
189
193
  
190
 
  if (debug){
 
194
  if(debug){
191
195
    fprintf(stderr, "Initialize gpgme\n");
192
196
  }
193
 
 
 
197
  
194
198
  /* Init GPGME */
195
199
  gpgme_check_version(NULL);
196
200
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
197
 
  if (rc != GPG_ERR_NO_ERROR){
 
201
  if(rc != GPG_ERR_NO_ERROR){
198
202
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
199
203
            gpgme_strsource(rc), gpgme_strerror(rc));
200
204
    return false;
201
205
  }
202
 
 
 
206
  
203
207
    /* Set GPGME home directory for the OpenPGP engine only */
204
 
  rc = gpgme_get_engine_info (&engine_info);
205
 
  if (rc != GPG_ERR_NO_ERROR){
 
208
  rc = gpgme_get_engine_info(&engine_info);
 
209
  if(rc != GPG_ERR_NO_ERROR){
206
210
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
207
211
            gpgme_strsource(rc), gpgme_strerror(rc));
208
212
    return false;
219
223
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
220
224
    return false;
221
225
  }
222
 
 
 
226
  
223
227
  /* Create new GPGME "context" */
224
228
  rc = gpgme_new(&(mc->ctx));
225
 
  if (rc != GPG_ERR_NO_ERROR){
 
229
  if(rc != GPG_ERR_NO_ERROR){
226
230
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
227
231
            gpgme_strsource(rc), gpgme_strerror(rc));
228
232
    return false;
229
233
  }
230
234
  
231
 
  if (not import_key(pubkey) or not import_key(seckey)){
 
235
  if(not import_key(pubkey) or not import_key(seckey)){
232
236
    return false;
233
237
  }
234
238
  
239
243
 * Decrypt OpenPGP data.
240
244
 * Returns -1 on error
241
245
 */
242
 
static ssize_t pgp_packet_decrypt (const mandos_context *mc,
243
 
                                   const char *cryptotext,
244
 
                                   size_t crypto_size,
245
 
                                   char **plaintext){
 
246
static ssize_t pgp_packet_decrypt(const mandos_context *mc,
 
247
                                  const char *cryptotext,
 
248
                                  size_t crypto_size,
 
249
                                  char **plaintext){
246
250
  gpgme_data_t dh_crypto, dh_plain;
247
251
  gpgme_error_t rc;
248
252
  ssize_t ret;
249
253
  size_t plaintext_capacity = 0;
250
254
  ssize_t plaintext_length = 0;
251
255
  
252
 
  if (debug){
 
256
  if(debug){
253
257
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
254
258
  }
255
259
  
256
260
  /* Create new GPGME data buffer from memory cryptotext */
257
261
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
258
262
                               0);
259
 
  if (rc != GPG_ERR_NO_ERROR){
 
263
  if(rc != GPG_ERR_NO_ERROR){
260
264
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
261
265
            gpgme_strsource(rc), gpgme_strerror(rc));
262
266
    return -1;
264
268
  
265
269
  /* Create new empty GPGME data buffer for the plaintext */
266
270
  rc = gpgme_data_new(&dh_plain);
267
 
  if (rc != GPG_ERR_NO_ERROR){
 
271
  if(rc != GPG_ERR_NO_ERROR){
268
272
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
269
273
            gpgme_strsource(rc), gpgme_strerror(rc));
270
274
    gpgme_data_release(dh_crypto);
274
278
  /* Decrypt data from the cryptotext data buffer to the plaintext
275
279
     data buffer */
276
280
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
277
 
  if (rc != GPG_ERR_NO_ERROR){
 
281
  if(rc != GPG_ERR_NO_ERROR){
278
282
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
279
283
            gpgme_strsource(rc), gpgme_strerror(rc));
280
284
    plaintext_length = -1;
281
 
    if (debug){
 
285
    if(debug){
282
286
      gpgme_decrypt_result_t result;
283
287
      result = gpgme_op_decrypt_result(mc->ctx);
284
 
      if (result == NULL){
 
288
      if(result == NULL){
285
289
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
286
290
      } else {
287
291
        fprintf(stderr, "Unsupported algorithm: %s\n",
314
318
  }
315
319
  
316
320
  /* Seek back to the beginning of the GPGME plaintext data buffer */
317
 
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
318
 
    perror("pgpme_data_seek");
 
321
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
 
322
    perror("gpgme_data_seek");
319
323
    plaintext_length = -1;
320
324
    goto decrypt_end;
321
325
  }
325
329
    plaintext_capacity = adjustbuffer(plaintext,
326
330
                                      (size_t)plaintext_length,
327
331
                                      plaintext_capacity);
328
 
    if (plaintext_capacity == 0){
 
332
    if(plaintext_capacity == 0){
329
333
        perror("adjustbuffer");
330
334
        plaintext_length = -1;
331
335
        goto decrypt_end;
334
338
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
335
339
                          BUFFER_SIZE);
336
340
    /* Print the data, if any */
337
 
    if (ret == 0){
 
341
    if(ret == 0){
338
342
      /* EOF */
339
343
      break;
340
344
    }
364
368
  return plaintext_length;
365
369
}
366
370
 
367
 
static const char * safer_gnutls_strerror (int value) {
368
 
  const char *ret = gnutls_strerror (value); /* Spurious warning */
369
 
  if (ret == NULL)
 
371
static const char * safer_gnutls_strerror(int value){
 
372
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
373
                                               -Wunreachable-code */
 
374
  if(ret == NULL)
370
375
    ret = "(unknown)";
371
376
  return ret;
372
377
}
387
392
  }
388
393
  
389
394
  ret = gnutls_global_init();
390
 
  if (ret != GNUTLS_E_SUCCESS) {
391
 
    fprintf (stderr, "GnuTLS global_init: %s\n",
392
 
             safer_gnutls_strerror(ret));
 
395
  if(ret != GNUTLS_E_SUCCESS){
 
396
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
397
            safer_gnutls_strerror(ret));
393
398
    return -1;
394
399
  }
395
400
  
396
 
  if (debug){
 
401
  if(debug){
397
402
    /* "Use a log level over 10 to enable all debugging options."
398
403
     * - GnuTLS manual
399
404
     */
403
408
  
404
409
  /* OpenPGP credentials */
405
410
  gnutls_certificate_allocate_credentials(&mc->cred);
406
 
  if (ret != GNUTLS_E_SUCCESS){
407
 
    fprintf (stderr, "GnuTLS memory error: %s\n", /* Spurious
408
 
                                                     warning */
409
 
             safer_gnutls_strerror(ret));
410
 
    gnutls_global_deinit ();
 
411
  if(ret != GNUTLS_E_SUCCESS){
 
412
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
413
                                                  * from
 
414
                                                  * -Wunreachable-code
 
415
                                                  */
 
416
            safer_gnutls_strerror(ret));
 
417
    gnutls_global_deinit();
411
418
    return -1;
412
419
  }
413
420
  
420
427
  ret = gnutls_certificate_set_openpgp_key_file
421
428
    (mc->cred, pubkeyfilename, seckeyfilename,
422
429
     GNUTLS_OPENPGP_FMT_BASE64);
423
 
  if (ret != GNUTLS_E_SUCCESS) {
 
430
  if(ret != GNUTLS_E_SUCCESS){
424
431
    fprintf(stderr,
425
432
            "Error[%d] while reading the OpenPGP key pair ('%s',"
426
433
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
431
438
  
432
439
  /* GnuTLS server initialization */
433
440
  ret = gnutls_dh_params_init(&mc->dh_params);
434
 
  if (ret != GNUTLS_E_SUCCESS) {
435
 
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
436
 
             " %s\n", safer_gnutls_strerror(ret));
 
441
  if(ret != GNUTLS_E_SUCCESS){
 
442
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
443
            " %s\n", safer_gnutls_strerror(ret));
437
444
    goto globalfail;
438
445
  }
439
446
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
440
 
  if (ret != GNUTLS_E_SUCCESS) {
441
 
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
442
 
             safer_gnutls_strerror(ret));
 
447
  if(ret != GNUTLS_E_SUCCESS){
 
448
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
449
            safer_gnutls_strerror(ret));
443
450
    goto globalfail;
444
451
  }
445
452
  
451
458
  
452
459
  gnutls_certificate_free_credentials(mc->cred);
453
460
  gnutls_global_deinit();
 
461
  gnutls_dh_params_deinit(mc->dh_params);
454
462
  return -1;
455
463
}
456
464
 
459
467
  int ret;
460
468
  /* GnuTLS session creation */
461
469
  ret = gnutls_init(session, GNUTLS_SERVER);
462
 
  if (ret != GNUTLS_E_SUCCESS){
 
470
  if(ret != GNUTLS_E_SUCCESS){
463
471
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
464
472
            safer_gnutls_strerror(ret));
465
473
  }
467
475
  {
468
476
    const char *err;
469
477
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
470
 
    if (ret != GNUTLS_E_SUCCESS) {
 
478
    if(ret != GNUTLS_E_SUCCESS){
471
479
      fprintf(stderr, "Syntax error at: %s\n", err);
472
480
      fprintf(stderr, "GnuTLS error: %s\n",
473
481
              safer_gnutls_strerror(ret));
474
 
      gnutls_deinit (*session);
 
482
      gnutls_deinit(*session);
475
483
      return -1;
476
484
    }
477
485
  }
478
486
  
479
487
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
480
488
                               mc->cred);
481
 
  if (ret != GNUTLS_E_SUCCESS) {
 
489
  if(ret != GNUTLS_E_SUCCESS){
482
490
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
483
491
            safer_gnutls_strerror(ret));
484
 
    gnutls_deinit (*session);
 
492
    gnutls_deinit(*session);
485
493
    return -1;
486
494
  }
487
495
  
488
496
  /* ignore client certificate if any. */
489
 
  gnutls_certificate_server_set_request (*session,
490
 
                                         GNUTLS_CERT_IGNORE);
 
497
  gnutls_certificate_server_set_request(*session,
 
498
                                        GNUTLS_CERT_IGNORE);
491
499
  
492
 
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
 
500
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
493
501
  
494
502
  return 0;
495
503
}
503
511
                                      AvahiIfIndex if_index,
504
512
                                      mandos_context *mc){
505
513
  int ret, tcp_sd;
 
514
  ssize_t sret;
506
515
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
507
516
  char *buffer = NULL;
508
517
  char *decrypted_buffer;
514
523
  char interface[IF_NAMESIZE];
515
524
  gnutls_session_t session;
516
525
  
517
 
  ret = init_gnutls_session (mc, &session);
518
 
  if (ret != 0){
 
526
  ret = init_gnutls_session(mc, &session);
 
527
  if(ret != 0){
519
528
    return -1;
520
529
  }
521
530
  
525
534
  }
526
535
  
527
536
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
528
 
  if(tcp_sd < 0) {
 
537
  if(tcp_sd < 0){
529
538
    perror("socket");
530
539
    return -1;
531
540
  }
543
552
  /* It would be nice to have a way to detect if we were passed an
544
553
     IPv4 address here.   Now we assume an IPv6 address. */
545
554
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
546
 
  if (ret < 0 ){
 
555
  if(ret < 0 ){
547
556
    perror("inet_pton");
548
557
    return -1;
549
558
  }
551
560
    fprintf(stderr, "Bad address: %s\n", ip);
552
561
    return -1;
553
562
  }
554
 
  to.in6.sin6_port = htons(port); /* Spurious warning */
 
563
  to.in6.sin6_port = htons(port); /* Spurious warnings from
 
564
                                     -Wconversion and
 
565
                                     -Wunreachable-code */
555
566
  
556
567
  to.in6.sin6_scope_id = (uint32_t)if_index;
557
568
  
570
581
  }
571
582
  
572
583
  ret = connect(tcp_sd, &to.in, sizeof(to));
573
 
  if (ret < 0){
 
584
  if(ret < 0){
574
585
    perror("connect");
575
586
    return -1;
576
587
  }
577
588
  
578
589
  const char *out = mandos_protocol_version;
579
590
  written = 0;
580
 
  while (true){
 
591
  while(true){
581
592
    size_t out_size = strlen(out);
582
 
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
 
593
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
583
594
                                   out_size - written));
584
 
    if (ret == -1){
 
595
    if(ret == -1){
585
596
      perror("write");
586
597
      retval = -1;
587
598
      goto mandos_end;
590
601
    if(written < out_size){
591
602
      continue;
592
603
    } else {
593
 
      if (out == mandos_protocol_version){
 
604
      if(out == mandos_protocol_version){
594
605
        written = 0;
595
606
        out = "\r\n";
596
607
      } else {
603
614
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
604
615
  }
605
616
  
606
 
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
 
617
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
607
618
  
608
619
  do{
609
 
    ret = gnutls_handshake (session);
 
620
    ret = gnutls_handshake(session);
610
621
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
611
622
  
612
 
  if (ret != GNUTLS_E_SUCCESS){
 
623
  if(ret != GNUTLS_E_SUCCESS){
613
624
    if(debug){
614
625
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
615
 
      gnutls_perror (ret);
 
626
      gnutls_perror(ret);
616
627
    }
617
628
    retval = -1;
618
629
    goto mandos_end;
628
639
  while(true){
629
640
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
630
641
                                   buffer_capacity);
631
 
    if (buffer_capacity == 0){
 
642
    if(buffer_capacity == 0){
632
643
      perror("adjustbuffer");
633
644
      retval = -1;
634
645
      goto mandos_end;
635
646
    }
636
647
    
637
 
    ret = gnutls_record_recv(session, buffer+buffer_length,
638
 
                             BUFFER_SIZE);
639
 
    if (ret == 0){
 
648
    sret = gnutls_record_recv(session, buffer+buffer_length,
 
649
                              BUFFER_SIZE);
 
650
    if(sret == 0){
640
651
      break;
641
652
    }
642
 
    if (ret < 0){
643
 
      switch(ret){
 
653
    if(sret < 0){
 
654
      switch(sret){
644
655
      case GNUTLS_E_INTERRUPTED:
645
656
      case GNUTLS_E_AGAIN:
646
657
        break;
647
658
      case GNUTLS_E_REHANDSHAKE:
648
659
        do{
649
 
          ret = gnutls_handshake (session);
 
660
          ret = gnutls_handshake(session);
650
661
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
651
 
        if (ret < 0){
 
662
        if(ret < 0){
652
663
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
653
 
          gnutls_perror (ret);
 
664
          gnutls_perror(ret);
654
665
          retval = -1;
655
666
          goto mandos_end;
656
667
        }
659
670
        fprintf(stderr, "Unknown error while reading data from"
660
671
                " encrypted session with Mandos server\n");
661
672
        retval = -1;
662
 
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
673
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
663
674
        goto mandos_end;
664
675
      }
665
676
    } else {
666
 
      buffer_length += (size_t) ret;
 
677
      buffer_length += (size_t) sret;
667
678
    }
668
679
  }
669
680
  
671
682
    fprintf(stderr, "Closing TLS session\n");
672
683
  }
673
684
  
674
 
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
685
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
675
686
  
676
 
  if (buffer_length > 0){
 
687
  if(buffer_length > 0){
677
688
    decrypted_buffer_size = pgp_packet_decrypt(mc, buffer,
678
689
                                               buffer_length,
679
690
                                               &decrypted_buffer);
680
 
    if (decrypted_buffer_size >= 0){
 
691
    if(decrypted_buffer_size >= 0){
681
692
      written = 0;
682
693
      while(written < (size_t) decrypted_buffer_size){
683
 
        ret = (int)fwrite (decrypted_buffer + written, 1,
684
 
                           (size_t)decrypted_buffer_size - written,
685
 
                           stdout);
 
694
        ret = (int)fwrite(decrypted_buffer + written, 1,
 
695
                          (size_t)decrypted_buffer_size - written,
 
696
                          stdout);
686
697
        if(ret == 0 and ferror(stdout)){
687
698
          if(debug){
688
699
            fprintf(stderr, "Error writing encrypted data: %s\n",
705
716
  
706
717
 mandos_end:
707
718
  free(buffer);
708
 
  ret = TEMP_FAILURE_RETRY(close(tcp_sd));
 
719
  ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
709
720
  if(ret == -1){
710
721
    perror("close");
711
722
  }
712
 
  gnutls_deinit (session);
 
723
  gnutls_deinit(session);
713
724
  return retval;
714
725
}
715
726
 
726
737
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
727
738
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
728
739
                             flags,
729
 
                             void* userdata) {
 
740
                             void* userdata){
730
741
  mandos_context *mc = userdata;
731
742
  assert(r);
732
743
  
733
744
  /* Called whenever a service has been resolved successfully or
734
745
     timed out */
735
746
  
736
 
  switch (event) {
 
747
  switch(event){
737
748
  default:
738
749
  case AVAHI_RESOLVER_FAILURE:
739
750
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
747
758
      avahi_address_snprint(ip, sizeof(ip), address);
748
759
      if(debug){
749
760
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
750
 
                PRIu16 ") on port %d\n", name, host_name, ip,
751
 
                interface, port);
 
761
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
762
                ip, (intmax_t)interface, port);
752
763
      }
753
764
      int ret = start_mandos_communication(ip, port, interface, mc);
754
 
      if (ret == 0){
 
765
      if(ret == 0){
755
766
        avahi_simple_poll_quit(mc->simple_poll);
756
767
      }
757
768
    }
759
770
  avahi_s_service_resolver_free(r);
760
771
}
761
772
 
762
 
static void browse_callback( AvahiSServiceBrowser *b,
763
 
                             AvahiIfIndex interface,
764
 
                             AvahiProtocol protocol,
765
 
                             AvahiBrowserEvent event,
766
 
                             const char *name,
767
 
                             const char *type,
768
 
                             const char *domain,
769
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
770
 
                             flags,
771
 
                             void* userdata) {
 
773
static void browse_callback(AvahiSServiceBrowser *b,
 
774
                            AvahiIfIndex interface,
 
775
                            AvahiProtocol protocol,
 
776
                            AvahiBrowserEvent event,
 
777
                            const char *name,
 
778
                            const char *type,
 
779
                            const char *domain,
 
780
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
781
                            flags,
 
782
                            void* userdata){
772
783
  mandos_context *mc = userdata;
773
784
  assert(b);
774
785
  
775
786
  /* Called whenever a new services becomes available on the LAN or
776
787
     is removed from the LAN */
777
788
  
778
 
  switch (event) {
 
789
  switch(event){
779
790
  default:
780
791
  case AVAHI_BROWSER_FAILURE:
781
792
    
790
801
       the callback function is called the Avahi server will free the
791
802
       resolver for us. */
792
803
    
793
 
    if (!(avahi_s_service_resolver_new(mc->server, interface,
 
804
    if(!(avahi_s_service_resolver_new(mc->server, interface,
794
805
                                       protocol, name, type, domain,
795
806
                                       AVAHI_PROTO_INET6, 0,
796
807
                                       resolve_callback, mc)))
811
822
}
812
823
 
813
824
int main(int argc, char *argv[]){
814
 
    AvahiSServiceBrowser *sb = NULL;
815
 
    int error;
816
 
    int ret;
817
 
    int exitcode = EXIT_SUCCESS;
818
 
    const char *interface = "eth0";
819
 
    struct ifreq network;
820
 
    int sd;
821
 
    uid_t uid;
822
 
    gid_t gid;
823
 
    char *connect_to = NULL;
824
 
    char tempdir[] = "/tmp/mandosXXXXXX";
825
 
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
826
 
    const char *seckey = PATHDIR "/" SECKEY;
827
 
    const char *pubkey = PATHDIR "/" PUBKEY;
828
 
    
829
 
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
830
 
                          .dh_bits = 1024, .priority = "SECURE256"
831
 
                          ":!CTYPE-X.509:+CTYPE-OPENPGP" };
832
 
    bool gnutls_initalized = false;
833
 
    bool pgpme_initalized = false;
834
 
    
835
 
    {
836
 
      struct argp_option options[] = {
837
 
        { .name = "debug", .key = 128,
838
 
          .doc = "Debug mode", .group = 3 },
839
 
        { .name = "connect", .key = 'c',
840
 
          .arg = "ADDRESS:PORT",
841
 
          .doc = "Connect directly to a specific Mandos server",
842
 
          .group = 1 },
843
 
        { .name = "interface", .key = 'i',
844
 
          .arg = "NAME",
845
 
          .doc = "Interface that will be used to search for Mandos"
846
 
          " servers",
847
 
          .group = 1 },
848
 
        { .name = "seckey", .key = 's',
849
 
          .arg = "FILE",
850
 
          .doc = "OpenPGP secret key file base name",
851
 
          .group = 1 },
852
 
        { .name = "pubkey", .key = 'p',
853
 
          .arg = "FILE",
854
 
          .doc = "OpenPGP public key file base name",
855
 
          .group = 2 },
856
 
        { .name = "dh-bits", .key = 129,
857
 
          .arg = "BITS",
858
 
          .doc = "Bit length of the prime number used in the"
859
 
          " Diffie-Hellman key exchange",
860
 
          .group = 2 },
861
 
        { .name = "priority", .key = 130,
862
 
          .arg = "STRING",
863
 
          .doc = "GnuTLS priority string for the TLS handshake",
864
 
          .group = 1 },
865
 
        { .name = NULL }
866
 
      };
867
 
      
868
 
      error_t parse_opt (int key, char *arg,
869
 
                         struct argp_state *state) {
870
 
        /* Get the INPUT argument from `argp_parse', which we know is
871
 
           a pointer to our plugin list pointer. */
872
 
        switch (key) {
873
 
        case 128:               /* --debug */
874
 
          debug = true;
875
 
          break;
876
 
        case 'c':               /* --connect */
877
 
          connect_to = arg;
878
 
          break;
879
 
        case 'i':               /* --interface */
880
 
          interface = arg;
881
 
          break;
882
 
        case 's':               /* --seckey */
883
 
          seckey = arg;
884
 
          break;
885
 
        case 'p':               /* --pubkey */
886
 
          pubkey = arg;
887
 
          break;
888
 
        case 129:               /* --dh-bits */
889
 
          errno = 0;
890
 
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
891
 
          if (errno){
892
 
            perror("strtol");
893
 
            exit(EXIT_FAILURE);
894
 
          }
895
 
          break;
896
 
        case 130:               /* --priority */
897
 
          mc.priority = arg;
898
 
          break;
899
 
        case ARGP_KEY_ARG:
900
 
          argp_usage (state);
901
 
        case ARGP_KEY_END:
902
 
          break;
903
 
        default:
904
 
          return ARGP_ERR_UNKNOWN;
905
 
        }
906
 
        return 0;
907
 
      }
908
 
      
909
 
      struct argp argp = { .options = options, .parser = parse_opt,
910
 
                           .args_doc = "",
911
 
                           .doc = "Mandos client -- Get and decrypt"
912
 
                           " passwords from a Mandos server" };
913
 
      ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
914
 
      if (ret == ARGP_ERR_UNKNOWN){
915
 
        fprintf(stderr, "Unknown error while parsing arguments\n");
916
 
        exitcode = EXIT_FAILURE;
917
 
        goto end;
918
 
      }
919
 
    }
920
 
    
921
 
    ret = init_gnutls_global(&mc, pubkey, seckey);
922
 
    if (ret == -1){
923
 
      fprintf(stderr, "init_gnutls_global failed\n");
924
 
      exitcode = EXIT_FAILURE;
925
 
      goto end;
926
 
    } else {
927
 
      gnutls_initalized = true;
928
 
    }
929
 
 
930
 
    if(mkdtemp(tempdir) == NULL){
931
 
      perror("mkdtemp");
932
 
      tempdir[0] = '\0';
933
 
      goto end;
934
 
    }
935
 
    
936
 
    if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
937
 
      fprintf(stderr, "pgpme_initalized failed\n");
938
 
      exitcode = EXIT_FAILURE;
939
 
      goto end;
940
 
    } else {
941
 
      pgpme_initalized = true;
942
 
    }
943
 
    
944
 
    /* If the interface is down, bring it up */
945
 
    {
946
 
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
947
 
      if(sd < 0) {
948
 
        perror("socket");
949
 
        exitcode = EXIT_FAILURE;
950
 
        goto end;
951
 
      }
952
 
      strcpy(network.ifr_name, interface);
 
825
  AvahiSServiceBrowser *sb = NULL;
 
826
  int error;
 
827
  int ret;
 
828
  intmax_t tmpmax;
 
829
  int numchars;
 
830
  int exitcode = EXIT_SUCCESS;
 
831
  const char *interface = "eth0";
 
832
  struct ifreq network;
 
833
  int sd;
 
834
  uid_t uid;
 
835
  gid_t gid;
 
836
  char *connect_to = NULL;
 
837
  char tempdir[] = "/tmp/mandosXXXXXX";
 
838
  bool tempdir_created = false;
 
839
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
 
840
  const char *seckey = PATHDIR "/" SECKEY;
 
841
  const char *pubkey = PATHDIR "/" PUBKEY;
 
842
  
 
843
  mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
844
                        .dh_bits = 1024, .priority = "SECURE256"
 
845
                        ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
846
  bool gnutls_initialized = false;
 
847
  bool gpgme_initialized = false;
 
848
  double delay = 2.5;
 
849
  
 
850
  {
 
851
    struct argp_option options[] = {
 
852
      { .name = "debug", .key = 128,
 
853
        .doc = "Debug mode", .group = 3 },
 
854
      { .name = "connect", .key = 'c',
 
855
        .arg = "ADDRESS:PORT",
 
856
        .doc = "Connect directly to a specific Mandos server",
 
857
        .group = 1 },
 
858
      { .name = "interface", .key = 'i',
 
859
        .arg = "NAME",
 
860
        .doc = "Interface that will be used to search for Mandos"
 
861
        " servers",
 
862
        .group = 1 },
 
863
      { .name = "seckey", .key = 's',
 
864
        .arg = "FILE",
 
865
        .doc = "OpenPGP secret key file base name",
 
866
        .group = 1 },
 
867
      { .name = "pubkey", .key = 'p',
 
868
        .arg = "FILE",
 
869
        .doc = "OpenPGP public key file base name",
 
870
        .group = 2 },
 
871
      { .name = "dh-bits", .key = 129,
 
872
        .arg = "BITS",
 
873
        .doc = "Bit length of the prime number used in the"
 
874
        " Diffie-Hellman key exchange",
 
875
        .group = 2 },
 
876
      { .name = "priority", .key = 130,
 
877
        .arg = "STRING",
 
878
        .doc = "GnuTLS priority string for the TLS handshake",
 
879
        .group = 1 },
 
880
      { .name = "delay", .key = 131,
 
881
        .arg = "SECONDS",
 
882
        .doc = "Maximum delay to wait for interface startup",
 
883
        .group = 2 },
 
884
      { .name = NULL }
 
885
    };
 
886
    
 
887
    error_t parse_opt(int key, char *arg,
 
888
                      struct argp_state *state){
 
889
      switch(key){
 
890
      case 128:                 /* --debug */
 
891
        debug = true;
 
892
        break;
 
893
      case 'c':                 /* --connect */
 
894
        connect_to = arg;
 
895
        break;
 
896
      case 'i':                 /* --interface */
 
897
        interface = arg;
 
898
        break;
 
899
      case 's':                 /* --seckey */
 
900
        seckey = arg;
 
901
        break;
 
902
      case 'p':                 /* --pubkey */
 
903
        pubkey = arg;
 
904
        break;
 
905
      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);
 
911
        }
 
912
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
 
913
        break;
 
914
      case 130:                 /* --priority */
 
915
        mc.priority = arg;
 
916
        break;
 
917
      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);
 
922
        }
 
923
        break;
 
924
      case ARGP_KEY_ARG:
 
925
        argp_usage(state);
 
926
      case ARGP_KEY_END:
 
927
        break;
 
928
      default:
 
929
        return ARGP_ERR_UNKNOWN;
 
930
      }
 
931
      return 0;
 
932
    }
 
933
    
 
934
    struct argp argp = { .options = options, .parser = parse_opt,
 
935
                         .args_doc = "",
 
936
                         .doc = "Mandos client -- Get and decrypt"
 
937
                         " 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;
 
942
      goto end;
 
943
    }
 
944
  }
 
945
  
 
946
  /* If the interface is down, bring it up */
 
947
  {
 
948
#ifdef __linux__
 
949
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
950
       messages to mess up the prompt */
 
951
    ret = klogctl(8, NULL, 5);
 
952
    if(ret == -1){
 
953
      perror("klogctl");
 
954
    }
 
955
#endif
 
956
    
 
957
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
958
    if(sd < 0){
 
959
      perror("socket");
 
960
      exitcode = EXIT_FAILURE;
 
961
#ifdef __linux__
 
962
      ret = klogctl(7, NULL, 0);
 
963
      if(ret == -1){
 
964
        perror("klogctl");
 
965
      }
 
966
#endif
 
967
      goto end;
 
968
    }
 
969
    strcpy(network.ifr_name, interface);
 
970
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
971
    if(ret == -1){
 
972
      perror("ioctl SIOCGIFFLAGS");
 
973
#ifdef __linux__
 
974
      ret = klogctl(7, NULL, 0);
 
975
      if(ret == -1){
 
976
        perror("klogctl");
 
977
      }
 
978
#endif
 
979
      exitcode = EXIT_FAILURE;
 
980
      goto end;
 
981
    }
 
982
    if((network.ifr_flags & IFF_UP) == 0){
 
983
      network.ifr_flags |= IFF_UP;
 
984
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
985
      if(ret == -1){
 
986
        perror("ioctl SIOCSIFFLAGS");
 
987
        exitcode = EXIT_FAILURE;
 
988
#ifdef __linux__
 
989
        ret = klogctl(7, NULL, 0);
 
990
        if(ret == -1){
 
991
          perror("klogctl");
 
992
        }
 
993
#endif
 
994
        goto end;
 
995
      }
 
996
    }
 
997
    /* sleep checking until interface is running */
 
998
    for(int i=0; i < delay * 4; i++){
953
999
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
954
1000
      if(ret == -1){
955
1001
        perror("ioctl SIOCGIFFLAGS");
956
 
        exitcode = EXIT_FAILURE;
957
 
        goto end;
958
 
      }
959
 
      if((network.ifr_flags & IFF_UP) == 0){
960
 
        network.ifr_flags |= IFF_UP;
961
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
962
 
        if(ret == -1){
963
 
          perror("ioctl SIOCSIFFLAGS");
964
 
          exitcode = EXIT_FAILURE;
965
 
          goto end;
966
 
        }
967
 
      }
968
 
      ret = TEMP_FAILURE_RETRY(close(sd));
969
 
      if(ret == -1){
970
 
        perror("close");
971
 
      }
972
 
    }
973
 
    
974
 
    uid = getuid();
975
 
    gid = getgid();
976
 
    
977
 
    ret = setuid(uid);
978
 
    if (ret == -1){
979
 
      perror("setuid");
980
 
    }
981
 
    
982
 
    setgid(gid);
983
 
    if (ret == -1){
984
 
      perror("setgid");
985
 
    }
986
 
    
987
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
988
 
    if(if_index == 0){
989
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
990
 
      exit(EXIT_FAILURE);
991
 
    }
992
 
    
993
 
    if(connect_to != NULL){
994
 
      /* Connect directly, do not use Zeroconf */
995
 
      /* (Mainly meant for debugging) */
996
 
      char *address = strrchr(connect_to, ':');
997
 
      if(address == NULL){
998
 
        fprintf(stderr, "No colon in address\n");
999
 
        exitcode = EXIT_FAILURE;
1000
 
        goto end;
1001
 
      }
1002
 
      errno = 0;
1003
 
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
1004
 
      if(errno){
1005
 
        perror("Bad port number");
1006
 
        exitcode = EXIT_FAILURE;
1007
 
        goto end;
1008
 
      }
1009
 
      *address = '\0';
1010
 
      address = connect_to;
1011
 
      ret = start_mandos_communication(address, port, if_index, &mc);
1012
 
      if(ret < 0){
1013
 
        exitcode = EXIT_FAILURE;
1014
 
      } else {
1015
 
        exitcode = EXIT_SUCCESS;
1016
 
      }
1017
 
      goto end;
1018
 
    }
1019
 
    
1020
 
    if (not debug){
1021
 
      avahi_set_log_function(empty_log);
1022
 
    }
1023
 
    
1024
 
    /* Initialize the pseudo-RNG for Avahi */
1025
 
    srand((unsigned int) time(NULL));
1026
 
    
1027
 
    /* Allocate main Avahi loop object */
1028
 
    mc.simple_poll = avahi_simple_poll_new();
1029
 
    if (mc.simple_poll == NULL) {
1030
 
        fprintf(stderr, "Avahi: Failed to create simple poll"
1031
 
                " object.\n");
1032
 
        exitcode = EXIT_FAILURE;
1033
 
        goto end;
1034
 
    }
1035
 
    
1036
 
    {
1037
 
      AvahiServerConfig config;
1038
 
      /* Do not publish any local Zeroconf records */
1039
 
      avahi_server_config_init(&config);
1040
 
      config.publish_hinfo = 0;
1041
 
      config.publish_addresses = 0;
1042
 
      config.publish_workstation = 0;
1043
 
      config.publish_domain = 0;
1044
 
      
1045
 
      /* Allocate a new server */
1046
 
      mc.server = avahi_server_new(avahi_simple_poll_get
1047
 
                                   (mc.simple_poll), &config, NULL,
1048
 
                                   NULL, &error);
1049
 
      
1050
 
      /* Free the Avahi configuration data */
1051
 
      avahi_server_config_free(&config);
1052
 
    }
1053
 
    
1054
 
    /* Check if creating the Avahi server object succeeded */
1055
 
    if (mc.server == NULL) {
1056
 
        fprintf(stderr, "Failed to create Avahi server: %s\n",
1057
 
                avahi_strerror(error));
1058
 
        exitcode = EXIT_FAILURE;
1059
 
        goto end;
1060
 
    }
1061
 
    
1062
 
    /* Create the Avahi service browser */
1063
 
    sb = avahi_s_service_browser_new(mc.server, if_index,
1064
 
                                     AVAHI_PROTO_INET6,
1065
 
                                     "_mandos._tcp", NULL, 0,
1066
 
                                     browse_callback, &mc);
1067
 
    if (sb == NULL) {
1068
 
        fprintf(stderr, "Failed to create service browser: %s\n",
1069
 
                avahi_strerror(avahi_server_errno(mc.server)));
1070
 
        exitcode = EXIT_FAILURE;
1071
 
        goto end;
1072
 
    }
1073
 
    
1074
 
    /* Run the main loop */
1075
 
    
1076
 
    if (debug){
1077
 
      fprintf(stderr, "Starting Avahi loop search\n");
1078
 
    }
1079
 
    
1080
 
    avahi_simple_poll_loop(mc.simple_poll);
1081
 
    
 
1002
      } else if(network.ifr_flags & IFF_RUNNING){
 
1003
        break;
 
1004
      }
 
1005
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1006
      ret = nanosleep(&sleeptime, NULL);
 
1007
      if(ret == -1 and errno != EINTR){
 
1008
        perror("nanosleep");
 
1009
      }
 
1010
    }
 
1011
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1012
    if(ret == -1){
 
1013
      perror("close");
 
1014
    }
 
1015
#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);
 
1038
  if(ret == -1){
 
1039
    fprintf(stderr, "init_gnutls_global failed\n");
 
1040
    exitcode = EXIT_FAILURE;
 
1041
    goto end;
 
1042
  } else {
 
1043
    gnutls_initialized = true;
 
1044
  }
 
1045
  
 
1046
  if(mkdtemp(tempdir) == NULL){
 
1047
    perror("mkdtemp");
 
1048
    goto end;
 
1049
  }
 
1050
  tempdir_created = true;
 
1051
  
 
1052
  if(not init_gpgme(&mc, pubkey, seckey, tempdir)){
 
1053
    fprintf(stderr, "init_gpgme failed\n");
 
1054
    exitcode = EXIT_FAILURE;
 
1055
    goto end;
 
1056
  } else {
 
1057
    gpgme_initialized = true;
 
1058
  }
 
1059
  
 
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;
 
1064
    goto end;
 
1065
  }
 
1066
  
 
1067
  if(connect_to != NULL){
 
1068
    /* Connect directly, do not use Zeroconf */
 
1069
    /* (Mainly meant for debugging) */
 
1070
    char *address = strrchr(connect_to, ':');
 
1071
    if(address == NULL){
 
1072
      fprintf(stderr, "No colon in address\n");
 
1073
      exitcode = EXIT_FAILURE;
 
1074
      goto end;
 
1075
    }
 
1076
    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'){
 
1080
      fprintf(stderr, "Bad port number\n");
 
1081
      exitcode = EXIT_FAILURE;
 
1082
      goto end;
 
1083
    }
 
1084
    port = (uint16_t)tmpmax;
 
1085
    *address = '\0';
 
1086
    address = connect_to;
 
1087
    ret = start_mandos_communication(address, port, if_index, &mc);
 
1088
    if(ret < 0){
 
1089
      exitcode = EXIT_FAILURE;
 
1090
    } else {
 
1091
      exitcode = EXIT_SUCCESS;
 
1092
    }
 
1093
    goto end;
 
1094
  }
 
1095
  
 
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;
 
1108
    goto end;
 
1109
  }
 
1110
  
 
1111
  {
 
1112
    AvahiServerConfig config;
 
1113
    /* Do not publish any local Zeroconf records */
 
1114
    avahi_server_config_init(&config);
 
1115
    config.publish_hinfo = 0;
 
1116
    config.publish_addresses = 0;
 
1117
    config.publish_workstation = 0;
 
1118
    config.publish_domain = 0;
 
1119
    
 
1120
    /* Allocate a new server */
 
1121
    mc.server = avahi_server_new(avahi_simple_poll_get
 
1122
                                 (mc.simple_poll), &config, NULL,
 
1123
                                 NULL, &error);
 
1124
    
 
1125
    /* Free the Avahi configuration data */
 
1126
    avahi_server_config_free(&config);
 
1127
  }
 
1128
  
 
1129
  /* Check if creating the Avahi server object succeeded */
 
1130
  if(mc.server == NULL){
 
1131
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1132
            avahi_strerror(error));
 
1133
    exitcode = EXIT_FAILURE;
 
1134
    goto end;
 
1135
  }
 
1136
  
 
1137
  /* Create the Avahi service browser */
 
1138
  sb = avahi_s_service_browser_new(mc.server, if_index,
 
1139
                                   AVAHI_PROTO_INET6, "_mandos._tcp",
 
1140
                                   NULL, 0, browse_callback, &mc);
 
1141
  if(sb == NULL){
 
1142
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1143
            avahi_strerror(avahi_server_errno(mc.server)));
 
1144
    exitcode = EXIT_FAILURE;
 
1145
    goto end;
 
1146
  }
 
1147
  
 
1148
  /* Run the main loop */
 
1149
  
 
1150
  if(debug){
 
1151
    fprintf(stderr, "Starting Avahi loop search\n");
 
1152
  }
 
1153
  
 
1154
  avahi_simple_poll_loop(mc.simple_poll);
 
1155
  
1082
1156
 end:
1083
 
    
1084
 
    if (debug){
1085
 
      fprintf(stderr, "%s exiting\n", argv[0]);
1086
 
    }
1087
 
    
1088
 
    /* Cleanup things */
1089
 
    if (sb != NULL)
1090
 
        avahi_s_service_browser_free(sb);
1091
 
    
1092
 
    if (mc.server != NULL)
1093
 
        avahi_server_free(mc.server);
1094
 
    
1095
 
    if (mc.simple_poll != NULL)
1096
 
        avahi_simple_poll_free(mc.simple_poll);
1097
 
    
1098
 
    if (gnutls_initalized){
1099
 
      gnutls_certificate_free_credentials(mc.cred);
1100
 
      gnutls_global_deinit ();
1101
 
    }
1102
 
 
1103
 
    if(pgpme_initalized){
1104
 
      gpgme_release(mc.ctx);
1105
 
    }
1106
 
 
1107
 
    /* Removes the temp directory used by GPGME */
1108
 
    if(tempdir[0] != '\0'){
1109
 
      DIR *d;
1110
 
      struct dirent *direntry;
1111
 
      d = opendir(tempdir);
1112
 
      if(d == NULL){
 
1157
  
 
1158
  if(debug){
 
1159
    fprintf(stderr, "%s exiting\n", argv[0]);
 
1160
  }
 
1161
  
 
1162
  /* Cleanup things */
 
1163
  if(sb != NULL)
 
1164
    avahi_s_service_browser_free(sb);
 
1165
  
 
1166
  if(mc.server != NULL)
 
1167
    avahi_server_free(mc.server);
 
1168
  
 
1169
  if(mc.simple_poll != NULL)
 
1170
    avahi_simple_poll_free(mc.simple_poll);
 
1171
  
 
1172
  if(gnutls_initialized){
 
1173
    gnutls_certificate_free_credentials(mc.cred);
 
1174
    gnutls_global_deinit();
 
1175
    gnutls_dh_params_deinit(mc.dh_params);
 
1176
  }
 
1177
  
 
1178
  if(gpgme_initialized){
 
1179
    gpgme_release(mc.ctx);
 
1180
  }
 
1181
  
 
1182
  /* Removes the temp directory used by GPGME */
 
1183
  if(tempdir_created){
 
1184
    DIR *d;
 
1185
    struct dirent *direntry;
 
1186
    d = opendir(tempdir);
 
1187
    if(d == NULL){
 
1188
      if(errno != ENOENT){
1113
1189
        perror("opendir");
1114
 
      } else {
1115
 
        while(true){
1116
 
          direntry = readdir(d);
1117
 
          if(direntry == NULL){
1118
 
            break;
1119
 
          }
1120
 
          if (direntry->d_type == DT_REG){
1121
 
            char *fullname = NULL;
1122
 
            ret = asprintf(&fullname, "%s/%s", tempdir,
1123
 
                           direntry->d_name);
1124
 
            if(ret < 0){
1125
 
              perror("asprintf");
1126
 
              continue;
1127
 
            }
1128
 
            ret = unlink(fullname);
1129
 
            if(ret == -1){
1130
 
              fprintf(stderr, "unlink(\"%s\"): %s",
1131
 
                      fullname, strerror(errno));
1132
 
            }
1133
 
            free(fullname);
1134
 
          }
1135
 
        }
1136
 
      }
1137
 
      ret = rmdir(tempdir);
1138
 
      if(ret == -1){
1139
 
        perror("rmdir");
1140
 
      }
1141
 
    }
1142
 
          
1143
 
    return exitcode;
 
1190
      }
 
1191
    } else {
 
1192
      while(true){
 
1193
        direntry = readdir(d);
 
1194
        if(direntry == NULL){
 
1195
          break;
 
1196
        }
 
1197
        /* Skip "." and ".." */
 
1198
        if(direntry->d_name[0] == '.'
 
1199
           and (direntry->d_name[1] == '\0'
 
1200
                or (direntry->d_name[1] == '.'
 
1201
                    and direntry->d_name[2] == '\0'))){
 
1202
          continue;
 
1203
        }
 
1204
        char *fullname = NULL;
 
1205
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
1206
                       direntry->d_name);
 
1207
        if(ret < 0){
 
1208
          perror("asprintf");
 
1209
          continue;
 
1210
        }
 
1211
        ret = remove(fullname);
 
1212
        if(ret == -1){
 
1213
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1214
                  strerror(errno));
 
1215
        }
 
1216
        free(fullname);
 
1217
      }
 
1218
      closedir(d);
 
1219
    }
 
1220
    ret = rmdir(tempdir);
 
1221
    if(ret == -1 and errno != ENOENT){
 
1222
      perror("rmdir");
 
1223
    }
 
1224
  }
 
1225
  
 
1226
  return exitcode;
1144
1227
}