/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/mandosclient.c

  • Committer: Teddy Hogeborn
  • Date: 2008-08-03 03:33:56 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080803033356-6aemgj0g0hoz91ow
* plugins.d/mandosclient.c (pgp_packet_decrypt): Renamed variables.
                                                 On debug, show
                                                 decrypted plaintext
                                                 in hexadecimal.  Free
                                                 the GPGME data
                                                 buffers even on
                                                 errors.

Show diffs side-by-side

added added

removed removed

Lines of Context:
32
32
#define _LARGEFILE_SOURCE
33
33
#define _FILE_OFFSET_BITS 64
34
34
 
35
 
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
36
 
 
37
 
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
38
 
                                   stdout, ferror() */
39
 
#include <stdint.h>             /* uint16_t, uint32_t */
40
 
#include <stddef.h>             /* NULL, size_t, ssize_t */
41
 
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
42
 
                                   srand() */
43
 
#include <stdbool.h>            /* bool, true */
44
 
#include <string.h>             /* memset(), strcmp(), strlen(),
45
 
                                   strerror(), asprintf(), strcpy() */
46
 
#include <sys/ioctl.h>          /* ioctl */
47
 
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
48
 
                                   sockaddr_in6, PF_INET6,
49
 
                                   SOCK_STREAM, INET6_ADDRSTRLEN,
50
 
                                   uid_t, gid_t */
51
 
#include <inttypes.h>           /* PRIu16 */
52
 
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
53
 
                                   struct in6_addr, inet_pton(),
54
 
                                   connect() */
55
 
#include <assert.h>             /* assert() */
56
 
#include <errno.h>              /* perror(), errno */
57
 
#include <time.h>               /* time() */
 
35
#include <stdio.h>
 
36
#include <assert.h>
 
37
#include <stdlib.h>
 
38
#include <time.h>
 
39
#include <net/if.h>             /* if_nametoindex */
 
40
#include <sys/ioctl.h>          /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
 
41
                                   SIOCSIFFLAGS */
58
42
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
59
 
                                   SIOCSIFFLAGS, if_indextoname(),
60
 
                                   if_nametoindex(), IF_NAMESIZE */
61
 
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
62
 
                                   getuid(), getgid(), setuid(),
63
 
                                   setgid() */
64
 
#include <netinet/in.h>
65
 
#include <arpa/inet.h>          /* inet_pton(), htons */
66
 
#include <iso646.h>             /* not, and */
67
 
#include <argp.h>               /* struct argp_option, error_t, struct
68
 
                                   argp_state, struct argp,
69
 
                                   argp_parse(), ARGP_KEY_ARG,
70
 
                                   ARGP_KEY_END, ARGP_ERR_UNKNOWN */
 
43
                                   SIOCSIFFLAGS */
71
44
 
72
 
/* Avahi */
73
 
/* All Avahi types, constants and functions
74
 
 Avahi*, avahi_*,
75
 
 AVAHI_* */
76
45
#include <avahi-core/core.h>
77
46
#include <avahi-core/lookup.h>
78
47
#include <avahi-core/log.h>
80
49
#include <avahi-common/malloc.h>
81
50
#include <avahi-common/error.h>
82
51
 
83
 
/* GnuTLS */
84
 
#include <gnutls/gnutls.h>      /* All GnuTLS types, constants and
85
 
                                   functions:
86
 
                                   gnutls_*
87
 
                                   init_gnutls_session(),
88
 
                                   GNUTLS_* */
89
 
#include <gnutls/openpgp.h>     /* gnutls_certificate_set_openpgp_key_file(),
90
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
91
 
 
92
 
/* GPGME */
93
 
#include <gpgme.h>              /* All GPGME types, constants and
94
 
                                   functions:
95
 
                                   gpgme_*
96
 
                                   GPGME_PROTOCOL_OpenPGP,
97
 
                                   GPG_ERR_NO_* */
 
52
//mandos client part
 
53
#include <sys/types.h>          /* socket(), inet_pton() */
 
54
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
 
55
                                   struct in6_addr, inet_pton() */
 
56
#include <gnutls/gnutls.h>      /* All GnuTLS stuff */
 
57
#include <gnutls/openpgp.h>     /* GnuTLS with openpgp stuff */
 
58
 
 
59
#include <unistd.h>             /* close() */
 
60
#include <netinet/in.h>
 
61
#include <stdbool.h>            /* true */
 
62
#include <string.h>             /* memset */
 
63
#include <arpa/inet.h>          /* inet_pton() */
 
64
#include <iso646.h>             /* not */
 
65
 
 
66
// gpgme
 
67
#include <errno.h>              /* perror() */
 
68
#include <gpgme.h>
 
69
 
 
70
// getopt_long
 
71
#include <getopt.h>
98
72
 
99
73
#define BUFFER_SIZE 256
100
74
 
 
75
static const char *keydir = "/conf/conf.d/mandos";
 
76
static const char *pubkeyfile = "pubkey.txt";
 
77
static const char *seckeyfile = "seckey.txt";
 
78
 
101
79
bool debug = false;
102
 
static const char *keydir = "/conf/conf.d/mandos";
103
 
static const char mandos_protocol_version[] = "1";
104
 
const char *argp_program_version = "password-request 1.0";
105
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
106
80
 
107
 
/* Used for passing in values through the Avahi callback functions */
 
81
/* Used for passing in values through all the callback functions */
108
82
typedef struct {
109
83
  AvahiSimplePoll *simple_poll;
110
84
  AvahiServer *server;
111
85
  gnutls_certificate_credentials_t cred;
112
86
  unsigned int dh_bits;
113
 
  gnutls_dh_params_t dh_params;
114
87
  const char *priority;
115
88
} mandos_context;
116
89
 
