/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

  • Committer: Teddy Hogeborn
  • Date: 2008-08-20 03:22:45 UTC
  • Revision ID: teddy@fukt.bsnet.se-20080820032245-ue341vdvzqdsg68l
* mandos (string_to_delta): Accept a whitespace-separated sequence of
                            intervals and return the sum.  This allows
                            "5m 30s" to be valid.
  (main): Provide an empty default value for the "host" option for
          "clients.conf", making it no longer a required option.

* mandos-clients.conf.xml: Removed <?xml-stylesheet>.
  (DESCRIPTION): Improved text.
  (DEFAULTS): Renamed to "OPTIONS".  Improved text for "timeout" and
              "interval".
  (CLIENTS): Removed; content moved to "OPTIONS".
  (EXPANSION): New section; document %(foo)s and %%(foo)s expansion.
  (FILES): Moved to before "EXAMPLES".
  (BUGS): New section.
  (EXAMPLES): Renamed to "EXAMPLE", as per man-pages(7).  Renamed
              example section "example_client" to "foo".  Changed
              example "host" setting to a more reasonable example host
              name.  Added additional example client "bar".

* mandos-conf.xml: Removed OVERVIEW entity.

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(), 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() */
42
58
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
43
 
                                   SIOCSIFFLAGS */
 
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 */
44
71
 
 
72
/* Avahi */
 
73
/* All Avahi types, constants and functions
 
74
 Avahi*, avahi_*,
 
75
 AVAHI_* */
45
76
#include <avahi-core/core.h>
46
77
#include <avahi-core/lookup.h>
47
78
#include <avahi-core/log.h>
49
80
#include <avahi-common/malloc.h>
50
81
#include <avahi-common/error.h>
51
82
 
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>
 
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_* */
72
98
 
73
99
#define BUFFER_SIZE 256
74
100
 
 
101
bool debug = false;
75
102
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 */
 
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
 
 
107
/* Used for passing in values through the Avahi callback functions */
82
108
typedef struct {
83
109
  AvahiSimplePoll *simple_poll;
84
110
  AvahiServer *server;
85
111
  gnutls_certificate_credentials_t cred;
86
112
  unsigned int dh_bits;
 
113
  gnutls_dh_params_t dh_params;
87
114
  const char *priority;
88
115
} mandos_context;
89
116
 
 
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
 
90
134
/* 
91
135
 * Decrypt OpenPGP data using keyrings in HOMEDIR.
92
136
 * Returns -1 on error
99
143
  gpgme_ctx_t ctx;
100
144
  gpgme_error_t rc;
101
145
  ssize_t ret;
102
 
  ssize_t plaintext_capacity = 0;
 
146
  size_t plaintext_capacity = 0;
103
147
  ssize_t plaintext_length = 0;
104
148
  gpgme_engine_info_t engine_info;
105
149
  
185
229
    } else {
186
230
      fprintf(stderr, "Unsupported algorithm: %s\n",
187
231
              result->unsupported_algorithm);
188
 
      fprintf(stderr, "Wrong key usage: %d\n",
 
232
      fprintf(stderr, "Wrong key usage: %u\n",
189
233
              result->wrong_key_usage);
190
234
      if(result->file_name != NULL){
191
235
        fprintf(stderr, "File name: %s\n", result->file_name);
215
259
  
216
260
  *plaintext = NULL;
217
261
  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");
 
262
    plaintext_capacity = adjustbuffer(plaintext,
 
263
                                      (size_t)plaintext_length,
 
264
                                      plaintext_capacity);
 
265
    if (plaintext_capacity == 0){
 
266
        perror("adjustbuffer");
224
267
        plaintext_length = -1;
225
268
        goto decrypt_end;
226
 
      }
227
 
      plaintext_capacity += BUFFER_SIZE;
228
269
    }
229
270
    
230
271
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
244
285
 
245
286
  if(debug){
246
287
    fprintf(stderr, "Decrypted password is: ");
247
 
    for(size_t i = 0; i < plaintext_length; i++){
 
288
    for(ssize_t i = 0; i < plaintext_length; i++){
248
289
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
249
290
    }
250
291
    fprintf(stderr, "\n");
261
302
}
262
303
 
263
304
static const char * safer_gnutls_strerror (int value) {
264
 
  const char *ret = gnutls_strerror (value);
 
305
  const char *ret = gnutls_strerror (value); /* Spurious warning */
