/mandos/release

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

« back to all changes in this revision

Viewing changes to plugins.d/mandosclient.c

merge +
mandosclient
        Added a adjustbuffer function.

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() */
 
36
 
35
37
#include <stdio.h>
36
38
#include <assert.h>
37
39
#include <stdlib.h>
38
40
#include <time.h>
39
41
#include <net/if.h>             /* if_nametoindex */
40
 
#include <sys/ioctl.h>          // ioctl, ifreq, SIOCGIFFLAGS, IFF_UP, SIOCSIFFLAGS
41
 
#include <net/if.h>             // ioctl, ifreq, SIOCGIFFLAGS, IFF_UP, SIOCSIFFLAGS
 
42
#include <sys/ioctl.h>          /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
 
43
                                   SIOCSIFFLAGS */
 
44
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
 
45
                                   SIOCSIFFLAGS */
42
46
 
43
47
#include <avahi-core/core.h>
44
48
#include <avahi-core/lookup.h>
47
51
#include <avahi-common/malloc.h>
48
52
#include <avahi-common/error.h>
49
53
 
50
 
//mandos client part
 
54
/* Mandos client part */
51
55
#include <sys/types.h>          /* socket(), inet_pton() */
52
56
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
53
57
                                   struct in6_addr, inet_pton() */
60
64
#include <string.h>             /* memset */
61
65
#include <arpa/inet.h>          /* inet_pton() */
62
66
#include <iso646.h>             /* not */
 
67
#include <net/if.h>             /* IF_NAMESIZE */
63
68
 
64
 
// gpgme
 
69
/* GPGME */
65
70
#include <errno.h>              /* perror() */
66
71
#include <gpgme.h>
67
72
 
68
 
// getopt long
 
73
/* getopt_long */
69
74
#include <getopt.h>
70
75
 
71
76
#define BUFFER_SIZE 256
72
 
#define DH_BITS 1024
73
77
 
74
 
static const char *certdir = "/conf/conf.d/mandos";
75
 
static const char *certfile = "openpgp-client.txt";
76
 
static const char *certkey = "openpgp-client-key.txt";
 
78
static const char *keydir = "/conf/conf.d/mandos";
 
79
static const char *pubkeyfile = "pubkey.txt";
 
80
static const char *seckeyfile = "seckey.txt";
77
81
 
78
82
bool debug = false;
79
83
 
 
84
const char mandos_protocol_version[] = "1";
 
85
 
 
86
/* Used for passing in values through all the callback functions */
80
87
typedef struct {
81
88
  AvahiSimplePoll *simple_poll;
82
89
  AvahiServer *server;
85
92
  const char *priority;
86
93
} mandos_context;
87
94
 
88
 
static ssize_t pgp_packet_decrypt (char *packet, size_t packet_size,
89
 
                                   char **new_packet,
 
95
size_t adjustbuffer(char **buffer, size_t buffer_length,
 
96
                  size_t buffer_capacity){
 
97
  if (buffer_length + BUFFER_SIZE > buffer_capacity){
 
98
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
99
    if (buffer == NULL){
 
100
      return 0;
 
101
    }
 
102
    buffer_capacity += BUFFER_SIZE;
 
103
  }
 
104
  return buffer_capacity;
 
105
}
 
106
 
 
107
/* 
 
108
 * Decrypt OpenPGP data using keyrings in HOMEDIR.
 
109
 * Returns -1 on error
 
110
 */
 
111
static ssize_t pgp_packet_decrypt (const char *cryptotext,
 
112
                                   size_t crypto_size,
 
113
                                   char **plaintext,
90
114
                                   const char *homedir){
91
115
  gpgme_data_t dh_crypto, dh_plain;
92
116
  gpgme_ctx_t ctx;
93
117
  gpgme_error_t rc;
94
118
  ssize_t ret;
95
 
  ssize_t new_packet_capacity = 0;
96
 
  ssize_t new_packet_length = 0;
 
119
  size_t plaintext_capacity = 0;
 
120
  ssize_t plaintext_length = 0;
97
121
  gpgme_engine_info_t engine_info;
98
 
 
 
122
  
99
123
  if (debug){
100
 
    fprintf(stderr, "Trying to decrypt OpenPGP packet\n");
 
124
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
101
125
  }
102
126
  
103
127
  /* Init GPGME */
109
133
    return -1;
110
134
  }
111
135
  
112
 
  /* Set GPGME home directory */
 
136
  /* Set GPGME home directory for the OpenPGP engine only */
113
137
  rc = gpgme_get_engine_info (&engine_info);
114
138
  if (rc != GPG_ERR_NO_ERROR){
115
139
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
125
149
    engine_info = engine_info->next;
126
150
  }
127
151
  if(engine_info == NULL){
128
 
    fprintf(stderr, "Could not set home dir to %s\n", homedir);
 
152
    fprintf(stderr, "Could not set GPGME home dir to %s\n", homedir);
129
153
    return -1;
130
154
  }
131
155
  
132
 
  /* Create new GPGME data buffer from packet buffer */
133
 
  rc = gpgme_data_new_from_mem(&dh_crypto, packet, packet_size, 0);
 
156
  /* Create new GPGME data buffer from memory cryptotext */
 
157
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
 
158
                               0);
134
159
  if (rc != GPG_ERR_NO_ERROR){
135
160
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
136
161
            gpgme_strsource(rc), gpgme_strerror(rc));
142
167
  if (rc != GPG_ERR_NO_ERROR){
143
168
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
144
169
            gpgme_strsource(rc), gpgme_strerror(rc));
 