117
 
/*
118
 
 * Make room in "buffer" for at least BUFFER_SIZE additional bytes.
119
 
 * "buffer_capacity" is how much is currently allocated,
120
 
 * "buffer_length" is how much is already used.
121
 
 */
122
 
size_t adjustbuffer(char **buffer, size_t buffer_length,
123
 
                  size_t buffer_capacity){
124
 
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
125
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
126
 
    if (buffer == NULL){
127
 
      return 0;
128
 
    }
129
 
    buffer_capacity += BUFFER_SIZE;
130
 
  }
131
 
  return buffer_capacity;
132
 
}
133
 
 
134
90
/* 
135
91
 * Decrypt OpenPGP data using keyrings in HOMEDIR.
136
92
 * Returns -1 on error
143
99
  gpgme_ctx_t ctx;
144
100
  gpgme_error_t rc;
145
101
  ssize_t ret;
146
 
  size_t plaintext_capacity = 0;
 
102
  ssize_t plaintext_capacity = 0;
147
103
  ssize_t plaintext_length = 0;
148
104
  gpgme_engine_info_t engine_info;
149
105
  
229
185
    } else {
230
186
      fprintf(stderr, "Unsupported algorithm: %s\n",
231
187
              result->unsupported_algorithm);
232
 
      fprintf(stderr, "Wrong key usage: %u\n",
 
188
      fprintf(stderr, "Wrong key usage: %d\n",
233
189
              result->wrong_key_usage);
234
190
      if(result->file_name != NULL){
235
191
        fprintf(stderr, "File name: %s\n", result->file_name);
259
215
  
260
216
  *plaintext = NULL;
261
217
  while(true){
262
 
    plaintext_capacity = adjustbuffer(plaintext,
263
 
                                      (size_t)plaintext_length,
264
 
                                      plaintext_capacity);
265
 
    if (plaintext_capacity == 0){
266
 
        perror("adjustbuffer");
 
218
    if (plaintext_length + BUFFER_SIZE > plaintext_capacity){
 
219
      *plaintext = realloc(*plaintext,
 
220
                            (unsigned int)plaintext_capacity
 
221
                            + BUFFER_SIZE);
 
222
      if (*plaintext == NULL){
 
223
        perror("realloc");
267
224
        plaintext_length = -1;
268
225
        goto decrypt_end;
 
226
      }
 
227
      plaintext_capacity += BUFFER_SIZE;
269
228
    }
270
229
    
271
230
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
285
244
 
286
245
  if(debug){
287
246
    fprintf(stderr, "Decrypted password is: ");
288
 
    for(ssize_t i = 0; i < plaintext_length; i++){
 
247
    for(size_t i = 0; i < plaintext_length; i++){
289
248
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
290
249
    }
291
250
    fprintf(stderr, "\n");
302
261
}
303
262
 
304
263
static const char * safer_gnutls_strerror (int value) {
305
 
  const char *ret = gnutls_strerror (value); /* Spurious warning */
 
264
  const char *ret = gnutls_strerror (value);
306
265
  if (ret == NULL)
307
266
    ret = "(unknown)";
308
267
  return ret;
309
268
}
310
269
 
311
 
/* GnuTLS log function callback */
312
270
static void debuggnutls(__attribute__((unused)) int level,
313
271
                        const char* string){
314
 
  fprintf(stderr, "GnuTLS: %s", string);
 
272
  fprintf(stderr, "%s", string);
315
273
}
316
274
 
317
 