265
306
  if (ret == NULL)
266
307
    ret = "(unknown)";
267
308
  return ret;
268
309
}
269
310
 
 
311
/* GnuTLS log function callback */
270
312
static void debuggnutls(__attribute__((unused)) int level,
271
313
                        const char* string){
272
 
  fprintf(stderr, "%s", string);
 
314
  fprintf(stderr, "GnuTLS: %s", string);
273
315
}
274
316
 
275
 
static int initgnutls(mandos_context *mc, gnutls_session_t *session,
276
 
                      gnutls_dh_params_t *dh_params){
277
 
  const char *err;
 
317
static int init_gnutls_global(mandos_context *mc,
 
318
                              const char *pubkeyfilename,
 
319
                              const char *seckeyfilename){
278
320
  int ret;
279
321
  
280
322
  if(debug){
281
323
    fprintf(stderr, "Initializing GnuTLS\n");
282
324
  }
283
 
 
284
 
  if ((ret = gnutls_global_init ())
285
 
      != GNUTLS_E_SUCCESS) {
286
 
    fprintf (stderr, "global_init: %s\n", safer_gnutls_strerror(ret));
 
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));
287
330
    return -1;
288
331
  }
289
332
  
290
333
  if (debug){
 
334
    /* "Use a log level over 10 to enable all debugging options."
 
335
     * - GnuTLS manual
 
336
     */
291
337
    gnutls_global_set_log_level(11);
292
338
    gnutls_global_set_log_function(debuggnutls);
293
339
  }
294
340
  
295
 
  /* openpgp credentials */
296
 
  if ((ret = gnutls_certificate_allocate_credentials (&mc->cred))
297
 
      != GNUTLS_E_SUCCESS) {
298
 
    fprintf (stderr, "memory error: %s\n",
 
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 */
299
346
             safer_gnutls_strerror(ret));
 
347
    gnutls_global_deinit ();
300
348
    return -1;
301
349
  }
302
350
  
303
351
  if(debug){
304
352
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
305
 
            " and keyfile %s as GnuTLS credentials\n", pubkeyfile,
306
 
            seckeyfile);
 
353
            " and keyfile %s as GnuTLS credentials\n", pubkeyfilename,
 
354
            seckeyfilename);
307
355
  }
308
356
  
309
357
  ret = gnutls_certificate_set_openpgp_key_file
310
 
    (mc->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
 
358
    (mc->cred, pubkeyfilename, seckeyfilename,
 
359
     GNUTLS_OPENPGP_FMT_BASE64);
311
360
  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",
 
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",
317
365
            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){
 
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){
341
401
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
342
402
            safer_gnutls_strerror(ret));
343
403
  }
344
404
  
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;
 
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
    }
351
415
  }
352
416
  
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",
 
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",
357
421
            safer_gnutls_strerror(ret));
 
422
    gnutls_deinit (*session);
358
423
    return -1;
359
424
  }
360
425
  
367
432
  return 0;
368
433
}
369
434
 
 
435
/* Avahi log function callback */
370
436
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
371
437
                      __attribute__((unused)) const char *txt){}
372
438
 
 
439
/* Called when a Mandos server is found */
373
440
static int start_mandos_communication(const char *ip, uint16_t port,
374
441
                                      AvahiIfIndex if_index,
375
442
                                      mandos_context *mc){
376
443
  int ret, tcp_sd;
377
 
  struct sockaddr_in6 to;
 
444
  union { struct sockaddr in; struct sockaddr_in6 in6; } to;
378
445
  char *buffer = NULL;
379
446
  char *decrypted_buffer;
380
447
  size_t buffer_length = 0;
381
448
  size_t buffer_capacity = 0;
382
449
  ssize_t decrypted_buffer_size;
383
 
  size_t written = 0;
 
450
  size_t written;
384
451
  int retval = 0;
385
452
  char interface[IF_NAMESIZE];
386
453
  gnutls_session_t session;
387
 
  gnutls_dh_params_t dh_params;
 
454
  
 
455
  ret = init_gnutls_session (mc, &session);
 
456
  if (ret != 0){
 
457
    return -1;
 
458
  }
388
459
  
389
460
  if(debug){
390
 
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
391
 
            ip, port);
 
461
    fprintf(stderr, "Setting up a tcp connection to %s, port %" PRIu16
 
462
            "\n", ip, port);
392
463
  }
