/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/password-request.c

name change for argp

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