static int init_gnutls_global(mandos_context *mc,
318
 
                              const char *pubkeyfilename,
319
 
                              const char *seckeyfilename){
 
275
static int initgnutls(mandos_context *mc, gnutls_session_t *session,
 
276
                      gnutls_dh_params_t *dh_params){
 
277
  const char *err;
320
278
  int ret;
321
279
  
322
280
  if(debug){
323
281
    fprintf(stderr, "Initializing GnuTLS\n");
324
282
  }
325
 
  
326
 
  ret = gnutls_global_init();
327
 
  if (ret != GNUTLS_E_SUCCESS) {
328
 
    fprintf (stderr, "GnuTLS global_init: %s\n",
329
 
             safer_gnutls_strerror(ret));
 
283
 
 
284
  if ((ret = gnutls_global_init ())
 
285
      != GNUTLS_E_SUCCESS) {
 
286
    fprintf (stderr, "global_init: %s\n", safer_gnutls_strerror(ret));
330
287
    return -1;
331
288
  }
332
289
  
333
290
  if (debug){
334
 
    /* "Use a log level over 10 to enable all debugging options."
335
 
     * - GnuTLS manual
336
 
     */
337
291
    gnutls_global_set_log_level(11);
338
292
    gnutls_global_set_log_function(debuggnutls);
339
293
  }
340
294
  
341
 
  /* OpenPGP credentials */
342
 
  gnutls_certificate_allocate_credentials(&mc->cred);
343
 
  if (ret != GNUTLS_E_SUCCESS){
344
 
    fprintf (stderr, "GnuTLS memory error: %s\n", /* Spurious
345
 
                                                     warning */
 
295
  /* openpgp credentials */
 
296
  if ((ret = gnutls_certificate_allocate_credentials (&mc->cred))
 
297
      != GNUTLS_E_SUCCESS) {
 
298
    fprintf (stderr, "memory error: %s\n",
346
299
             safer_gnutls_strerror(ret));
347
 
    gnutls_global_deinit ();
348
300
    return -1;
349
301
  }
350
302
  
351
303
  if(debug){
352
304
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
353
 
            " and keyfile %s as GnuTLS credentials\n", pubkeyfilename,
354
 
            seckeyfilename);
 
305
            " and keyfile %s as GnuTLS credentials\n", pubkeyfile,
 
306
            seckeyfile);
355
307
  }
356
308
  
357
309
  ret = gnutls_certificate_set_openpgp_key_file
358
 
    (mc->cred, pubkeyfilename, seckeyfilename,
359
 
     GNUTLS_OPENPGP_FMT_BASE64);
 
310
    (mc->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
360
311
  if (ret != GNUTLS_E_SUCCESS) {
361
 
    fprintf(stderr,
362
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
363
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
364
 
    fprintf(stdout, "The GnuTLS error is: %s\n",
 
312
    fprintf
 
313
      (stderr, "Error[%d] while reading the OpenPGP key pair ('%s',"
 
314
       " '%s')\n",
 
315
       ret, pubkeyfile, seckeyfile);
 
316
    fprintf(stdout, "The Error is: %s\n",
365
317
            safer_gnutls_strerror(ret));
366
 
    goto globalfail;
367
 
  }
368
 
  
369
 
  /* GnuTLS server initialization */
370
 
  ret = gnutls_dh_params_init(&mc->dh_params);
371
 
  if (ret != GNUTLS_E_SUCCESS) {
372
 
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
373
 
             " %s\n", safer_gnutls_strerror(ret));
374
 
    goto globalfail;
375
 
  }
376
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
377
 
  if (ret != GNUTLS_E_SUCCESS) {
378
 
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
379
 
             safer_gnutls_strerror(ret));
380
 
    goto globalfail;
381
 
  }
382
 
  
383
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
384
 
 
385
 
  return 0;
386
 
 
387
 
 globalfail:
388
 
 
389
 
  gnutls_certificate_free_credentials(mc->cred);
390
 
  gnutls_global_deinit();
391
 
  return -1;
392
 
 
393
 
}
394
 
 
395
 
static int init_gnutls_session(mandos_context *mc,
396
 
                               gnutls_session_t *session){
397
 
  int ret;
398
 
  /* GnuTLS session creation */
399
 
  ret = gnutls_init(session, GNUTLS_SERVER);
400
 
  if (ret != GNUTLS_E_SUCCESS){
 
318
    return -1;
 
319
  }
 
320
  
 
321
  //GnuTLS server initialization
 
322
  if ((ret = gnutls_dh_params_init(dh_params))
 
323
      != GNUTLS_E_SUCCESS) {
 
324
    fprintf (stderr, "Error in dh parameter initialization: %s\n",
 
325
             safer_gnutls_strerror(ret));
 
326
    return -1;
 
327
  }
 
328
  
 
329
  if ((ret = gnutls_dh_params_generate2(*dh_params, mc->dh_bits))
 
330
      != GNUTLS_E_SUCCESS) {
 
331
    fprintf (stderr, "Error in prime generation: %s\n",
 
332
             safer_gnutls_strerror(ret));
 
333
    return -1;
 
334
  }
 
335
  
 
336
  gnutls_certificate_set_dh_params(mc->cred, *dh_params);
 
337
  
 
338
  // GnuTLS session creation
 
339
  if ((ret = gnutls_init(session, GNUTLS_SERVER))
 
340
      != GNUTLS_E_SUCCESS){
401
341
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
402
342
            safer_gnutls_strerror(ret));
403
343
  }
404
344
  
405
 
  {
406
 
    const char *err;
407
 
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
408
 
    if (ret != GNUTLS_E_SUCCESS) {
409
 
      fprintf(stderr, "Syntax error at: %s\n", err);
410
 
      fprintf(stderr, "GnuTLS error: %s\n",
411
 
              safer_gnutls_strerror(ret));
412
 
      gnutls_deinit (*session);
413
 
      return -1;
414
 
    }
 
345
  if ((ret = gnutls_priority_set_direct(*session, mc->priority, &err))
 
346
      != GNUTLS_E_SUCCESS) {
 
347
    fprintf(stderr, "Syntax error at: %s\n", err);
 
348
    fprintf(stderr, "GnuTLS error: %s\n",
 
349
            safer_gnutls_strerror(ret));
 
350
    return -1;
415
351
  }
416
352
  
417
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
418
 
                               mc->cred);
419
 
  if (ret != GNUTLS_E_SUCCESS) {
420
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
353
  if ((ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
354
                                    mc->cred))
 
355
      != GNUTLS_E_SUCCESS) {
 
356
    fprintf(stderr, "Error setting a credentials set: %s\n",
421
357
            safer_gnutls_strerror(ret));
422
 
    gnutls_deinit (*session);
423
358
    return -1;
424
359
  }
425
360
  
432
367
  return 0;
433
368
}
434
369
 
435
 
/* Avahi log function callback */
436
370
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
437
371
                      __attribute__((unused)) const char *txt){}
438
372
 
439
 
/* Called when a Mandos server is found */
440
373
static int start_mandos_communication(const char *ip, uint16_t port,
441
374
                                      AvahiIfIndex if_index,
442
375
                                      mandos_context *mc){
443
376
  int ret, tcp_sd;
444
 
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
 
377
  struct sockaddr_in6 to;
445
378
  char *buffer = NULL;
446
379
  char *decrypted_buffer;
447
380
  size_t buffer_length = 0;
448
381
  size_t buffer_capacity = 0;
449
382
  ssize_t decrypted_buffer_size;
450
 
  size_t written;
 
383
  size_t written = 0;
451
384
  int retval = 0;
452
385
  char interface[IF_NAMESIZE];
453
386
  gnutls_session_t session;
454
 
  
455
 
  ret = init_gnutls_session (mc, &session);
456
 
  if (ret != 0){
457
 
    return -1;
458
 
  }
 
387
  gnutls_dh_params_t dh_params;
459
388
  
460
389
  if(debug){
461
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
462
 
            "\n", ip, port);
 
390
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
 
391
            ip, port);
463
392
  }