393
464
  
394
465
  tcp_sd = socket(PF_INET6, SOCK_STREAM, 0);
405
476
    fprintf(stderr, "Binding to interface %s\n", interface);
406
477
  }
407
478
  
408
 
  memset(&to,0,sizeof(to));     /* Spurious warning */
409
 
  to.sin6_family = AF_INET6;
410
 
  ret = inet_pton(AF_INET6, ip, &to.sin6_addr);
 
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);
411
484
  if (ret < 0 ){
412
485
    perror("inet_pton");
413
486
    return -1;
416
489
    fprintf(stderr, "Bad address: %s\n", ip);
417
490
    return -1;
418
491
  }
419
 
  to.sin6_port = htons(port);   /* Spurious warning */
 
492
  to.in6.sin6_port = htons(port); /* Spurious warning */
420
493
  
421
 
  to.sin6_scope_id = (uint32_t)if_index;
 
494
  to.in6.sin6_scope_id = (uint32_t)if_index;
422
495
  
423
496
  if(debug){
424
 
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
 
497
    fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
498
            port);
425
499
    char addrstr[INET6_ADDRSTRLEN] = "";
426
 
    if(inet_ntop(to.sin6_family, &(to.sin6_addr), addrstr,
 
500
    if(inet_ntop(to.in6.sin6_family, &(to.in6.sin6_addr), addrstr,
427
501
                 sizeof(addrstr)) == NULL){
428
502
      perror("inet_ntop");
429
503
    } else {
433
507
    }
434
508
  }
435
509
  
436
 
  ret = connect(tcp_sd, (struct sockaddr *) &to, sizeof(to));
 
510
  ret = connect(tcp_sd, &to.in, sizeof(to));
437
511
  if (ret < 0){
438
512
    perror("connect");
439
513
    return -1;
440
514
  }
441
 
  
442
 
  ret = initgnutls (mc, &session, &dh_params);
443
 
  if (ret != 0){
444
 
    retval = -1;
445
 
    return -1;
 
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
    }
 
538
  }
 
539
 
 
540
  if(debug){
 
541
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
446
542
  }
447
543
  
448
544
  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);
 
545
 
 
546
  do{
 
547
    ret = gnutls_handshake (session);
 
548
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
455
549
  
456
550
  if (ret != GNUTLS_E_SUCCESS){
457
551
    if(debug){
458
 
      fprintf(stderr, "\n*** Handshake failed ***\n");
 
552
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
459
553
      gnutls_perror (ret);
460
554
    }
461
555
    retval = -1;
462
 
    goto exit;
 
556
    goto mandos_end;
463
557
  }
464
558
  
465
 
  //Retrieve OpenPGP packet that contains the wanted password
 
559
  /* Read OpenPGP packet that contains the wanted password */
466
560
  
467
561
  if(debug){
468
562
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
470
564
  }
471
565
 
472
566
  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;
 
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;
480
573
    }
481
574
    
482
575
    ret = gnutls_record_recv(session, buffer+buffer_length,
490
583
      case GNUTLS_E_AGAIN:
491
584
        break;
492
585
      case GNUTLS_E_REHANDSHAKE:
493
 
        ret = gnutls_handshake (session);
 
586
        do{
 
587
          ret = gnutls_handshake (session);
 
588
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
494
589
        if (ret < 0){
495
 
          fprintf(stderr, "\n*** Handshake failed ***\n");
 
590
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
496
591
          gnutls_perror (ret);
497
592
          retval = -1;
498
 
          goto exit;
 
593
          goto mandos_end;
499
594
        }
500
595
        break;
501
596
      default:
502
597
        fprintf(stderr, "Unknown error while reading data from"
503
 
                " encrypted session with mandos server\n");
 
598
                " encrypted session with Mandos server\n");
504
599
        retval = -1;
505
600
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
506
 
        goto exit;
 
601
        goto mandos_end;
507
602
      }
508
603
    } else {
509
604
      buffer_length += (size_t) ret;
510
605
    }
511
606
  }
512
607
  
 
608
  if(debug){
 
609
    fprintf(stderr, "Closing TLS session\n");
 
610
  }
 
611
  
 
612
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
613
  
513
614
  if (buffer_length > 0){
514
615
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
515
616
                                               buffer_length,
516
617
                                               &decrypted_buffer,
517
618
                                               keydir);