170
    gpgme_data_release(dh_crypto);
145
171
    return -1;
146
172
  }
147
173
  
150
176
  if (rc != GPG_ERR_NO_ERROR){
151
177
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
152
178
            gpgme_strsource(rc), gpgme_strerror(rc));
153
 
    return -1;
 
179
    plaintext_length = -1;
 
180
    goto decrypt_end;
154
181
  }
155
182
  
156
 
  /* Decrypt data from the FILE pointer to the plaintext data
157
 
     buffer */
 
183
  /* Decrypt data from the cryptotext data buffer to the plaintext
 
184
     data buffer */
158
185
  rc = gpgme_op_decrypt(ctx, dh_crypto, dh_plain);
159
186
  if (rc != GPG_ERR_NO_ERROR){
160
187
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
161
188
            gpgme_strsource(rc), gpgme_strerror(rc));
162
 
    return -1;
 
189
    plaintext_length = -1;
 
190
    goto decrypt_end;
163
191
  }
164
 
 
 
192
  
165
193
  if(debug){
166
 
    fprintf(stderr, "Decryption of OpenPGP packet succeeded\n");
 
194
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
167
195
  }
168
 
 
 
196
  
169
197
  if (debug){
170
198
    gpgme_decrypt_result_t result;
171
199
    result = gpgme_op_decrypt_result(ctx);
195
223
    }
196
224
  }
197
225
  
198
 
  /* Delete the GPGME FILE pointer cryptotext data buffer */
199
 
  gpgme_data_release(dh_crypto);
200
 
  
201
226
  /* Seek back to the beginning of the GPGME plaintext data buffer */
202
227
  if (gpgme_data_seek(dh_plain, (off_t) 0, SEEK_SET) == -1){
203
228
    perror("pgpme_data_seek");
 
229
    plaintext_length = -1;
 
230
    goto decrypt_end;
204
231
  }
205
232
  
206
 
  *new_packet = 0;
 
233
  *plaintext = NULL;
207
234
  while(true){
208
 
    if (new_packet_length + BUFFER_SIZE > new_packet_capacity){
209
 
      *new_packet = realloc(*new_packet,
210
 
                            (unsigned int)new_packet_capacity
211
 
                            + BUFFER_SIZE);
212
 
      if (*new_packet == NULL){
213
 
        perror("realloc");
214
 
        return -1;
215
 
      }
216
 
      new_packet_capacity += BUFFER_SIZE;
 
235
    plaintext_capacity = adjustbuffer(plaintext, (size_t)plaintext_length,
 
236
                                      plaintext_capacity);
 
237
    if (plaintext_capacity == 0){
 
238
        perror("adjustbuffer");
 
239
        plaintext_length = -1;
 
240
        goto decrypt_end;
217
241
    }
218
242
    
219
 
    ret = gpgme_data_read(dh_plain, *new_packet + new_packet_length,
 
243
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
220
244
                          BUFFER_SIZE);
221
245
    /* Print the data, if any */
222
246
    if (ret == 0){
 
247
      /* EOF */
223
248
      break;
224
249
    }
225
250
    if(ret < 0){
226
251
      perror("gpgme_data_read");
227
 
      return -1;
 
252
      plaintext_length = -1;
 
253
      goto decrypt_end;
228
254
    }
229
 
    new_packet_length += ret;
 
255
    plaintext_length += ret;
230
256
  }
231
257
 
232
 
  /* FIXME: check characters before printing to screen so to not print
233
 
     terminal control characters */
234
 
  /*   if(debug){ */
235
 
  /*     fprintf(stderr, "decrypted password is: "); */
236
 
  /*     fwrite(*new_packet, 1, new_packet_length, stderr); */
237
 
  /*     fprintf(stderr, "\n"); */
238
 
  /*   } */
 
258
  if(debug){
 
259
    fprintf(stderr, "Decrypted password is: ");
 
260
    for(ssize_t i = 0; i < plaintext_length; i++){
 
261
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
 
262
    }
 
263
    fprintf(stderr, "\n");
 
264
  }
 
265
  
 
266
 decrypt_end:
 
267
  
 
268
  /* Delete the GPGME cryptotext data buffer */
 
269
  gpgme_data_release(dh_crypto);
239
270
  
240
271
  /* Delete the GPGME plaintext data buffer */
241
272
  gpgme_data_release(dh_plain);
242
 
  return new_packet_length;
 
273
  return plaintext_length;
243
274
}
244
275
 
245
276
static const char * safer_gnutls_strerror (int value) {
249
280
  return ret;
250
281
}
251
282
 
 
283
/* GnuTLS log function callback */
252
284
static void debuggnutls(__attribute__((unused)) int level,
253
285
                        const char* string){
254
 
  fprintf(stderr, "%s", string);
 
286
  fprintf(stderr, "GnuTLS: %s", string);
255
287
}
256
288
 
257
 