464
393
  
465
394
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
476
405
    fprintf(stderr, "Binding to interface %s\n", interface);
477
406
  }
478
407
  
479
 
  memset(&to, 0, sizeof(to));
480
 
  to.in6.sin6_family = AF_INET6;
481
 
  /* It would be nice to have a way to detect if we were passed an
482
 
     IPv4 address here.   Now we assume an IPv6 address. */
483
 
  ret = inet_pton(AF_INET6, ip, &to.in6.sin6_addr);
 
408
  memset(&to,0,sizeof(to));     /* Spurious warning */
 
409
  to.sin6_family = AF_INET6;
 
410
  ret = inet_pton(AF_INET6, ip, &to.sin6_addr);
484
411
  if (ret < 0 ){
485
412
    perror("inet_pton");
486
413
    return -1;
489
416
    fprintf(stderr, "Bad address: %s\n", ip);
490
417
    return -1;
491
418
  }
492
 
  to.in6.sin6_port = htons(port); /* Spurious warning */
 
419
  to.sin6_port = htons(port);   /* Spurious warning */
493
420
  
494
 
  to.in6.sin6_scope_id = (uint32_t)if_index;
 
421
  to.sin6_scope_id = (uint32_t)if_index;
495
422
  
496
423
  if(debug){
497
 
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
498
 
            port);
 
424
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
499
425
    char addrstr[INET6_ADDRSTRLEN] = "";
500
 
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
 
426
    if(inet_ntop(to.sin6_family, &(to.sin6_addr), addrstr,
501
427
                 sizeof(addrstr)) == NULL){
502
428
      perror("inet_ntop");
503
429
    } else {
507
433
    }
508
434
  }
509
435
  
510
 
  ret = connect(tcp_sd, &to.in, sizeof(to));
 
436
  ret = connect(tcp_sd, (struct sockaddr *) &to, sizeof(to));
511
437
  if (ret < 0){
512
438
    perror("connect");
513
439
    return -1;
514
440
  }
515
 
 
516
 
  const char *out = mandos_protocol_version;
517
 
  written = 0;
518
 
  while (true){
519
 
    size_t out_size = strlen(out);
520
 
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
521
 
                                   out_size - written));
522
 
    if (ret == -1){
523
 
      perror("write");
524
 
      retval = -1;
525
 
      goto mandos_end;
526
 
    }
527
 
    written += (size_t)ret;
528
 
    if(written < out_size){
529
 
      continue;
530
 
    } else {
531
 
      if (out == mandos_protocol_version){
532
 
        written = 0;
533
 
        out = "\r\n";
534
 
      } else {
535
 
        break;
536
 
      }
537
 
    }
 
441
  
 
442
  ret = initgnutls (mc, &session, &dh_params);
 
443
  if (ret != 0){
 
444
    retval = -1;
 
445
    return -1;
538
446
  }
539
 
 
 
447
  
 
448
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
 
449
  
540
450
  if(debug){
541
451
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
542
452
  }
543
453
  