518
619
    if (decrypted_buffer_size >= 0){
 
620
      written = 0;
519
621
      while(written < (size_t) decrypted_buffer_size){
520
622
        ret = (int)fwrite (decrypted_buffer + written, 1,
521
623
                           (size_t)decrypted_buffer_size - written,
535
637
      retval = -1;
536
638
    }
537
639
  }
538
 
 
539
 
  //shutdown procedure
540
 
 
541
 
  if(debug){
542
 
    fprintf(stderr, "Closing TLS session\n");
543
 
  }
544
 
 
 
640
  
 
641
  /* Shutdown procedure */
 
642
  
 
643
 mandos_end:
545
644
  free(buffer);
546
 
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
547
 
 exit:
548
645
  close(tcp_sd);
549
646
  gnutls_deinit (session);
550
 
  gnutls_certificate_free_credentials (mc->cred);
551
 
  gnutls_global_deinit ();
552
647
  return retval;
553
648
}
554
649
 
567
662
                             flags,
568
663
                             void* userdata) {
569
664
  mandos_context *mc = userdata;
570
 
  assert(r);                    /* Spurious warning */
 
665
  assert(r);
571
666
  
572
667
  /* Called whenever a service has been resolved successfully or
573
668
     timed out */
575
670
  switch (event) {
576
671
  default:
577
672
  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,
 
673
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
674
            " of type '%s' in domain '%s': %s\n", name, type, domain,
580
675
            avahi_strerror(avahi_server_errno(mc->server)));
581
676
    break;
582
677
    
585
680
      char ip[AVAHI_ADDRESS_STR_MAX];
586
681
      avahi_address_snprint(ip, sizeof(ip), address);
587
682
      if(debug){
588
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s) on"
589
 
                " port %d\n", name, host_name, ip, port);
 
683
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
684
                PRIu16 ") on port %d\n", name, host_name, ip,
 
685
                interface, port);
590
686
      }
591
687
      int ret = start_mandos_communication(ip, port, interface, mc);
592
688
      if (ret == 0){
593
 
        exit(EXIT_SUCCESS);
 
689
        avahi_simple_poll_quit(mc->simple_poll);
594
690
      }
595
691
    }
596
692
  }
608
704
                             flags,
609
705
                             void* userdata) {
610
706
  mandos_context *mc = userdata;
611
 
  assert(b);                    /* Spurious warning */
 
707
  assert(b);
612
708
  
613
709
  /* Called whenever a new services becomes available on the LAN or
614
710
     is removed from the LAN */
617
713
  default:
618
714
  case AVAHI_BROWSER_FAILURE:
619
715
    
620
 
    fprintf(stderr, "(Browser) %s\n",
 
716
    fprintf(stderr, "(Avahi browser) %s\n",
621
717
            avahi_strerror(avahi_server_errno(mc->server)));
622
718
    avahi_simple_poll_quit(mc->simple_poll);
623
719
    return;
624
720
    
625
721
  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. */
 
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. */
630
726
    
631
727
    if (!(avahi_s_service_resolver_new(mc->server, interface,
632
728
                                       protocol, name, type, domain,
633
729
                                       AVAHI_PROTO_INET6, 0,
634
730
                                       resolve_callback, mc)))
635
 
      fprintf(stderr, "Failed to resolve service '%s': %s\n", name,
636
 
              avahi_strerror(avahi_server_errno(mc->server)));
 
731
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
732
              name, avahi_strerror(avahi_server_errno(mc->server)));
637
733
    break;
638
734
    
639
735
  case AVAHI_BROWSER_REMOVE:
641
737
    
642
738
  case AVAHI_BROWSER_ALL_FOR_NOW:
643
739
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
 
740
    if(debug){
 
741
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
742
    }
644
743
    break;
645
744
  }
646
745
}
647
746
 
648
747
/* Combines file name and path and returns the malloced new
649
748
   string. some sane checks could/should be added */
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){
 
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){
655
753
    return NULL;
656
754
  }
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';
665
755
  return tmp;
666
756
}
667
757
 
668
758
 
669
 