static int initgnutls(mandos_context *mc){
258
 
  const char *err;
 
289
static int initgnutls(mandos_context *mc, gnutls_session_t *session,
 
290
                      gnutls_dh_params_t *dh_params){
259
291
  int ret;
260
292
  
261
293
  if(debug){
264
296
 
265
297
  if ((ret = gnutls_global_init ())
266
298
      != GNUTLS_E_SUCCESS) {
267
 
    fprintf (stderr, "global_init: %s\n", safer_gnutls_strerror(ret));
 
299
    fprintf (stderr, "GnuTLS global_init: %s\n",
 
300
             safer_gnutls_strerror(ret));
268
301
    return -1;
269
302
  }
270
 
 
 
303
  
271
304
  if (debug){
 
305
    /* "Use a log level over 10 to enable all debugging options."
 
306
     * - GnuTLS manual
 
307
     */
272
308
    gnutls_global_set_log_level(11);
273
309
    gnutls_global_set_log_function(debuggnutls);
274
310
  }
275
311
  
276
 
  /* openpgp credentials */
277
 
  if ((ret = gnutls_certificate_allocate_credentials (&es->cred))
 
312
  /* OpenPGP credentials */
 
313
  if ((ret = gnutls_certificate_allocate_credentials (&mc->cred))
278
314
      != GNUTLS_E_SUCCESS) {
279
 
    fprintf (stderr, "memory error: %s\n",
 
315
    fprintf (stderr, "GnuTLS memory error: %s\n",
280
316
             safer_gnutls_strerror(ret));
281
317
    return -1;
282
318
  }
283
319
  
284
320
  if(debug){
285
321
    fprintf(stderr, "Attempting to use OpenPGP certificate %s"
286
 
            " and keyfile %s as GnuTLS credentials\n", certfile,
287
 
            certkey);
 
322
            " and keyfile %s as GnuTLS credentials\n", pubkeyfile,
 
323
            seckeyfile);
288
324
  }
289
325
  
290
326
  ret = gnutls_certificate_set_openpgp_key_file
291
 
    (es->cred, certfile, certkey, GNUTLS_OPENPGP_FMT_BASE64);
 
327
    (mc->cred, pubkeyfile, seckeyfile, GNUTLS_OPENPGP_FMT_BASE64);
292
328
  if (ret != GNUTLS_E_SUCCESS) {
293
 
    fprintf
294
 
      (stderr, "Error[%d] while reading the OpenPGP key pair ('%s',"
295
 
       " '%s')\n",
296
 
       ret, certfile, certkey);
297
 
    fprintf(stdout, "The Error is: %s\n",
 
329
    fprintf(stderr,
 
330
            "Error[%d] while reading the OpenPGP key pair ('%s',"
 
331
            " '%s')\n", ret, pubkeyfile, seckeyfile);
 
332
    fprintf(stdout, "The GnuTLS error is: %s\n",
298
333
            safer_gnutls_strerror(ret));
299
334
    return -1;
300
335
  }
301
336
  
302
 
  //GnuTLS server initialization
303
 
  if ((ret = gnutls_dh_params_init (&es->dh_params))
304
 
      != GNUTLS_E_SUCCESS) {
305
 
    fprintf (stderr, "Error in dh parameter initialization: %s\n",
306
 
             safer_gnutls_strerror(ret));
307
 
    return -1;
308
 
  }
309
 
  
310
 
  if ((ret = gnutls_dh_params_generate2 (es->dh_params, DH_BITS))
311
 
      != GNUTLS_E_SUCCESS) {
312
 
    fprintf (stderr, "Error in prime generation: %s\n",
313
 
             safer_gnutls_strerror(ret));
314
 
    return -1;
315
 
  }
316
 
  
317
 
  gnutls_certificate_set_dh_params (es->cred, es->dh_params);
318
 
  
319
 
  // GnuTLS session creation
320
 
  if ((ret = gnutls_init (&es->session, GNUTLS_SERVER))
321
 
      != GNUTLS_E_SUCCESS){
 
337
  /* GnuTLS server initialization */
 
338
  ret = gnutls_dh_params_init(dh_params);
 
339
  if (ret != GNUTLS_E_SUCCESS) {
 
340
    fprintf (stderr, "Error in GnuTLS DH parameter initialization:"
 
341
             " %s\n", safer_gnutls_strerror(ret));
 
342
    return -1;
 
343
  }
 
344
  ret = gnutls_dh_params_generate2(*dh_params, mc->dh_bits);
 
345
  if (ret != GNUTLS_E_SUCCESS) {
 
346
    fprintf (stderr, "Error in GnuTLS prime generation: %s\n",
 
347
             safer_gnutls_strerror(ret));
 
348
    return -1;
 
349
  }
 
350
  
 
351
  gnutls_certificate_set_dh_params(mc->cred, *dh_params);
 
352
  
 
353
  /* GnuTLS session creation */
 
354
  ret = gnutls_init(session, GNUTLS_SERVER);
 
355
  if (ret != GNUTLS_E_SUCCESS){
322
356
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
323
357
            safer_gnutls_strerror(ret));
324
358
  }
325
359
  
326
 
  if ((ret = gnutls_priority_set_direct (es->session, mc->priority, &err))
327
 
      != GNUTLS_E_SUCCESS) {
328
 
    fprintf(stderr, "Syntax error at: %s\n", err);
329
 
    fprintf(stderr, "GnuTLS error: %s\n",
330
 
            safer_gnutls_strerror(ret));
331
 
    return -1;
 
360
  {
 
361
    const char *err;
 
362
    ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
363
    if (ret != GNUTLS_E_SUCCESS) {
 
364
      fprintf(stderr, "Syntax error at: %s\n", err);
 
365
      fprintf(stderr, "GnuTLS error: %s\n",
 
366
              safer_gnutls_strerror(ret));
 
367
      return -1;
 
368
    }
332
369
  }
333
370
  
334
 
  if ((ret = gnutls_credentials_set
335
 
       (es->session, GNUTLS_CRD_CERTIFICATE, es->cred))
336
 
      != GNUTLS_E_SUCCESS) {
337
 
    fprintf(stderr, "Error setting a credentials set: %s\n",
 
371
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
372
                               mc->cred);
 
373
  if (ret != GNUTLS_E_SUCCESS) {
 
374
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
338
375
            safer_gnutls_strerror(ret));
339
376
    return -1;
340
377
  }
341
378
  
342
379
  /* ignore client certificate if any. */
343
 
  gnutls_certificate_server_set_request (es->session,
 
380
  gnutls_certificate_server_set_request (*session,
344
381
                                         GNUTLS_CERT_IGNORE);
345
382
  
346
 
  gnutls_dh_set_prime_bits (es->session, DH_BITS);
 
383
  gnutls_dh_set_prime_bits (*session, mc->dh_bits);
347
384
  
348
385
  return 0;
349
386
}
350
387
 
 
388
/* Avahi log function callback */
351
389
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
352
390
                      __attribute__((unused)) const char *txt){}
353
391
 
 
392
/* Called when a Mandos server is found */
354
393
static int start_mandos_communication(const char *ip, uint16_t port,
355
394
                                      AvahiIfIndex if_index,
356
395
                                      mandos_context *mc){
357
396
  int ret, tcp_sd;
358
397
  struct sockaddr_in6 to;
359
 
  encrypted_session es;
360
398
  char *buffer = NULL;
361
399
  char *decrypted_buffer;
362
400
  size_t buffer_length = 0;
363
401
  size_t buffer_capacity = 0;
364
402
  ssize_t decrypted_buffer_size;
365
 
  size_t written = 0;
 
403
  size_t written;
366
404
  int retval = 0;
367
405
  char interface[IF_NAMESIZE];
 
406
  gnutls_session_t session;
 
407
  gnutls_dh_params_t dh_params;
 
408
  
 
409
  ret = initgnutls (mc, &session, &dh_params);
 
410
  if (ret != 0){
 
411
    return -1;
 
412
  }
368
413
  
369
414
  if(debug){
370
415
    fprintf(stderr, "Setting up a tcp connection to %s, port %d\n",
379
424
 
380
425
  if(debug){
381
426
    if(if_indextoname((unsigned int)if_index, interface) == NULL){
382
 
      if(debug){
383
 
        perror("if_indextoname");
384
 
      }
 
427
      perror("if_indextoname");
385
428
      return -1;
386
429
    }
387
 
    
388
430
    fprintf(stderr, "Binding to interface %s\n", interface);
389
431
  }
390
432
  
391
433
  memset(&to,0,sizeof(to));     /* Spurious warning */
392
434
  to.sin6_family = AF_INET6;
 
435
  /* It would be nice to have a way to detect if we were passed an
 
436
     IPv4 address here.   Now we assume an IPv6 address. */
393
437
  ret = inet_pton(AF_INET6, ip, &to.sin6_addr);
394
438
  if (ret < 0 ){
395
439
    perror("inet_pton");
396
440
    return -1;
397
 
  }  
 
441
  }
398
442
  if(ret == 0){
399
443
    fprintf(stderr, "Bad address: %s\n", ip);
400
444
    return -1;
405
449
  
406
450
  if(debug){
407
451
    fprintf(stderr, "Connection to: %s, port %d\n", ip, port);
408
 
/*     char addrstr[INET6_ADDRSTRLEN]; */
409
 
/*     if(inet_ntop(to.sin6_family, &(to.sin6_addr), addrstr, */
410
 
/*               sizeof(addrstr)) == NULL){ */
411
 
/*       perror("inet_ntop"); */
412
 
/*     } else { */
413
 
/*       fprintf(stderr, "Really connecting to: %s, port %d\n", */
414
 
/*            addrstr, ntohs(to.sin6_port)); */
415
 
/*     } */
 
452
    char addrstr[INET6_ADDRSTRLEN] = "";
 
453
    if(inet_ntop(to.sin6_family, &(to.sin6_addr), addrstr,
 
454
                 sizeof(addrstr)) == NULL){
 
455
      perror("inet_ntop");
 
456
    } else {
 
457
      if(strcmp(addrstr, ip) != 0){
 
458
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
459
      }
 
460
    }
416
461
  }
417
462
  
418
463
  ret = connect(tcp_sd, (struct sockaddr *) &to, sizeof(to));
420
465
    perror("connect");
421
466
    return -1;
422
467
  }
423
 
  
424
 
  ret = initgnutls (&es);
425
 
  if (ret != 0){
426
 
    retval = -1;
427
 
    return -1;
 
468
 
 
469
  const char *out = mandos_protocol_version;
 
470
  written = 0;
 
471
  while (true){
 
472
    size_t out_size = strlen(out);
 
473
    ret = TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
 
474
                                   out_size - written));
 
475
    if (ret == -1){
 
476
      perror("write");
 
477
      retval = -1;
 
478
      goto mandos_end;
 
479
    }
 
480
    written += (size_t)ret;
 
481
    if(written < out_size){
 
482
      continue;
 
483
    } else {
 
484
      if (out == mandos_protocol_version){
 
485
        written = 0;
 
486
        out = "\r\n";
 
487
      } else {
 
488
        break;
 
489
      }
 
490
    }
428
491
  }
429
 
  
430
 
  gnutls_transport_set_ptr (es.session,
431
 
                            (gnutls_transport_ptr_t) tcp_sd);
432
 
  
 
492
 
433
493
  if(debug){
434
494
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
435
495
  }
436
496
  
437
 
  ret = gnutls_handshake (es.session);
 
497
  gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) tcp_sd);
 
498
  
 
499
  ret = gnutls_handshake (session);
438
500
  
439
501
  if (ret != GNUTLS_E_SUCCESS){
440
502
    if(debug){
441
 
      fprintf(stderr, "\n*** Handshake failed ***\n");
 
503
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
442
504
      gnutls_perror (ret);
443
505
    }
444
506
    retval = -1;
445
 
    goto exit;
 
507
    goto mandos_end;
446
508
  }
447
509
  
448
 
  //Retrieve OpenPGP packet that contains the wanted password
 
510
  /* Read OpenPGP packet that contains the wanted password */
449
511
  
450
512
  if(debug){
451
513
    fprintf(stderr, "Retrieving pgp encrypted password from %s\n",
453
515
  }
454
516
 
455
517
  while(true){
456
 
    if (buffer_length + BUFFER_SIZE > buffer_capacity){
457
 
      buffer = realloc(buffer, buffer_capacity + BUFFER_SIZE);
458
 
      if (buffer == NULL){
459
 
        perror("realloc");
460
 
        goto exit;
461
 
      }
462
 
      buffer_capacity += BUFFER_SIZE;
 
518
    buffer_capacity = adjustbuffer(&buffer, buffer_length, buffer_capacity);
 
519
    if (buffer_capacity == 0){
 
520
      perror("adjustbuffer");
 
521
      retval = -1;
 
522
      goto mandos_end;
463
523
    }
464
524
    
465
 
    ret = gnutls_record_recv
466
 
      (es.session, buffer+buffer_length, BUFFER_SIZE);
 
525
    ret = gnutls_record_recv(session, buffer+buffer_length,
 
526
                             BUFFER_SIZE);
467
527
    if (ret == 0){
468
528
      break;
469
529
    }
473
533
      case GNUTLS_E_AGAIN:
474
534
        break;
475
535
      case GNUTLS_E_REHANDSHAKE:
476
 
        ret = gnutls_handshake (es.session);
 
536
        ret = gnutls_handshake (session);
477
537
        if (ret < 0){
478
 
          fprintf(stderr, "\n*** Handshake failed ***\n");
 
538
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
479
539
          gnutls_perror (ret);
480
540
          retval = -1;
481
 
          goto exit;
 
541
          goto mandos_end;
482
542
        }
483
543
        break;
484
544
      default:
485
545
        fprintf(stderr, "Unknown error while reading data from"
486
 
                " encrypted session with mandos server\n");
 
546
                " encrypted session with Mandos server\n");
487
547
        retval = -1;
488
 
        gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
489
 
        goto exit;
 
548
        gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
549
        goto mandos_end;
490
550
      }
491
551
    } else {
492
552
      buffer_length += (size_t) ret;
493
553
    }
494
554
  }
495
555
  
 
556
  if(debug){
 
557
    fprintf(stderr, "Closing TLS session\n");
 
558
  }
 
559
  
 
560
  gnutls_bye (session, GNUTLS_SHUT_RDWR);
 
561
  
496
562
  if (buffer_length > 0){
497
563
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
498
564
                                               buffer_length,
499
565
                                               &decrypted_buffer,
500
 
                                               certdir);
 
566
                                               keydir);
501
567
    if (decrypted_buffer_size >= 0){
 
568
      written = 0;
502
569
      while(written < (size_t) decrypted_buffer_size){
503
570
        ret = (int)fwrite (decrypted_buffer + written, 1,
504
571
                           (size_t)decrypted_buffer_size - written,
518
585
      retval = -1;
519
586
    }
520
587
  }
521
 
 
522
 
  //shutdown procedure
523
 
 
524
 
  if(debug){
525
 
    fprintf(stderr, "Closing TLS session\n");
526
 
  }
527
 
 
 
588
  
 
589
  /* Shutdown procedure */
 
590
  
 
591
 mandos_end:
528
592
  free(buffer);
529
 
  gnutls_bye (es.session, GNUTLS_SHUT_RDWR);
530
 
 exit:
531
593
  close(tcp_sd);
532
 
  gnutls_deinit (es.session);
533
 
  gnutls_certificate_free_credentials (es.cred);
 
594
  gnutls_deinit (session);
 
595
  gnutls_certificate_free_credentials (mc->cred);
534
596
  gnutls_global_deinit ();
535
597
  return retval;
536
598
}
537
599
 
538
 
static void resolve_callback( AvahiSServiceResolver *r,
539
 
                              AvahiIfIndex interface,
540
 
                              AVAHI_GCC_UNUSED AvahiProtocol protocol,
541
 
                              AvahiResolverEvent event,
542
 
                              const char *name,
543
 
                              const char *type,
544
 
                              const char *domain,
545
 
                              const char *host_name,
546
 
                              const AvahiAddress *address,
547
 
                              uint16_t port,
548
 
                              AVAHI_GCC_UNUSED AvahiStringList *txt,
549
 
                              AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
550
 
                              AVAHI_GCC_UNUSED void* userdata) {
 
600
static void resolve_callback(AvahiSServiceResolver *r,
 
601
                             AvahiIfIndex interface,
 
602
                             AVAHI_GCC_UNUSED AvahiProtocol protocol,
 
603
                             AvahiResolverEvent event,
 
604
                             const char *name,
 
605
                             const char *type,
 
606
                             const char *domain,
 
607
                             const char *host_name,
 
608
                             const AvahiAddress *address,
 
609
                             uint16_t port,
 
610
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
 
611
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
612
                             flags,
 
613
                             void* userdata) {
551
614
  mandos_context *mc = userdata;
552
615
  assert(r);                    /* Spurious warning */
553
616
  
557
620
  switch (event) {
558
621
  default:
559
622
  case AVAHI_RESOLVER_FAILURE:
560
 
    fprintf(stderr, "(Resolver) Failed to resolve service '%s' of"
561
 
            " type '%s' in domain '%s': %s\n", name, type, domain,
 
623
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
624
            " of type '%s' in domain '%s': %s\n", name, type, domain,
562
625
            avahi_strerror(avahi_server_errno(mc->server)));
563
626
    break;
564
627
    
567
630
      char ip[AVAHI_ADDRESS_STR_MAX];
568
631
      avahi_address_snprint(ip, sizeof(ip), address);
569
632
      if(debug){
570
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s) on"
571
 
                " port %d\n", name, host_name, ip, port);
 
633
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %d) on"
 
634
                " port %d\n", name, host_name, ip, interface, port);
572
635
      }
573
636
      int ret = start_mandos_communication(ip, port, interface, mc);
574
637
      if (ret == 0){
586
649
                             const char *name,
587
650
                             const char *type,
588
651
                             const char *domain,
589
 
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
 
652
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
 
653
                             flags,
590
654
                             void* userdata) {
591
655
  mandos_context *mc = userdata;
592
656
  assert(b);                    /* Spurious warning */
597
661
  switch (event) {
598
662
  default:
599
663
  case AVAHI_BROWSER_FAILURE:
600
 
      
601
 
    fprintf(stderr, "(Browser) %s\n",
 
664
    
 
665
    fprintf(stderr, "(Avahi browser) %s\n",
602
666
            avahi_strerror(avahi_server_errno(mc->server)));
603
667
    avahi_simple_poll_quit(mc->simple_poll);
604
668
    return;
605
 
      
 
669
    
606
670
  case AVAHI_BROWSER_NEW:
607
 
    /* We ignore the returned resolver object. In the callback
608
 
       function we free it. If the server is terminated before
609
 
       the callback function is called the server will free
610
 
       the resolver for us. */
611
 
      
612
 
    if (!(avahi_s_service_resolver_new(mc->server, interface, protocol, name,
613
 
                                       type, domain,
 
671
    /* We ignore the returned Avahi resolver object. In the callback
 
672
       function we free it. If the Avahi server is terminated before
 
673
       the callback function is called the Avahi server will free the
 
674
       resolver for us. */
 
675
    
 
676
    if (!(avahi_s_service_resolver_new(mc->server, interface,
 
677
                                       protocol, name, type, domain,
614
678
                                       AVAHI_PROTO_INET6, 0,
615
679
                                       resolve_callback, mc)))
616
 
      fprintf(stderr, "Failed to resolve service '%s': %s\n", name,
617
 
              avahi_strerror(avahi_server_errno(s)));
 
680
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
681
              name, avahi_strerror(avahi_server_errno(mc->server)));
618
682
    break;
619
 
      
 
683
    
620
684
  case AVAHI_BROWSER_REMOVE:
621
685
    break;
622
 
      
 
686
    
623
687
  case AVAHI_BROWSER_ALL_FOR_NOW:
624
688
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
 
689
    if(debug){
 
690
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
691
    }
625
692
    break;
626
693
  }
627
694
}
636
703
    return NULL;
637
704
  }
638
705
  if(f_len > 0){
639
 
    memcpy(tmp, first, f_len);
 
706
    memcpy(tmp, first, f_len);  /* Spurious warning */
640
707
  }
641
708
  tmp[f_len] = '/';
642
709
  if(s_len > 0){
643
 
    memcpy(tmp + f_len + 1, second, s_len);
 
710
    memcpy(tmp + f_len + 1, second, s_len); /* Spurious warning */
644
711
  }
645
712
  tmp[f_len + 1 + s_len] = '\0';
646
713
  return tmp;
647
714
}
648
715
 
649
716
 
650
 
int main(AVAHI_GCC_UNUSED int argc, AVAHI_GCC_UNUSED char*argv[]) {
651
 
    AvahiServerConfig config;
 
717
int main(int argc, char *argv[]){
652
718
    AvahiSServiceBrowser *sb = NULL;
653
719
    int error;
654
720
    int ret;
655
 
    int returncode = EXIT_SUCCESS;
 
721
    int exitcode = EXIT_SUCCESS;
656
722
    const char *interface = "eth0";
657
723
    struct ifreq network;
658
724
    int sd;
659
725
    char *connect_to = NULL;
660
726
    AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
661
727
    mandos_context mc = { .simple_poll = NULL, .server = NULL,
662
 
                          .dh_bits = 2048, .priority = "SECURE256"};
 
728
                          .dh_bits = 1024, .priority = "SECURE256"};
663
729
    
664
 
    while (true){
665
 
      static struct option long_options[] = {
666
 
        {"debug", no_argument, (int *)&debug, 1},
667
 
        {"connect", required_argument, 0, 'C'},
668
 
        {"interface", required_argument, 0, 'i'},
669
 
        {"certdir", required_argument, 0, 'd'},
670
 
        {"certkey", required_argument, 0, 'c'},
671
 
        {"certfile", required_argument, 0, 'k'},
672
 
        {"dh_bits", required_argument, 0, 'D'},
673
 
        {"priority", required_argument, 0, 'p'},
674
 
        {0, 0, 0, 0} };
675
 
      
676
 
      int option_index = 0;
677
 
      ret = getopt_long (argc, argv, "i:", long_options,
678
 
                         &option_index);
679
 
      
680
 
      if (ret == -1){
681
 
        break;
682
 
      }
683
 
      
684
 
      switch(ret){
685
 
      case 0:
686
 
        break;
687
 
      case 'i':
688
 
        interface = optarg;
689
 
        break;
690
 
      case 'C':
691
 
        connect_to = optarg;
692
 
        break;
693
 
      case 'd':
694
 
        certdir = optarg;
695
 
        break;
696
 
      case 'c':
697
 
        certfile = optarg;
698
 
        break;
699
 
      case 'k':
700
 
        certkey = optarg;
701
 
        break;
702
 
      case 'D':
703
 
        {
704
 
          long int tmp;
 
730
    {
 
731
      /* Temporary int to get the address of for getopt_long */
 
732
      int debug_int = debug ? 1 : 0;
 
733
      while (true){
 
734
        struct option long_options[] = {
 
735
          {"debug", no_argument, &debug_int, 1},
 
736
          {"connect", required_argument, NULL, 'c'},
 
737
          {"interface", required_argument, NULL, 'i'},
 
738
          {"keydir", required_argument, NULL, 'd'},
 
739
          {"seckey", required_argument, NULL, 's'},
 
740
          {"pubkey", required_argument, NULL, 'p'},
 
741
          {"dh-bits", required_argument, NULL, 'D'},
 
742
          {"priority", required_argument, NULL, 'P'},
 
743
          {0, 0, 0, 0} };
 
744
      
 
745
        int option_index = 0;
 
746
        ret = getopt_long (argc, argv, "i:", long_options,
 
747
                           &option_index);
 
748
      
 
749
        if (ret == -1){
 
750
          break;
 
751
        }
 
752
      
 
753
        switch(ret){
 
754
        case 0:
 
755
          break;
 
756
        case 'i':
 
757
          interface = optarg;
 
758
          break;
 
759
        case 'c':
 
760
          connect_to = optarg;
 
761
          break;
 
762
        case 'd':
 
763
          keydir = optarg;
 
764
          break;
 
765
        case 'p':
 
766
          pubkeyfile = optarg;
 
767
          break;
 
768
        case 's':
 
769
          seckeyfile = optarg;
 
770
          break;
 
771
        case 'D':
705
772
          errno = 0;
706
 
          tmp = strtol(optarg, NULL, 10);
707
 
          if (errno == ERANGE){
 
773
          mc.dh_bits = (unsigned int) strtol(optarg, NULL, 10);
 
774
          if (errno){
708
775
            perror("strtol");
709
776
            exit(EXIT_FAILURE);
710
777
          }
711
 
          mc.dh_bits = tmp;
 
778
          break;
 
779
        case 'P':
 
780
          mc.priority = optarg;
 
781
          break;
 
782
        case '?':
 
783
        default:
 
784
          /* getopt_long() has already printed a message about the
 
785
             unrcognized option, so just exit. */
 
786
          exit(EXIT_FAILURE);
712
787
        }
713
 
        break;
714
 
      case 'p':
715
 
        mc.priority = optarg;
716
 
        break;
717
 
      default:
718
 
        exit(EXIT_FAILURE);
719
788
      }
720
 
    }
721
 
    
722
 
    certfile = combinepath(certdir, certfile);
723
 
    if (certfile == NULL){
724
 
      perror("combinepath");
725
 
      returncode = EXIT_FAILURE;
726
 
      goto exit;
727
 
    }
728
 
 
729
 
    certkey = combinepath(certdir, certkey);
730
 
    if (certkey == NULL){
731
 
      perror("combinepath");
732
 
      returncode = EXIT_FAILURE;
733
 
      goto exit;
 
789
      /* Set the global debug flag from the temporary int */
 
790
      debug = debug_int ? true : false;
 
791
    }
 
792
    
 
793
    pubkeyfile = combinepath(keydir, pubkeyfile);
 
794
    if (pubkeyfile == NULL){
 
795
      perror("combinepath");
 
796
      exitcode = EXIT_FAILURE;
 
797
      goto end;
 
798
    }
 
799
    
 
800
    seckeyfile = combinepath(keydir, seckeyfile);
 
801
    if (seckeyfile == NULL){
 
802
      perror("combinepath");
 
803
      goto end;
734
804
    }
735
805
    
736
806
    if_index = (AvahiIfIndex) if_nametoindex(interface);
755
825
      }
756
826
      *address = '\0';
757
827
      address = connect_to;
758
 
      ret = start_mandos_communication(address, port, if_index);
 
828
      ret = start_mandos_communication(address, port, if_index, &mc);
759
829
      if(ret < 0){
760
830
        exit(EXIT_FAILURE);
761
831
      } else {
763
833
      }
764
834
    }
765
835
    
766
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
767
 
    if(sd < 0) {
768
 
      perror("socket");
769
 
      returncode = EXIT_FAILURE;
770
 
      goto exit;
771
 
    }
772
 
    strcpy(network.ifr_name, interface);    
773
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
774
 
    if(ret == -1){
775
 
      
776
 
      perror("ioctl SIOCGIFFLAGS");
777
 
      returncode = EXIT_FAILURE;
778
 
      goto exit;
779
 
    }
780
 
    if((network.ifr_flags & IFF_UP) == 0){
781
 
      network.ifr_flags |= IFF_UP;
782
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
836
    /* If the interface is down, bring it up */
 
837
    {
 
838
      sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
839
      if(sd < 0) {
 
840
        perror("socket");
 
841
        exitcode = EXIT_FAILURE;
 
842
        goto end;
 
843
      }
 
844
      strcpy(network.ifr_name, interface); /* Spurious warning */
 
845
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
783
846
      if(ret == -1){
784
 
        perror("ioctl SIOCSIFFLAGS");
785
 
        returncode = EXIT_FAILURE;
786
 
        goto exit;
787
 
      }
 
847
        perror("ioctl SIOCGIFFLAGS");
 
848
        exitcode = EXIT_FAILURE;
 
849
        goto end;
 
850
      }
 
851
      if((network.ifr_flags & IFF_UP) == 0){
 
852
        network.ifr_flags |= IFF_UP;
 
853
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
854
        if(ret == -1){
 
855
          perror("ioctl SIOCSIFFLAGS");
 
856
          exitcode = EXIT_FAILURE;
 
857
          goto end;
 
858
        }
 
859
      }
 
860
      close(sd);
788
861
    }
789
 
    close(sd);
790
862
    
791
863
    if (not debug){
792
864
      avahi_set_log_function(empty_log);
793
865
    }
794
866
    
795
 
    /* Initialize the psuedo-RNG */
 
867
    /* Initialize the pseudo-RNG for Avahi */
796
868
    srand((unsigned int) time(NULL));
797
 
 
798
 
    /* Allocate main loop object */
799
 
    if (!(mc.simple_poll = avahi_simple_poll_new())) {
800
 
        fprintf(stderr, "Failed to create simple poll object.\n");
801
 
        returncode = EXIT_FAILURE;      
802
 
        goto exit;
803
 
    }
804
 
 
805
 
    /* Do not publish any local records */
806
 
    avahi_server_config_init(&config);
807
 
    config.publish_hinfo = 0;
808
 
    config.publish_addresses = 0;
809
 
    config.publish_workstation = 0;
810
 
    config.publish_domain = 0;
811
 
 
812
 
    /* Allocate a new server */
813
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
814
 
                              &config, NULL, NULL, &error);
815
 
 
816
 
    /* Free the configuration data */
817
 
    avahi_server_config_free(&config);
818
 
 
819
 
    /* Check if creating the server object succeeded */
820
 
    if (!mc.server) {
821
 
        fprintf(stderr, "Failed to create server: %s\n",
 
869
    
 
870
    /* Allocate main Avahi loop object */
 
871
    mc.simple_poll = avahi_simple_poll_new();
 
872
    if (mc.simple_poll == NULL) {
 
873
        fprintf(stderr, "Avahi: Failed to create simple poll"
 
874
                " object.\n");
 
875
        exitcode = EXIT_FAILURE;
 
876
        goto end;
 
877
    }
 
878
 
 
879
    {
 
880
      AvahiServerConfig config;
 
881
      /* Do not publish any local Zeroconf records */
 
882
      avahi_server_config_init(&config);
 
883
      config.publish_hinfo = 0;
 
884
      config.publish_addresses = 0;
 
885
      config.publish_workstation = 0;
 
886
      config.publish_domain = 0;
 
887
 
 
888
      /* Allocate a new server */
 
889
      mc.server = avahi_server_new(avahi_simple_poll_get
 
890
                                   (mc.simple_poll), &config, NULL,
 
891
                                   NULL, &error);
 
892
    
 
893
      /* Free the Avahi configuration data */
 
894
      avahi_server_config_free(&config);
 
895
    }
 
896
    
 
897
    /* Check if creating the Avahi server object succeeded */
 
898
    if (mc.server == NULL) {
 
899
        fprintf(stderr, "Failed to create Avahi server: %s\n",
822
900
                avahi_strerror(error));
823
 
        returncode = EXIT_FAILURE;
824
 
        goto exit;
 
901
        exitcode = EXIT_FAILURE;
 
902
        goto end;
825
903
    }
826
904
    
827
 
    /* Create the service browser */
 
905
    /* Create the Avahi service browser */
828
906
    sb = avahi_s_service_browser_new(mc.server, if_index,
829
907
                                     AVAHI_PROTO_INET6,
830
908
                                     "_mandos._tcp", NULL, 0,
831
909
                                     browse_callback, &mc);
832
 
    if (!sb) {
 
910
    if (sb == NULL) {
833
911
        fprintf(stderr, "Failed to create service browser: %s\n",
834
912
                avahi_strerror(avahi_server_errno(mc.server)));
835
 
        returncode = EXIT_FAILURE;
836
 
        goto exit;
 
913
        exitcode = EXIT_FAILURE;
 
914
        goto end;
837
915
    }
838
916
    
839
917
    /* Run the main loop */
840
918
 
841
919
    if (debug){
842
 
      fprintf(stderr, "Starting avahi loop search\n");
 
920
      fprintf(stderr, "Starting Avahi loop search\n");
843
921
    }
844
922
    
845
 
    avahi_simple_poll_loop(simple_poll);
 
923
    avahi_simple_poll_loop(mc.simple_poll);
846
924
    
847
 
 exit:
 
925
 end:
848
926
 
849
927
    if (debug){
850
928
      fprintf(stderr, "%s exiting\n", argv[0]);
851
929
    }
852
930
    
853
931
    /* Cleanup things */
854
 
    if (sb)
 
932
    if (sb != NULL)
855
933
        avahi_s_service_browser_free(sb);
856
934
    
857
 
    if (mc.server)
 
935
    if (mc.server != NULL)
858
936
        avahi_server_free(mc.server);
859
937
 
860
 
    if (simple_poll)
861
 
        avahi_simple_poll_free(simple_poll);
862
 
    free(certfile);
863
 
    free(certkey);
 
938
    if (mc.simple_poll != NULL)
 
939
        avahi_simple_poll_free(mc.simple_poll);
 
940
    free(pubkeyfile);
 
941
    free(seckeyfile);
864
942
    
865
 
    return returncode;
 
943
    return exitcode;
866
944
}