544
 
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
545
 
 
546
 
  do{
547
 
    ret = gnutls_handshake (session);
548
 
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
 
454
  ret = gnutls_handshake (session);
549
455
  
550
456
  if (ret != GNUTLS_E_SUCCESS){
551
457
    if(debug){
552
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
458
      fprintf(stderr, "\n*** Handshake failed ***\n");
553
459
      gnutls_perror (ret);
554
460
    }
555
461
    retval = -1;
556
 
    goto mandos_end;
 
462
    goto exit;
557
463
  }
558
464
  
559
 
  /* Read OpenPGP packet that contains the wanted password */
 
465
  //Retrieve OpenPGP packet that contains the wanted password
560
466
  
561
467
  if(debug){
562
468
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
564
470
  }
565
471
 
566
472
  while(true){
567
 
    buffer_capacity = adjustbuffer(&buffer, buffer_length,
568
 
                                   buffer_capacity);
569
 
    if (buffer_capacity == 0){
570
 
      perror("adjustbuffer");
571
 
      retval = -1;
572
 
      goto mandos_end;
 
473
    if (buffer_length + BUFFER_SIZE > buffer_capacity){
 
474
      buffer = realloc(buffer, buffer_capacity + BUFFER_SIZE);
 
475
      if (buffer == NULL){
 
476
        perror("realloc");
 
477
        goto exit;
 
478
      }
 
479
      buffer_capacity += BUFFER_SIZE;
573
480
    }
574
481
    
575
482
    ret = gnutls_record_recv(session, buffer+buffer_length,
583
490
      case GNUTLS_E_AGAIN:
584
491
        break;
585
492
      case GNUTLS_E_REHANDSHAKE:
586
 
        do{
587
 
          ret = gnutls_handshake (session);
588
 
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
 
493
        ret = gnutls_handshake (session);
589
494
        if (ret < 0){
590
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
495
          fprintf(stderr, "\n*** Handshake failed ***\n");
591
496
          gnutls_perror (ret);
592
497
          retval = -1;
593
 
          goto mandos_end;
 
498
          goto exit;
594
499
        }
595
500
        break;
596
501
      default:
597
502
        fprintf(stderr, "Unknown error while reading data from"
598
 
                " encrypted session with Mandos server\n");
 
503
                " encrypted session with mandos server\n");
599
504
        retval = -1;
600
505
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
601
 
        goto mandos_end;
 
506
        goto exit;
602
507
      }
603
508
    } else {
604
509
      buffer_length += (size_t) ret;
605
510
    }
606
511
  }
607
512
  
608
 
  if(debug){
609
 
    fprintf(stderr, "Closing TLS session\n");
610
 
  }
611
 
  
612
 
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
613
 
  
614
513
  if (buffer_length > 0){
615
514
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
616
515
                                               buffer_length,
617
516
                                               &decrypted_buffer,
618
517
                                               keydir);
619
518
    if (decrypted_buffer_size >= 0){
620
 
      written = 0;
621
519
      while(written < (size_t) decrypted_buffer_size){
622
520
        ret = (int)fwrite (decrypted_buffer + written, 1,
623
521
                           (size_t)decrypted_buffer_size - written,
637
535
      retval = -1;
638
536
    }
639
537
  }
640
 
  
641
 
  /* Shutdown procedure */
642
 
  
643
 
 mandos_end:
 
538
 
 
539
  //shutdown procedure
 
540
 
 
541
  if(debug){
 
542
    fprintf(stderr, "Closing TLS session\n");
 
543
  }
 
544
 
644
545
  free(buffer);
 
546
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
547
 exit:
645
548
  close(tcp_sd);
646
549
  gnutls_deinit (session);
 
550
  gnutls_certificate_free_credentials (mc->cred);
 
551
  gnutls_global_deinit ();
647
552
  return retval;
648
553
}
649
554
 
662
567
                             flags,
663
568
                             void* userdata) {
664
569
  mandos_context *mc = userdata;
665
 
  assert(r);
 
570
  assert(r);                    /* Spurious warning */
666
571
  
667
572
  /* Called whenever a service has been resolved successfully or
668
573
     timed out */
670
575
  switch (event) {
671
576
  default:
672
577
  case AVAHI_RESOLVER_FAILURE:
673
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
674
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
 
578
    fprintf(stderr, "(Resolver) Failed to resolve service '%s' of"
 
579
            " type '%s' in domain '%s': %s\n", name, type, domain,
675
580
            avahi_strerror(avahi_server_errno(mc->server)));
676
581
    break;
677
582
    
680
585
      char ip[AVAHI_ADDRESS_STR_MAX];
681
586
      avahi_address_snprint(ip, sizeof(ip), address);
682
587
      if(debug){
683
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
684
 
                PRIu16 ") on port %d\n", name, host_name, ip,
685
 
                interface, port);
 
588
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s) on"
 
589
                " port %d\n", name, host_name, ip, port);
686
590
      }
687
591
      int ret = start_mandos_communication(ip, port, interface, mc);
688
592
      if (ret == 0){
689
 
        avahi_simple_poll_quit(mc->simple_poll);
 
593
        exit(EXIT_SUCCESS);
690
594
      }
691
595
    }
692
596
  }
704
608
                             flags,
705
609
                             void* userdata) {
706
610
  mandos_context *mc = userdata;
707
 
  assert(b);
 
611
  assert(b);                    /* Spurious warning */
708
612
  
709
613
  /* Called whenever a new services becomes available on the LAN or
710
614
     is removed from the LAN */
713
617
  default:
714
618
  case AVAHI_BROWSER_FAILURE:
715
619
    
716
 
    fprintf(stderr, "(Avahi browser) %s\n",
 
620
    fprintf(stderr, "(Browser) %s\n",
717
621
            avahi_strerror(avahi_server_errno(mc->server)));
718
622
    avahi_simple_poll_quit(mc->simple_poll);
719
623
    return;
720
624
    
721
625
  case AVAHI_BROWSER_NEW:
722
 
    /* We ignore the returned Avahi resolver object. In the callback
723
 
       function we free it. If the Avahi server is terminated before
724
 
       the callback function is called the Avahi server will free the
725
 
       resolver for us. */
 
626
    /* We ignore the returned resolver object. In the callback
 
627
       function we free it. If the server is terminated before
 
628
       the callback function is called the server will free
 
629
       the resolver for us. */
726
630
    
727
631
    if (!(avahi_s_service_resolver_new(mc->server, interface,
728
632
                                       protocol, name, type, domain,
729
633
                                       AVAHI_PROTO_INET6, 0,
730
634
                                       resolve_callback, mc)))
731
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
732
 
              name, avahi_strerror(avahi_server_errno(mc->server)));
 
635
      fprintf(stderr, "Failed to resolve service '%s': %s\n", name,
 
636
              avahi_strerror(avahi_server_errno(mc->server)));
733
637
    break;
734
638
    
735
639
  case AVAHI_BROWSER_REMOVE:
737
641
    
738
642
  case AVAHI_BROWSER_ALL_FOR_NOW:
739
643
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
740
 
    if(debug){
741
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
742
 
    }
743
644
    break;
744
645
  }
745
646
}
746
647
 
747
648
/* Combines file name and path and returns the malloced new
748
649
   string. some sane checks could/should be added */
749
 