int main(AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char*argv[]) {
670
 
    AvahiServerConfig config;
 
759
int main(int argc, char *argv[]){
671
760
    AvahiSServiceBrowser *sb = NULL;
672
761
    int error;
673
762
    int ret;
674
 
    int debug_int;
675
 
    int returncode = EXIT_SUCCESS;
 
763
    int exitcode = EXIT_SUCCESS;
676
764
    const char *interface = "eth0";
677
765
    struct ifreq network;
678
766
    int sd;
 
767
    uid_t uid;
 
768
    gid_t gid;
679
769
    char *connect_to = NULL;
680
770
    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";
681
775
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
682
776
                          .dh_bits = 1024, .priority = "SECURE256"};
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;
 
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");
752
931
    }
753
932
    
754
933
    if_index = (AvahiIfIndex) if_nametoindex(interface);
763
942
      char *address = strrchr(connect_to, ':');
764
943
      if(address == NULL){
765
944
        fprintf(stderr, "No colon in address\n");
766
 
        exit(EXIT_FAILURE);
 
945
        exitcode = EXIT_FAILURE;
 
946
        goto end;
767
947
      }
768
948
      errno = 0;
769
949
      uint16_t port = (uint16_t) strtol(address+1, NULL, 10);
770
950
      if(errno){
771
951
        perror("Bad port number");
772
 
        exit(EXIT_FAILURE);
 
952
        exitcode = EXIT_FAILURE;
 
953
        goto end;
773
954
      }
774
955
      *address = '\0';
775
956
      address = connect_to;
776
957
      ret = start_mandos_communication(address, port, if_index, &mc);
777
958
      if(ret < 0){
778
 
        exit(EXIT_FAILURE);
 
959
        exitcode = EXIT_FAILURE;
779
960
      } else {
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);
 
961
        exitcode = EXIT_SUCCESS;
 
962
      }
 
963
      goto end;
 
964
    }
808
965
    
809
966
    if (not debug){
810
967
      avahi_set_log_function(empty_log);
811
968
    }
812
969
    
813
 
    /* Initialize the psuedo-RNG */
 
970
    /* Initialize the pseudo-RNG for Avahi */
814
971
    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",
 
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",
840
1003
                avahi_strerror(error));
841
 
        returncode = EXIT_FAILURE;
842
 
        goto exit;
 
1004
        exitcode = EXIT_FAILURE;
 
1005
        goto end;
843
1006
    }
844
1007
    
845
 
    /* Create the service browser */
 
1008
    /* Create the Avahi service browser */
846
1009
    sb = avahi_s_service_browser_new(mc.server, if_index,
847
1010
                                     AVAHI_PROTO_INET6,
848
1011
                                     "_mandos._tcp", NULL, 0,
849
1012
                                     browse_callback, &mc);
850
 
    if (!sb) {
 
1013
    if (sb == NULL) {
851
1014
        fprintf(stderr, "Failed to create service browser: %s\n",
852
1015
                avahi_strerror(avahi_server_errno(mc.server)));
853
 
        returncode = EXIT_FAILURE;
854
 
        goto exit;
 
1016
        exitcode = EXIT_FAILURE;
 
1017
        goto end;
855
1018
    }
856
1019
    
857
1020
    /* Run the main loop */
858
1021
 
859
1022
    if (debug){
860
 
      fprintf(stderr, "Starting avahi loop search\n");
 
1023
      fprintf(stderr, "Starting Avahi loop search\n");
861
1024
    }
862
1025
    
863
1026
    avahi_simple_poll_loop(mc.simple_poll);
864
1027
    
865
 
 exit:
 
1028
 end:
866
1029
 
867
1030
    if (debug){
868
1031
      fprintf(stderr, "%s exiting\n", argv[0]);
869
1032
    }
870
1033
    
871
1034
    /* Cleanup things */
872
 
    if (sb)
 
1035
    if (sb != NULL)
873
1036
        avahi_s_service_browser_free(sb);
874
1037
    
875
 
    if (mc.server)
 
1038
    if (mc.server != NULL)
876
1039
        avahi_server_free(mc.server);
877
1040
 
878
 
    if (mc.simple_poll)
 
1041
    if (mc.simple_poll != NULL)
879
1042
        avahi_simple_poll_free(mc.simple_poll);
880
 
    free(pubkeyfile);
881
 
    free(seckeyfile);
 
1043
    free(pubkeyfilename);
 
1044
    free(seckeyfilename);
 
1045
 
 
1046
    if (gnutls_initalized){
 
1047
      gnutls_certificate_free_credentials(mc.cred);
 
1048
      gnutls_global_deinit ();
 
1049
    }
882
1050
    
883
 
    return returncode;
 
1051
    return exitcode;
884
1052
}