static char *combinepath(const char *first, const char *second){
750
 
  char *tmp;
751
 
  int ret = asprintf(&tmp, "%s/%s", first, second);
752
 
  if(ret < 0){
 
650
static const char *combinepath(const char *first, const char *second){
 
651
  size_t f_len = strlen(first);
 
652
  size_t s_len = strlen(second);
 
653
  char *tmp = malloc(f_len + s_len + 2);
 
654
  if (tmp == NULL){
753
655
    return NULL;
754
656
  }
 
657
  if(f_len > 0){
 
658
    memcpy(tmp, first, f_len);  /* Spurious warning */
 
659
  }
 
660
  tmp[f_len] = '/';
 
661
  if(s_len > 0){
 
662
    memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
 
663
  }
 
664
  tmp[f_len + 1 + s_len] = '\0';
755
665
  return tmp;
756
666
}
757
667
 
758
668
 
759
 
int main(int argc, char *argv[]){
 
669
int main(AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char*argv[]) {
 
670
    AvahiServerConfig config;
760
671
    AvahiSServiceBrowser *sb = NULL;
761
672
    int error;
762
673
    int ret;
763
 
    int exitcode = EXIT_SUCCESS;
 
674
    int debug_int;
 
675
    int returncode = EXIT_SUCCESS;
764
676
    const char *interface = "eth0";
765
677
    struct ifreq network;
766
678
    int sd;
767
 
    uid_t uid;
768
 
    gid_t gid;
769
679
    char *connect_to = NULL;
770
680
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
771
 
    char *pubkeyfilename = NULL;
772
 
    char *seckeyfilename = NULL;
773
 
    const char *pubkeyname = "pubkey.txt";
774
 
    const char *seckeyname = "seckey.txt";
775
681
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
776
682
                          .dh_bits = 1024, .priority = "SECURE256"};
777
 
    bool gnutls_initalized = false;
778
 
    
779
 
    {
780
 
      struct argp_option options[] = {
781
 
        { .name = "debug", .key = 128,
782
 
          .doc = "Debug mode", .group = 3 },
783
 
        { .name = "connect", .key = 'c',
784
 
          .arg = "IP",
785
 
          .doc = "Connect directly to a sepcified mandos server",
786
 
          .group = 1 },
787
 
        { .name = "interface", .key = 'i',
788
 
          .arg = "INTERFACE",
789
 
          .doc = "Interface that Avahi will conntect through",
790
 
          .group = 1 },
791
 
        { .name = "keydir", .key = 'd',
792
 
          .arg = "KEYDIR",
793
 
          .doc = "Directory where the openpgp keyring is",
794
 
          .group = 1 },
795
 
        { .name = "seckey", .key = 's',
796
 
          .arg = "SECKEY",
797
 
          .doc = "Secret openpgp key for gnutls authentication",
798
 
          .group = 1 },
799
 
        { .name = "pubkey", .key = 'p',
800
 
          .arg = "PUBKEY",
801
 
          .doc = "Public openpgp key for gnutls authentication",
802
 
          .group = 2 },
803
 
        { .name = "dh-bits", .key = 129,
804
 
          .arg = "BITS",
805
 
          .doc = "dh-bits to use in gnutls communication",
806
 
          .group = 2 },
807
 
        { .name = "priority", .key = 130,
808
 
          .arg = "PRIORITY",
809
 
          .doc = "GNUTLS priority", .group = 1 },
810
 
        { .name = NULL }
811
 
      };
812
 
 
813
 
      
814
 
      error_t parse_opt (int key, char *arg,
815
 
                         struct argp_state *state) {
816
 
        /* Get the INPUT argument from `argp_parse', which we know is
817
 
           a pointer to our plugin list pointer. */
818
 
        switch (key) {
819
 
        case 128:
820
 
          debug = true;
821
 
          break;
822
 
        case 'c':
823
 
          connect_to = arg;
824
 
          break;
825
 
        case 'i':
826
 
          interface = arg;
827
 
          break;
828
 
        case 'd':
829
 
          keydir = arg;
830
 
          break;
831
 
        case 's':
832
 
          seckeyname = arg;
833
 
          break;
834
 
        case 'p':
835
 
          pubkeyname = arg;
836
 
          break;
837
 
        case 129:
838
 
          errno = 0;
839
 
          mc.dh_bits = (unsigned int) strtol(arg, NULL, 10);
840
 
          if (errno){
841
 
            perror("strtol");
842
 
            exit(EXIT_FAILURE);
843
 
          }
844
 
          break;
845
 
        case 130:
846
 
          mc.priority = arg;
847
 
          break;
848
 
        case ARGP_KEY_ARG:
849
 
          argp_usage (state);
850
 
        case ARGP_KEY_END:
851
 
          break;
852
 
        default:
853
 
          return ARGP_ERR_UNKNOWN;
854
 
        }
855
 
        return 0;
856
 
      }
857
 
 
858
 
      struct argp argp = { .options = options, .parser = parse_opt,
859
 
                           .args_doc = "",
860
 
                           .doc = "Mandos client -- Get and decrypt"
861
 
                           " passwords from mandos server" };
862
 
      ret = argp_parse (&argp, argc, argv, 0, 0, NULL);
863
 
      if (ret == ARGP_ERR_UNKNOWN){
864
 
        fprintf(stderr, "Unknown error while parsing arguments\n");
865
 
        exitcode = EXIT_FAILURE;
866
 
        goto end;
867
 
      }
868
 
    }
869
 
      
870
 
    pubkeyfilename = combinepath(keydir, pubkeyname);
871
 
    if (pubkeyfilename == NULL){
872
 
      perror("combinepath");
873
 
      exitcode = EXIT_FAILURE;
874
 
      goto end;
875
 
    }
876
 
    
877
 
    seckeyfilename = combinepath(keydir, seckeyname);
878
 
    if (seckeyfilename == NULL){
879
 
      perror("combinepath");
880
 
      exitcode = EXIT_FAILURE;
881
 
      goto end;
882
 
    }
883
 
 
884
 
    ret = init_gnutls_global(&mc, pubkeyfilename, seckeyfilename);
885
 
    if (ret == -1){
886
 
      fprintf(stderr, "init_gnutls_global failed\n");
887
 
      exitcode = EXIT_FAILURE;
888
 
      goto end;
889
 
    } else {
890
 
      gnutls_initalized = true;
891
 
    }
892
 
    
893
 
    /* If the interface is down, bring it up */
894
 
    {
895
 
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
896
 
      if(sd < 0) {
897
 
        perror("socket");
898
 
        exitcode = EXIT_FAILURE;
899
 
        goto end;
900
 
      }
901
 
      strcpy(network.ifr_name, interface);
902
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
903
 
      if(ret == -1){
904
 
        perror("ioctl SIOCGIFFLAGS");
905
 
        exitcode = EXIT_FAILURE;
906
 
        goto end;
907
 
      }
908
 
      if((network.ifr_flags & IFF_UP) == 0){
909
 
        network.ifr_flags |= IFF_UP;
910
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
911
 
        if(ret == -1){
912
 
          perror("ioctl SIOCSIFFLAGS");
913
 
          exitcode = EXIT_FAILURE;
914
 
          goto end;
915
 
        }
916
 
      }
917
 
      close(sd);
918
 
    }
919
 
    
920
 
    uid = getuid();
921
 
    gid = getgid();
922
 
    
923
 
    ret = setuid(uid);
924
 
    if (ret == -1){
925
 
      perror("setuid");
926
 
    }
927
 
    
928
 
    setgid(gid);
929
 
    if (ret == -1){
930
 
      perror("setgid");
 
683
    
 
684
    debug_int = debug ? 1 : 0;
 
685
    while (true){
 
686
      struct option long_options[] = {
 
687
        {"debug", no_argument, &debug_int, 1},
 
688
        {"connect", required_argument, NULL, 'c'},
 
689
        {"interface", required_argument, NULL, 'i'},
 
690
        {"keydir", required_argument, NULL, 'd'},
 
691
        {"seckey", required_argument, NULL, 's'},
 
692
        {"pubkey", required_argument, NULL, 'p'},
 
693
        {"dh-bits", required_argument, NULL, 'D'},
 
694
        {"priority", required_argument, NULL, 'P'},
 
695
        {0, 0, 0, 0} };
 
696
      
 
697
      int option_index = 0;
 
698
      ret = getopt_long (argc, argv, "i:", long_options,
 
699
                         &option_index);
 
700
      
 
701
      if (ret == -1){
 
702
        break;
 
703
      }
 
704
      
 
705
      switch(ret){
 
706
      case 0:
 
707
        break;
 
708
      case 'i':
 
709
        interface = optarg;
 
710
        break;
 
711
      case 'c':
 
712
        connect_to = optarg;
 
713
        break;
 
714
      case 'd':
 
715
        keydir = optarg;
 
716
        break;
 
717
      case 'p':
 
718
        pubkeyfile = optarg;
 
719
        break;
 
720
      case 's':
 
721
        seckeyfile = optarg;
 
722
        break;
 
723
      case 'D':
 
724
        errno = 0;
 
725
        mc.dh_bits = (unsigned int) strtol(optarg, NULL, 10);
 
726
        if (errno){
 
727
          perror("strtol");
 
728
          exit(EXIT_FAILURE);
 
729
        }
 
730
        break;
 
731
      case 'P':
 
732
        mc.priority = optarg;
 
733
        break;
 
734
      case '?':
 
735
      default:
 
736
        exit(EXIT_FAILURE);
 
737
      }
 
738
    }
 
739
    debug = debug_int ? true : false;
 
740
    
 
741
    pubkeyfile = combinepath(keydir, pubkeyfile);
 
742
    if (pubkeyfile == NULL){
 
743
      perror("combinepath");
 
744
      returncode = EXIT_FAILURE;
 
745
      goto exit;
 
746
    }
 
747
    
 
748
    seckeyfile = combinepath(keydir, seckeyfile);
 
749
    if (seckeyfile == NULL){
 
750
      perror("combinepath");
 
751
      goto exit;
931
752
    }
932
753
    
933
754
    if_index = (AvahiIfIndex) if_nametoindex(interface);
942
763
      char *address = strrchr(connect_to, ':');
943
764
      if(address == NULL){
944
765
        fprintf(stderr, "No colon in address\n");
945
 
        exitcode = EXIT_FAILURE;
946
 
        goto end;
 
766
        exit(EXIT_FAILURE);
947
767
      }
948
768
      errno = 0;
949
769
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
950
770
      if(errno){
951
771
        perror("Bad port number");
952
 
        exitcode = EXIT_FAILURE;
953
 
        goto end;
 
772
        exit(EXIT_FAILURE);
954
773
      }
955
774
      *address = '\0';
956
775
      address = connect_to;
957
776
      ret = start_mandos_communication(address, port, if_index, &mc);
958
777
      if(ret < 0){
959
 
        exitcode = EXIT_FAILURE;
 
778
        exit(EXIT_FAILURE);
960
779
      } else {
961
 
        exitcode = EXIT_SUCCESS;
962
 
      }
963
 
      goto end;
964
 
    }
 
780
        exit(EXIT_SUCCESS);
 
781
      }
 
782
    }
 
783
    
 
784
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
785
    if(sd < 0) {
 
786
      perror("socket");
 
787
      returncode = EXIT_FAILURE;
 
788
      goto exit;
 
789
    }
 
790
    strcpy(network.ifr_name, interface); /* Spurious warning */
 
791
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
792
    if(ret == -1){
 
793
      
 
794
      perror("ioctl SIOCGIFFLAGS");
 
795
      returncode = EXIT_FAILURE;
 
796
      goto exit;
 
797
    }
 
798
    if((network.ifr_flags & IFF_UP) == 0){
 
799
      network.ifr_flags |= IFF_UP;
 
800
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
801
      if(ret == -1){
 
802
        perror("ioctl SIOCSIFFLAGS");
 
803
        returncode = EXIT_FAILURE;
 
804
        goto exit;
 
805
      }
 
806
    }
 
807
    close(sd);
965
808
    
966
809
    if (not debug){
967
810
      avahi_set_log_function(empty_log);
968
811
    }
969
812
    
970
 
    /* Initialize the pseudo-RNG for Avahi */
 
813
    /* Initialize the psuedo-RNG */
971
814
    srand((unsigned int) time(NULL));
972
 
    
973
 
    /* Allocate main Avahi loop object */
974
 
    mc.simple_poll = avahi_simple_poll_new();
975
 
    if (mc.simple_poll == NULL) {
976
 
        fprintf(stderr, "Avahi: Failed to create simple poll"
977
 
                " object.\n");
978
 
        exitcode = EXIT_FAILURE;
979
 
        goto end;
980
 
    }
981
 
 
982
 
    {
983
 
      AvahiServerConfig config;
984
 
      /* Do not publish any local Zeroconf records */
985
 
      avahi_server_config_init(&config);
986
 
      config.publish_hinfo = 0;
987
 
      config.publish_addresses = 0;
988
 
      config.publish_workstation = 0;
989
 
      config.publish_domain = 0;
990
 
 
991
 
      /* Allocate a new server */
992
 
      mc.server = avahi_server_new(avahi_simple_poll_get
993
 
                                   (mc.simple_poll), &config, NULL,
994
 
                                   NULL, &error);
995
 
    
996
 
      /* Free the Avahi configuration data */
997
 
      avahi_server_config_free(&config);
998
 
    }
999
 
    
1000
 
    /* Check if creating the Avahi server object succeeded */
1001
 
    if (mc.server == NULL) {
1002
 
        fprintf(stderr, "Failed to create Avahi server: %s\n",
 
815
 
 
816
    /* Allocate main loop object */
 
817
    if (!(mc.simple_poll = avahi_simple_poll_new())) {
 
818
        fprintf(stderr, "Failed to create simple poll object.\n");
 
819
        returncode = EXIT_FAILURE;
 
820
        goto exit;
 
821
    }
 
822
 
 
823
    /* Do not publish any local records */
 
824
    avahi_server_config_init(&config);
 
825
    config.publish_hinfo = 0;
 
826
    config.publish_addresses = 0;
 
827
    config.publish_workstation = 0;
 
828
    config.publish_domain = 0;
 
829
 
 
830
    /* Allocate a new server */
 
831
    mc.server=avahi_server_new(avahi_simple_poll_get(mc.simple_poll),
 
832
                               &config, NULL, NULL, &error);
 
833
    
 
834
    /* Free the configuration data */
 
835
    avahi_server_config_free(&config);
 
836
    
 
837
    /* Check if creating the server object succeeded */
 
838
    if (!mc.server) {
 
839
        fprintf(stderr, "Failed to create server: %s\n",
1003
840
                avahi_strerror(error));
1004
 
        exitcode = EXIT_FAILURE;
1005
 
        goto end;
 
841
        returncode = EXIT_FAILURE;
 
842
        goto exit;
1006
843
    }
1007
844
    
1008
 
    /* Create the Avahi service browser */
 
845
    /* Create the service browser */
1009
846
    sb = avahi_s_service_browser_new(mc.server, if_index,
1010
847
                                     AVAHI_PROTO_INET6,
1011
848
                                     "_mandos._tcp", NULL, 0,
1012
849
                                     browse_callback, &mc);
1013
 
    if (sb == NULL) {
 
850
    if (!sb) {
1014
851
        fprintf(stderr, "Failed to create service browser: %s\n",
1015
852
                avahi_strerror(avahi_server_errno(mc.server)));
1016
 
        exitcode = EXIT_FAILURE;
1017
 
        goto end;
 
853
        returncode = EXIT_FAILURE;
 
854
        goto exit;
1018
855
    }
1019
856
    
1020
857
    /* Run the main loop */
1021
858
 
1022
859
    if (debug){
1023
 
      fprintf(stderr, "Starting Avahi loop search\n");
 
860
      fprintf(stderr, "Starting avahi loop search\n");
1024
861
    }
1025
862
    
1026
863
    avahi_simple_poll_loop(mc.simple_poll);
1027
864
    
1028
 
 end:
 
865
 exit:
1029
866
 
1030
867
    if (debug){
1031
868
      fprintf(stderr, "%s exiting\n", argv[0]);
1032
869
    }
1033
870
    
1034
871
    /* Cleanup things */
1035
 
    if (sb != NULL)
 
872
    if (sb)
1036
873
        avahi_s_service_browser_free(sb);
1037
874
    
1038
 
    if (mc.server != NULL)
 
875
    if (mc.server)
1039
876
        avahi_server_free(mc.server);
1040
877
 
1041
 
    if (mc.simple_poll != NULL)
 
878
    if (mc.simple_poll)
1042
879
        avahi_simple_poll_free(mc.simple_poll);
1043
 
    free(pubkeyfilename);
1044
 
    free(seckeyfilename);
1045
 
 
1046
 
    if (gnutls_initalized){
1047
 
      gnutls_certificate_free_credentials(mc.cred);
1048
 
      gnutls_global_deinit ();
1049
 
    }
 
880
    free(pubkeyfile);
 
881
    free(seckeyfile);
1050
882
    
1051
 
    return exitcode;
 
883
    return returncode;
1052
884
}