~ubuntu-branches/ubuntu/saucy/openvpn/saucy

« back to all changes in this revision

Viewing changes to ssl.c

  • Committer: Bazaar Package Importer
  • Author(s): Alberto Gonzalez Iniesta
  • Date: 2005-01-05 19:03:11 UTC
  • mto: (1.4.1) (10.1.1 lenny)
  • mto: This revision was merged to the branch mainline in revision 3.
  • Revision ID: james.westby@ubuntu.com-20050105190311-d0uioiqtor5xbzre
Tags: upstream-1.99+2.rc6
ImportĀ upstreamĀ versionĀ 1.99+2.rc6

Show diffs side-by-side

added added

removed removed

Lines of Context:
50
50
#include "misc.h"
51
51
#include "fdmisc.h"
52
52
#include "interval.h"
53
 
#include "options.h"
 
53
#include "perf.h"
 
54
#include "status.h"
 
55
#include "gremlin.h"
 
56
 
 
57
#ifdef WIN32
 
58
#include "cryptoapi.h"
 
59
#endif
54
60
 
55
61
#include "memdbg.h"
56
62
 
 
63
#ifndef ENABLE_OCC
 
64
static const char ssl_default_options_string[] = "V0 UNDEF";
 
65
#endif
 
66
 
 
67
static inline const char *
 
68
local_options_string (const struct tls_session *session)
 
69
{
 
70
#ifdef ENABLE_OCC
 
71
  return session->opt->local_options;
 
72
#else
 
73
  return ssl_default_options_string;
 
74
#endif
 
75
}
 
76
 
57
77
#ifdef MEASURE_TLS_HANDSHAKE_STATS
58
78
 
59
 
static int tls_handshake_success;
60
 
static int tls_handshake_error;
61
 
static int tls_packets_generated;
62
 
static int tls_packets_sent;
 
79
static int tls_handshake_success; /* GLOBAL */
 
80
static int tls_handshake_error;   /* GLOBAL */
 
81
static int tls_packets_generated; /* GLOBAL */
 
82
static int tls_packets_sent;      /* GLOBAL */
63
83
 
64
84
#define INCR_SENT       ++tls_packets_sent
65
85
#define INCR_GENERATED  ++tls_packets_generated
85
105
 
86
106
#ifdef BIO_DEBUG
87
107
 
88
 
static FILE *biofp;
89
 
static bool biofp_toggle;
90
 
static time_t biofp_last_open;
91
 
static const int biofp_reopen_interval = 600;
 
108
#warning BIO_DEBUG defined
 
109
 
 
110
static FILE *biofp;                            /* GLOBAL */
 
111
static bool biofp_toggle;                      /* GLOBAL */
 
112
static time_t biofp_last_open;                 /* GLOBAL */
 
113
static const int biofp_reopen_interval = 600;  /* GLOBAL */
92
114
 
93
115
static void
94
116
close_biofp()
120
142
}
121
143
 
122
144
static void
123
 
bio_debug_data (const char *mode, BIO *bio, uint8_t *buf, int len, const char *desc)
 
145
bio_debug_data (const char *mode, BIO *bio, const uint8_t *buf, int len, const char *desc)
124
146
{
 
147
  struct gc_arena gc = gc_new ();
125
148
  if (len > 0)
126
149
    {
127
150
      open_biofp();
128
151
      fprintf(biofp, "BIO_%s %s time=" time_format " bio=" ptr_format " len=%d data=%s\n",
129
 
              mode, desc, time (NULL), bio, len, format_hex (buf, len, 0));
 
152
              mode, desc, time (NULL), (ptr_type)bio, len, format_hex (buf, len, 0, &gc));
130
153
      fflush (biofp);
131
154
    }
 
155
  gc_free (&gc);
132
156
}
133
157
 
134
158
static void
136
160
{
137
161
  open_biofp();
138
162
  fprintf(biofp, "BIO %s time=" time_format " bio=" ptr_format "\n",
139
 
          mode, time (NULL), bio);
 
163
          mode, time (NULL), (ptr_type)bio);
140
164
  fflush (biofp);
141
165
}
142
166
 
180
204
  frame_set_mtu_dynamic (frame, 0, SET_MTU_TUN);
181
205
}
182
206
 
 
207
/*
 
208
 * Allocate space in SSL objects
 
209
 * in which to store a struct tls_session
 
210
 * pointer back to parent.
 
211
 */
 
212
 
 
213
static int mydata_index; /* GLOBAL */
 
214
 
 
215
static void
 
216
ssl_set_mydata_index ()
 
217
{
 
218
  mydata_index = SSL_get_ex_new_index (0, "struct session *", NULL, NULL, NULL);
 
219
  ASSERT (mydata_index >= 0);
 
220
}
 
221
 
183
222
void
184
223
init_ssl_lib ()
185
224
{
197
236
#ifdef CRYPTO_MDEBUG
198
237
  CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
199
238
#endif
 
239
 
 
240
  ssl_set_mydata_index ();
200
241
}
201
242
 
202
243
void
209
250
  fclose (fp);
210
251
#endif
211
252
 
 
253
  uninit_crypto_lib ();
212
254
  EVP_cleanup ();
213
255
  ERR_free_strings ();
214
256
}
215
257
 
216
258
/*
217
 
 * OpenSSL library calls back here if the private key
218
 
 * is protected by a password.
 
259
 * OpenSSL library calls pem_password_callback if the
 
260
 * private key is protected by a password.
219
261
 */
 
262
 
 
263
static struct user_pass passbuf; /* GLOBAL */
 
264
 
 
265
void
 
266
pem_password_setup (const char *auth_file)
 
267
{
 
268
  if (!strlen (passbuf.password))
 
269
    get_user_pass (&passbuf, auth_file, true, UP_TYPE_PRIVATE_KEY, GET_USER_PASS_MANAGEMENT|GET_USER_PASS_SENSITIVE);
 
270
}
 
271
 
220
272
int
221
273
pem_password_callback (char *buf, int size, int rwflag, void *u)
222
274
{
223
 
#ifdef HAVE_GETPASS
224
 
  static char passbuf[256];
225
 
 
226
 
  if (!strlen (passbuf))
227
 
    {
228
 
      char *gp = getpass ("Enter PEM pass phrase:");
229
 
      if (!gp)
230
 
        msg (M_FATAL, "TLS Error: Error reading PEM pass phrase for private key");
231
 
      strncpynt (passbuf, gp, sizeof (passbuf));
232
 
      memset (gp, 0, strlen (gp));
233
 
    }
234
 
 
235
275
  if (buf)
236
276
    {
237
 
      if (!strlen (passbuf))
238
 
        msg (M_FATAL, "TLS Error: Need PEM pass phrase for private key");
239
 
      strncpynt (buf, passbuf, size);
240
 
      CLEAR (passbuf);
 
277
      /* prompt for password even if --askpass wasn't specified */
 
278
      pem_password_setup (NULL);
 
279
      strncpynt (buf, passbuf.password, size);
 
280
      purge_user_pass (&passbuf);
 
281
 
241
282
      return strlen (buf);
242
283
    }
243
 
#else
244
 
  msg (M_FATAL, "Sorry but I can't read a password from the console because this operating system or C library doesn't support the getpass() function");
245
 
#endif
246
284
  return 0;
247
285
}
248
286
 
249
287
/*
 
288
 * Auth username/password handling
 
289
 */
 
290
 
 
291
static bool auth_user_pass_enabled;     /* GLOBAL */
 
292
static struct user_pass auth_user_pass; /* GLOBAL */
 
293
 
 
294
void
 
295
auth_user_pass_setup (const char *auth_file)
 
296
{
 
297
  auth_user_pass_enabled = true;
 
298
  if (!auth_user_pass.defined)
 
299
    get_user_pass (&auth_user_pass, auth_file, false, UP_TYPE_AUTH, GET_USER_PASS_MANAGEMENT|GET_USER_PASS_SENSITIVE);
 
300
}
 
301
 
 
302
/*
 
303
 * Disable password caching
 
304
 */
 
305
void
 
306
ssl_set_auth_nocache (void)
 
307
{
 
308
  passbuf.nocache = true;
 
309
  auth_user_pass.nocache = true;
 
310
}
 
311
 
 
312
/*
250
313
 * OpenSSL callback to get a temporary RSA key, mostly
251
314
 * used for export ciphers.
252
315
 */
263
326
}
264
327
 
265
328
/*
 
329
 * Extract a field from an X509 subject name.
 
330
 *
 
331
 * Example:
 
332
 *
 
333
 * /C=US/ST=CO/L=Denver/O=ORG/CN=Test-CA/Email=jim@yonan.net
 
334
 *
 
335
 * The common name is 'Test-CA'
 
336
 */
 
337
static void
 
338
extract_x509_field (const char *x509, const char *field_name, char *out, int size)
 
339
{
 
340
  char field_buf[256];
 
341
  struct buffer x509_buf;
 
342
 
 
343
  ASSERT (size > 0);
 
344
  *out = '\0';
 
345
  buf_set_read (&x509_buf, (uint8_t *)x509, strlen (x509));
 
346
  while (buf_parse (&x509_buf, '/', field_buf, sizeof (field_buf)))
 
347
    {
 
348
      struct buffer component_buf;
 
349
      char field_name_buf[64];
 
350
      char field_value_buf[256];
 
351
      buf_set_read (&component_buf, field_buf, strlen (field_buf));
 
352
      buf_parse (&component_buf, '=', field_name_buf, sizeof (field_name_buf));
 
353
      buf_parse (&component_buf, '=', field_value_buf, sizeof (field_value_buf));
 
354
      if (!strcmp (field_name_buf, field_name))
 
355
        {
 
356
          strncpynt (out, field_value_buf, size);
 
357
          break;
 
358
        }
 
359
    }
 
360
}
 
361
 
 
362
static void
 
363
setenv_untrusted (struct tls_session *session)
 
364
{
 
365
  setenv_sockaddr (session->opt->es, "untrusted", &session->untrusted_sockaddr, SA_IP_PORT);
 
366
}
 
367
 
 
368
static void
 
369
set_common_name (struct tls_session *session, const char *common_name)
 
370
{
 
371
  if (session->common_name)
 
372
    {
 
373
      free (session->common_name);
 
374
      session->common_name = NULL;
 
375
    }
 
376
  if (common_name)
 
377
    {
 
378
      session->common_name = string_alloc (common_name, NULL);
 
379
    }
 
380
}
 
381
 
 
382
/*
 
383
 * nsCertType checking
 
384
 */
 
385
 
 
386
#define verify_nsCertType(x, usage) (((x)->ex_flags & EXFLAG_NSCERT) && ((x)->ex_nscert & (usage)))
 
387
 
 
388
static const char *
 
389
print_nsCertType (int type)
 
390
{
 
391
  switch (type)
 
392
    {
 
393
    case NS_SSL_SERVER:
 
394
      return "SERVER";
 
395
    case NS_SSL_CLIENT:
 
396
      return "CLIENT";
 
397
    default:
 
398
      return "?";
 
399
    }
 
400
}
 
401
 
 
402
/*
266
403
 * Our verify callback function -- check
267
404
 * that an incoming peer certificate is good.
268
405
 */
269
406
 
270
 
static const char *verify_command;
271
 
static const char *verify_x509name;
272
 
static const char *crl_file;
273
 
static int verify_maxlevel;
274
 
 
275
 
void
276
 
tls_set_verify_command (const char *cmd)
277
 
{
278
 
  verify_command = cmd;
279
 
}
280
 
 
281
 
void
282
 
tls_set_verify_x509name (const char *x509name)
283
 
{
284
 
  verify_x509name = x509name;
285
 
}
286
 
 
287
 
void
288
 
tls_set_crl_verify (const char *crl)
289
 
{
290
 
  crl_file = crl;
291
 
}
292
 
 
293
 
int
294
 
get_max_tls_verify_id ()
295
 
{
296
 
  return verify_maxlevel;
297
 
}
298
 
 
299
407
static int
300
408
verify_callback (int preverify_ok, X509_STORE_CTX * ctx)
301
409
{
302
 
  char txt[512];
 
410
  char subject[256];
303
411
  char envname[64];
 
412
  char common_name[TLS_CN_LEN];
 
413
  SSL *ssl;
 
414
  struct tls_session *session;
 
415
  const struct tls_options *opt;
304
416
  const int max_depth = 8;
305
417
 
306
 
  X509_NAME_oneline (X509_get_subject_name (ctx->current_cert), txt,
307
 
                     sizeof (txt));
308
 
  txt[sizeof (txt) - 1] = '\0';
309
 
  safe_string (txt);
310
 
 
 
418
  /* get the tls_session pointer */
 
419
  ssl = X509_STORE_CTX_get_ex_data (ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
 
420
  ASSERT (ssl);
 
421
  session = (struct tls_session *) SSL_get_ex_data (ssl, mydata_index);
 
422
  ASSERT (session);
 
423
  opt = session->opt;
 
424
  ASSERT (opt);
 
425
 
 
426
  session->verified = false;
 
427
 
 
428
  /* get the X509 name */
 
429
  X509_NAME_oneline (X509_get_subject_name (ctx->current_cert), subject,
 
430
                     sizeof (subject));
 
431
  subject[sizeof (subject) - 1] = '\0';
 
432
 
 
433
  /* enforce character class restrictions in X509 name */
 
434
  string_mod (subject, X509_NAME_CHAR_CLASS, 0, '_');
 
435
 
 
436
  /* extract the common name */
 
437
  extract_x509_field (subject, "CN", common_name, TLS_CN_LEN);
 
438
  string_mod (common_name, COMMON_NAME_CHAR_CLASS, 0, '_');
 
439
 
 
440
#if 0 /* print some debugging info */
 
441
  msg (D_LOW, "LOCAL OPT: %s", opt->local_options);
 
442
  msg (D_LOW, "X509: %s", subject);
 
443
#endif
 
444
 
 
445
  /* did peer present cert which was signed our root cert? */
311
446
  if (!preverify_ok)
312
447
    {
313
448
      /* Remote site specified a certificate, but it's not correct */
314
449
      msg (D_TLS_ERRORS, "VERIFY ERROR: depth=%d, error=%s: %s",
315
 
           ctx->error_depth, X509_verify_cert_error_string (ctx->error), txt);
316
 
      return 0;                 /* Reject connection */
 
450
           ctx->error_depth, X509_verify_cert_error_string (ctx->error), subject);
 
451
      goto err;                 /* Reject connection */
317
452
    }
318
453
 
 
454
  /* warn if cert chain is too deep */
319
455
  if (ctx->error_depth >= max_depth)
320
456
    msg (M_WARN, "TLS Warning: Convoluted certificate chain detected with depth [%d] greater than %d", ctx->error_depth, max_depth);
321
457
 
 
458
  /* save common name in session object */
 
459
  if (ctx->error_depth == 0)
 
460
    set_common_name (session, common_name);
 
461
 
322
462
  /* export subject name string as environmental variable */
323
 
  verify_maxlevel = max_int (verify_maxlevel, ctx->error_depth);
 
463
  session->verify_maxlevel = max_int (session->verify_maxlevel, ctx->error_depth);
324
464
  openvpn_snprintf (envname, sizeof(envname), "tls_id_%d", ctx->error_depth);
325
 
  setenv_str (envname, txt);
 
465
  setenv_str (opt->es, envname, subject);
 
466
 
 
467
#if 0
 
468
  /* export common name string as environmental variable */
 
469
  openvpn_snprintf (envname, sizeof(envname), "tls_common_name_%d", ctx->error_depth);
 
470
  setenv_str (opt->es, envname, common_name);
 
471
#endif
326
472
 
327
473
  /* export serial number as environmental variable */
328
474
  {
329
475
    const int serial = (int) ASN1_INTEGER_get (X509_get_serialNumber (ctx->current_cert));
330
476
    openvpn_snprintf (envname, sizeof(envname), "tls_serial_%d", ctx->error_depth);
331
 
    setenv_int (envname, serial);
 
477
    setenv_int (opt->es, envname, serial);
332
478
  }
333
 
  
334
 
  if (verify_x509name)
335
 
    if (ctx->error_depth == 0)
336
 
      {
337
 
        if (strcmp (verify_x509name, txt) == 0)
338
 
          msg (D_HANDSHAKE, "VERIFY X509NAME OK: %s", txt);
339
 
        else
340
 
          {
341
 
            msg (D_HANDSHAKE, "VERIFY X509NAME ERROR: %s, must be %s",
342
 
                 txt, verify_x509name);
343
 
            return 0;           /* Reject connection */
344
 
          }
345
 
      }
346
 
 
347
 
  if (verify_command)
348
 
    {
349
 
      char command[512];
350
 
      struct buffer out;
351
 
      int ret;
352
 
 
353
 
      setenv_str ("script_type", "tls-verify");
 
479
 
 
480
  /* export current untrusted IP */
 
481
  setenv_untrusted (session);
 
482
 
 
483
  /* verify certificate nsCertType */
 
484
  if (opt->ns_cert_type && ctx->error_depth == 0)
 
485
    {
 
486
      if (verify_nsCertType (ctx->current_cert, opt->ns_cert_type))
 
487
        {
 
488
          msg (D_HANDSHAKE, "VERIFY OK: nsCertType=%s",
 
489
               print_nsCertType (opt->ns_cert_type));
 
490
        }
 
491
      else
 
492
        {
 
493
          msg (D_HANDSHAKE, "VERIFY nsCertType ERROR: %s, require nsCertType=%s",
 
494
               subject, print_nsCertType (opt->ns_cert_type));
 
495
          goto err;             /* Reject connection */
 
496
        }
 
497
    }
 
498
 
 
499
  /* verify X509 name or common name against --tls-remote */
 
500
  if (opt->verify_x509name && strlen (opt->verify_x509name) > 0 && ctx->error_depth == 0)
 
501
    {
 
502
      if (strcmp (opt->verify_x509name, subject) == 0
 
503
          || strncmp (opt->verify_x509name, common_name, strlen (opt->verify_x509name)) == 0)
 
504
        msg (D_HANDSHAKE, "VERIFY X509NAME OK: %s", subject);
 
505
      else
 
506
        {
 
507
          msg (D_HANDSHAKE, "VERIFY X509NAME ERROR: %s, must be %s",
 
508
               subject, opt->verify_x509name);
 
509
          goto err;             /* Reject connection */
 
510
        }
 
511
    }
 
512
 
 
513
  /* call --tls-verify plug-in(s) */
 
514
  if (plugin_defined (opt->plugins, OPENVPN_PLUGIN_TLS_VERIFY))
 
515
    {
 
516
      char command[256];
 
517
      struct buffer out;
 
518
      int ret;
 
519
 
 
520
      buf_set_write (&out, (uint8_t*)command, sizeof (command));
 
521
      buf_printf (&out, "%d %s",
 
522
                  ctx->error_depth,
 
523
                  subject);
 
524
 
 
525
      ret = plugin_call (opt->plugins, OPENVPN_PLUGIN_TLS_VERIFY, command, opt->es);
 
526
 
 
527
      if (!ret)
 
528
        {
 
529
          msg (D_HANDSHAKE, "VERIFY PLUGIN OK: depth=%d, %s",
 
530
               ctx->error_depth, subject);
 
531
        }
 
532
      else
 
533
        {
 
534
          msg (D_HANDSHAKE, "VERIFY PLUGIN ERROR: depth=%d, %s",
 
535
               ctx->error_depth, subject);
 
536
          goto err;             /* Reject connection */
 
537
        }
 
538
    }
 
539
 
 
540
  /* run --tls-verify script */
 
541
  if (opt->verify_command)
 
542
    {
 
543
      char command[256];
 
544
      struct buffer out;
 
545
      int ret;
 
546
 
 
547
      setenv_str (opt->es, "script_type", "tls-verify");
354
548
 
355
549
      buf_set_write (&out, (uint8_t*)command, sizeof (command));
356
550
      buf_printf (&out, "%s %d %s",
357
 
                  verify_command,
 
551
                  opt->verify_command,
358
552
                  ctx->error_depth,
359
 
                  txt);
360
 
      msg (D_TLS_DEBUG, "executing verify command: %s", command);
361
 
      ret = openvpn_system (command);
 
553
                  subject);
 
554
      dmsg (D_TLS_DEBUG, "TLS: executing verify command: %s", command);
 
555
      ret = openvpn_system (command, opt->es, S_SCRIPT);
 
556
 
362
557
      if (system_ok (ret))
363
558
        {
364
559
          msg (D_HANDSHAKE, "VERIFY SCRIPT OK: depth=%d, %s",
365
 
               ctx->error_depth, txt);
 
560
               ctx->error_depth, subject);
366
561
        }
367
562
      else
368
563
        {
369
564
          if (!system_executed (ret))
370
565
            msg (M_ERR, "Verify command failed to execute: %s", command);
371
566
          msg (D_HANDSHAKE, "VERIFY SCRIPT ERROR: depth=%d, %s",
372
 
               ctx->error_depth, txt);
373
 
          return 0;             /* Reject connection */
 
567
               ctx->error_depth, subject);
 
568
          goto err;             /* Reject connection */
374
569
        }
375
570
    }
376
571
  
377
 
  if (crl_file)
 
572
  /* check peer cert against CRL */
 
573
  if (opt->crl_file)
378
574
    {
379
575
      X509_CRL *crl=NULL;
380
576
      X509_REVOKED *revoked;
387
583
        msg (M_ERR, "CRL: BIO err");
388
584
        goto end;
389
585
      }
390
 
      if (BIO_read_filename(in,crl_file) <= 0) {
391
 
        msg (M_ERR, "CRL: cannot read: %s",crl_file);
 
586
      if (BIO_read_filename(in, opt->crl_file) <= 0) {
 
587
        msg (M_ERR, "CRL: cannot read: %s", opt->crl_file);
392
588
        goto end;
393
589
      }
394
590
      crl=PEM_read_bio_X509_CRL(in,NULL,NULL,NULL);
395
591
      if (crl == NULL) {
396
 
        msg (M_ERR, "CRL: cannot read CRL from file %s",crl_file);
 
592
        msg (M_ERR, "CRL: cannot read CRL from file %s", opt->crl_file);
 
593
        goto end;
 
594
      }
 
595
 
 
596
      if (X509_NAME_cmp(X509_CRL_get_issuer(crl), X509_get_issuer_name(ctx->current_cert)) != 0) {
 
597
        msg (M_WARN, "CRL: CRL %s is from a different issuer than the issuer of certificate %s", opt->crl_file, subject);
 
598
        retval = 1;
397
599
        goto end;
398
600
      }
399
601
 
402
604
      for (i = 0; i < n; i++) {
403
605
        revoked = (X509_REVOKED *)sk_value(X509_CRL_get_REVOKED(crl), i);
404
606
        if (ASN1_INTEGER_cmp(revoked->serialNumber, X509_get_serialNumber(ctx->current_cert)) == 0) {
405
 
          msg (D_HANDSHAKE, "CRL CHECK FAILED: %s is REVOKED",txt);
 
607
          msg (D_HANDSHAKE, "CRL CHECK FAILED: %s is REVOKED",subject);
406
608
          goto end;
407
609
        }
408
610
      }
409
611
 
410
612
      retval = 1;
411
 
      msg (D_HANDSHAKE, "CRL CHECK OK: %s",txt);
 
613
      msg (D_HANDSHAKE, "CRL CHECK OK: %s",subject);
412
614
 
413
615
    end:
414
616
 
415
617
      BIO_free(in);
416
618
      if (!retval)
417
 
        return retval;
 
619
        goto err;
418
620
    }
419
621
 
420
 
  msg (D_HANDSHAKE, "VERIFY OK: depth=%d, %s", ctx->error_depth, txt);
 
622
  msg (D_HANDSHAKE, "VERIFY OK: depth=%d, %s", ctx->error_depth, subject);
421
623
 
 
624
  session->verified = true;
422
625
  return 1;                     /* Accept connection */
 
626
 
 
627
 err:
 
628
  return 0;                     /* Reject connection */
 
629
}
 
630
 
 
631
void
 
632
tls_set_common_name (struct tls_multi *multi, const char *common_name)
 
633
{
 
634
  if (multi)
 
635
    set_common_name (&multi->session[TM_ACTIVE], common_name);
 
636
}
 
637
 
 
638
const char *
 
639
tls_common_name (struct tls_multi *multi, bool null)
 
640
{
 
641
  const char *ret = NULL;
 
642
  if (multi)
 
643
    ret = multi->session[TM_ACTIVE].common_name;
 
644
  if (ret && strlen (ret))
 
645
    return ret;
 
646
  else if (null)
 
647
    return NULL;
 
648
  else
 
649
    return "UNDEF";
 
650
}
 
651
 
 
652
void
 
653
tls_lock_common_name (struct tls_multi *multi)
 
654
{
 
655
  const char *cn = multi->session[TM_ACTIVE].common_name;
 
656
  if (cn && !multi->locked_cn)
 
657
    multi->locked_cn = string_alloc (cn, NULL);
 
658
}
 
659
 
 
660
/*
 
661
 * Return true if at least one valid key state exists
 
662
 * which has passed authentication.  If we are using
 
663
 * username/password authentication, and the authentication
 
664
 * failed, we may have a live S_ACTIVE/S_NORMAL key state
 
665
 * even though the 'authenticated' var might be false.
 
666
 *
 
667
 * This is so that we can return an AUTH_FAILED error
 
668
 * message to the client over the TLS channel.
 
669
 *
 
670
 * If 'authenticated' is false, tunnel traffic forwarding
 
671
 * is disabled but TLS channel data can still be sent
 
672
 * or received.
 
673
 */
 
674
bool
 
675
tls_authenticated (struct tls_multi *multi)
 
676
{
 
677
  if (multi)
 
678
    {
 
679
      int i;
 
680
      for (i = 0; i < KEY_SCAN_SIZE; ++i)
 
681
        {
 
682
          const struct key_state *ks = multi->key_scan[i];
 
683
          if (DECRYPT_KEY_ENABLED (multi, ks) && ks->authenticated)
 
684
            return true;
 
685
        }
 
686
    }
 
687
  return false;
 
688
}
 
689
 
 
690
void
 
691
tls_deauthenticate (struct tls_multi *multi)
 
692
{
 
693
  if (multi)
 
694
    {
 
695
      int i, j;
 
696
      for (i = 0; i < TM_SIZE; ++i)
 
697
        for (j = 0; j < KS_SIZE; ++j)
 
698
          multi->session[i].key[j].authenticated = false;
 
699
    }
423
700
}
424
701
 
425
702
/*
430
707
{
431
708
  if (where & SSL_CB_LOOP)
432
709
    {
433
 
      msg (D_HANDSHAKE_VERBOSE, "SSL state (%s): %s",
 
710
      dmsg (D_HANDSHAKE_VERBOSE, "SSL state (%s): %s",
434
711
           where & SSL_ST_CONNECT ? "connect" :
435
712
           where & SSL_ST_ACCEPT ? "accept" :
436
713
           "undefined", SSL_state_string_long (s));
437
714
    }
438
715
  else if (where & SSL_CB_ALERT)
439
716
    {
440
 
      msg (D_HANDSHAKE_VERBOSE, "SSL alert (%s): %s: %s",
 
717
      dmsg (D_HANDSHAKE_VERBOSE, "SSL alert (%s): %s: %s",
441
718
           where & SSL_CB_READ ? "read" : "write",
442
719
           SSL_alert_type_string_long (ret),
443
720
           SSL_alert_desc_string_long (ret));
449
726
 * All files are in PEM format.
450
727
 */
451
728
SSL_CTX *
452
 
init_ssl (bool server,
453
 
          const char *ca_file,
454
 
          const char *dh_file,
455
 
          const char *cert_file,
456
 
          const char *priv_key_file,
457
 
          const char *cipher_list)
 
729
init_ssl (const struct options *options)
458
730
{
459
731
  SSL_CTX *ctx;
460
732
  DH *dh;
461
733
  BIO *bio;
 
734
  bool using_cert_file = false;
462
735
 
463
 
  if (server)
 
736
  if (options->tls_server)
464
737
    {
465
738
      ctx = SSL_CTX_new (TLSv1_server_method ());
466
739
      if (ctx == NULL)
469
742
      SSL_CTX_set_tmp_rsa_callback (ctx, tmp_rsa_cb);
470
743
 
471
744
      /* Get Diffie Hellman Parameters */
472
 
      if (!(bio = BIO_new_file (dh_file, "r")))
473
 
        msg (M_SSLERR, "Cannot open %s for DH parameters", dh_file);
 
745
      if (!(bio = BIO_new_file (options->dh_file, "r")))
 
746
        msg (M_SSLERR, "Cannot open %s for DH parameters", options->dh_file);
474
747
      dh = PEM_read_bio_DHparams (bio, NULL, NULL, NULL);
475
748
      BIO_free (bio);
476
749
      if (!dh)
477
 
        msg (M_SSLERR, "Cannot load DH parameters from %s", dh_file);
 
750
        msg (M_SSLERR, "Cannot load DH parameters from %s", options->dh_file);
478
751
      if (!SSL_CTX_set_tmp_dh (ctx, dh))
479
752
        msg (M_SSLERR, "SSL_CTX_set_tmp_dh");
480
753
      msg (D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key",
495
768
  /* Set callback for getting password from user to decrypt private key */
496
769
  SSL_CTX_set_default_passwd_cb (ctx, pem_password_callback);
497
770
 
498
 
  /* Load Certificate */
499
 
  if (!SSL_CTX_use_certificate_file (ctx, cert_file, SSL_FILETYPE_PEM))
500
 
    msg (M_SSLERR, "Cannot load certificate file %s", cert_file);
501
 
 
502
 
  /* Load Private Key */
503
 
  if (!SSL_CTX_use_PrivateKey_file (ctx, priv_key_file, SSL_FILETYPE_PEM))
504
 
    msg (M_SSLERR, "Cannot load private key file %s", priv_key_file);
505
 
  warn_if_group_others_accessible (priv_key_file);
506
 
 
507
 
  /* Check Private Key */
508
 
  if (!SSL_CTX_check_private_key (ctx))
509
 
    msg (M_SSLERR, "Private key does not match the certificate");
510
 
 
511
 
  /* Load CA file for verifying peer supplied certificate */
512
 
  if (!SSL_CTX_load_verify_locations (ctx, ca_file, NULL))
513
 
    msg (M_SSLERR, "Cannot load CA certificate file %s (SSL_CTX_load_verify_locations)", ca_file);
514
 
 
515
 
  /* Load names of CAs from file and use it as a client CA list */
516
 
  {
517
 
    STACK_OF(X509_NAME) *cert_names;
518
 
    cert_names = SSL_load_client_CA_file (ca_file);
519
 
    if (!cert_names)
520
 
      msg (M_SSLERR, "Cannot load CA certificate file %s (SSL_load_client_CA_file)", ca_file);
521
 
    SSL_CTX_set_client_CA_list (ctx, cert_names);
522
 
  }
523
 
 
 
771
  if (options->pkcs12_file)
 
772
    {
 
773
    /* Use PKCS #12 file for key, cert and CA certs */
 
774
 
 
775
      FILE *fp;
 
776
      EVP_PKEY *pkey;
 
777
      X509 *cert;
 
778
      STACK_OF(X509) *ca = NULL;
 
779
      PKCS12 *p12;
 
780
      int i;
 
781
      char password[256];
 
782
 
 
783
      /* Load the PKCS #12 file */
 
784
      if (!(fp = fopen(options->pkcs12_file, "rb")))
 
785
        msg (M_SSLERR, "Error opening file %s", options->pkcs12_file);
 
786
      p12 = d2i_PKCS12_fp(fp, NULL);
 
787
      fclose (fp);
 
788
      if (!p12) msg (M_SSLERR, "Error reading PKCS#12 file %s", options->pkcs12_file);
 
789
      
 
790
      /* Parse the PKCS #12 file */
 
791
      if (!PKCS12_parse(p12, "", &pkey, &cert, &ca))
 
792
        {
 
793
          pem_password_callback (password, sizeof(password) - 1, 0, NULL);
 
794
          /* Reparse the PKCS #12 file with password */
 
795
          ca = NULL;
 
796
          if (!PKCS12_parse(p12, password, &pkey, &cert, &ca))
 
797
             msg (M_SSLERR, "Error parsing PKCS#12 file %s", options->pkcs12_file);
 
798
        }
 
799
      PKCS12_free(p12);
 
800
 
 
801
      /* Load Certificate */
 
802
      if (!SSL_CTX_use_certificate (ctx, cert))
 
803
        msg (M_SSLERR, "Cannot use certificate");
 
804
 
 
805
      /* Load Private Key */
 
806
      if (!SSL_CTX_use_PrivateKey (ctx, pkey))
 
807
        msg (M_SSLERR, "Cannot use private key");
 
808
      warn_if_group_others_accessible (options->pkcs12_file);
 
809
 
 
810
      /* Check Private Key */
 
811
      if (!SSL_CTX_check_private_key (ctx))
 
812
        msg (M_SSLERR, "Private key does not match the certificate");
 
813
 
 
814
      /* Set Certificate Verification chain */
 
815
      if (ca && sk_num(ca))
 
816
        {
 
817
          for (i = 0; i < sk_X509_num(ca); i++)
 
818
            {
 
819
              if (!X509_STORE_add_cert(ctx->cert_store,sk_X509_value(ca, i)))
 
820
                 msg (M_SSLERR, "Cannot add certificate to certificate chain (X509_STORE_add_cert)");
 
821
              if (!SSL_CTX_add_client_CA(ctx, sk_X509_value(ca, i)))
 
822
                msg (M_SSLERR, "Cannot add certificate to client CA list (SSL_CTX_add_client_CA)");
 
823
            }
 
824
        }
 
825
    }
 
826
  else
 
827
    {
 
828
      /* Use seperate PEM files for key, cert and CA certs */
 
829
 
 
830
#ifdef WIN32
 
831
      if (options->cryptoapi_cert)
 
832
        {
 
833
          /* Load Certificate and Private Key */
 
834
          if (!SSL_CTX_use_CryptoAPI_certificate (ctx, options->cryptoapi_cert))
 
835
            msg (M_SSLERR, "Cannot load certificate \"%s\" from Microsoft Certificate Store",
 
836
                 options->cryptoapi_cert);
 
837
        }
 
838
      else
 
839
#endif
 
840
        {
 
841
          /* Load Certificate */
 
842
          if (options->cert_file)
 
843
            {
 
844
              using_cert_file = true;
 
845
              if (!SSL_CTX_use_certificate_file (ctx, options->cert_file, SSL_FILETYPE_PEM))
 
846
                msg (M_SSLERR, "Cannot load certificate file %s", options->cert_file);
 
847
            }
 
848
 
 
849
          /* Load Private Key */
 
850
          if (options->priv_key_file)
 
851
            {
 
852
              if (!SSL_CTX_use_PrivateKey_file (ctx, options->priv_key_file, SSL_FILETYPE_PEM))
 
853
                {
 
854
#ifdef ENABLE_MANAGEMENT
 
855
                  if (management && (ERR_GET_REASON (ERR_peek_error()) == EVP_R_BAD_DECRYPT))
 
856
                    management_auth_failure (management, UP_TYPE_PRIVATE_KEY);
 
857
#endif
 
858
                  msg (M_SSLERR, "Cannot load private key file %s", options->priv_key_file);
 
859
                }
 
860
              warn_if_group_others_accessible (options->priv_key_file);
 
861
 
 
862
              /* Check Private Key */
 
863
              if (!SSL_CTX_check_private_key (ctx))
 
864
                msg (M_SSLERR, "Private key does not match the certificate");
 
865
            }
 
866
        }
 
867
 
 
868
      /* Load CA file for verifying peer supplied certificate */
 
869
      ASSERT (options->ca_file);
 
870
      if (!SSL_CTX_load_verify_locations (ctx, options->ca_file, NULL))
 
871
        msg (M_SSLERR, "Cannot load CA certificate file %s (SSL_CTX_load_verify_locations)", options->ca_file);
 
872
 
 
873
      /* Load names of CAs from file and use it as a client CA list */
 
874
      {
 
875
        STACK_OF(X509_NAME) *cert_names;
 
876
        cert_names = SSL_load_client_CA_file (options->ca_file);
 
877
        if (!cert_names)
 
878
          msg (M_SSLERR, "Cannot load CA certificate file %s (SSL_load_client_CA_file)", options->ca_file);
 
879
        SSL_CTX_set_client_CA_list (ctx, cert_names);
 
880
      }
 
881
 
 
882
    }
 
883
  
524
884
  /* Enable the use of certificate chains */
525
 
  if (!SSL_CTX_use_certificate_chain_file (ctx, cert_file))
526
 
    msg (M_SSLERR, "Cannot load certificate chain file %s (SSL_use_certificate_chain_file)", cert_file);
 
885
  if (using_cert_file)
 
886
    {
 
887
      if (!SSL_CTX_use_certificate_chain_file (ctx, options->cert_file))
 
888
        msg (M_SSLERR, "Cannot load certificate chain file %s (SSL_use_certificate_chain_file)", options->cert_file);
 
889
    }
527
890
 
528
891
  /* Require peer certificate verification */
529
 
  SSL_CTX_set_verify (ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
530
 
                      verify_callback);
 
892
#if P2MP_SERVER
 
893
  if (options->client_cert_not_required)
 
894
    {
 
895
      msg (M_WARN, "WARNING: This configuration may accept clients which do not present a certificate");
 
896
    }
 
897
  else
 
898
#endif
 
899
    SSL_CTX_set_verify (ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
 
900
                        verify_callback);
531
901
 
532
902
  /* Connection information callback */
533
903
  SSL_CTX_set_info_callback (ctx, info_callback);
534
904
 
535
905
  /* Allowable ciphers */
536
 
  if (cipher_list)
 
906
  if (options->cipher_list)
537
907
    {
538
 
      if (!SSL_CTX_set_cipher_list (ctx, cipher_list))
539
 
        msg (M_SSLERR, "Problem with cipher list: %s", cipher_list);
 
908
      if (!SSL_CTX_set_cipher_list (ctx, options->cipher_list))
 
909
        msg (M_SSLERR, "Problem with cipher list: %s", options->cipher_list);
540
910
    }
541
911
 
542
912
  return ctx;
719
1089
 * For debugging.
720
1090
 */
721
1091
static const char *
722
 
print_key_id (struct tls_multi *multi)
 
1092
print_key_id (struct tls_multi *multi, struct gc_arena *gc)
723
1093
{
724
1094
  int i;
725
 
  struct buffer out = alloc_buf_gc (256);
 
1095
  struct buffer out = alloc_buf_gc (256, gc);
726
1096
 
727
1097
  for (i = 0; i < KEY_SCAN_SIZE; ++i)
728
1098
    {
729
1099
      struct key_state *ks = multi->key_scan[i];
730
1100
      buf_printf (&out, " [key#%d state=%s id=%d sid=%s]", i,
731
1101
                  state_name (ks->state), ks->key_id,
732
 
                  session_id_print (&ks->session_id_remote));
 
1102
                  session_id_print (&ks->session_id_remote, gc));
733
1103
    }
734
1104
 
735
1105
  return BSTR (&out);
775
1145
 * Write to an OpenSSL BIO in non-blocking mode.
776
1146
 */
777
1147
static int
778
 
bio_write (BIO * bio, struct buffer *buf, const char *desc)
 
1148
bio_write (struct tls_multi* multi, BIO *bio, const uint8_t *data, int size, const char *desc)
779
1149
{
780
1150
  int i;
781
1151
  int ret = 0;
782
 
  ASSERT (buf->len >= 0);
783
 
  if (buf->len)
 
1152
  ASSERT (size >= 0);
 
1153
  if (size)
784
1154
    {
785
1155
      /*
786
1156
       * Free the L_TLS lock prior to calling BIO routines
789
1159
       * allowing tunnel packet forwarding to continue.
790
1160
       */
791
1161
#ifdef BIO_DEBUG
792
 
      bio_debug_data ("write", bio, BPTR (buf), BLEN (buf), desc);
 
1162
      bio_debug_data ("write", bio, data, size, desc);
793
1163
#endif
794
 
      mutex_unlock (L_TLS);
795
 
      i = BIO_write (bio, BPTR (buf), BLEN (buf));
796
 
      mutex_lock (L_TLS);
 
1164
      i = BIO_write (bio, data, size);
 
1165
 
797
1166
      if (i < 0)
798
1167
        {
799
1168
          if (BIO_should_retry (bio))
807
1176
              ret = -1;
808
1177
            }
809
1178
        }
810
 
      else if (i != buf->len)
 
1179
      else if (i != size)
811
1180
        {
812
1181
          msg (D_TLS_ERRORS | M_SSL,
813
 
               "TLS ERROR: BIO write %s incomplete %d/%d", desc, i, buf->len);
 
1182
               "TLS ERROR: BIO write %s incomplete %d/%d", desc, i, size);
814
1183
          ret = -1;
815
1184
        }
816
1185
      else
817
1186
        {                       /* successful write */
818
 
          msg (D_HANDSHAKE_VERBOSE, "BIO write %s %d bytes", desc, i);
819
 
          memset (BPTR (buf), 0, BLEN (buf)); /* erase data just written */
820
 
          buf->len = 0;
 
1187
          dmsg (D_HANDSHAKE_VERBOSE, "BIO write %s %d bytes", desc, i);
821
1188
          ret = 1;
822
1189
        }
823
1190
    }
828
1195
 * Read from an OpenSSL BIO in non-blocking mode.
829
1196
 */
830
1197
static int
831
 
bio_read (BIO * bio, struct buffer *buf, int maxlen, const char *desc)
 
1198
bio_read (struct tls_multi* multi, BIO *bio, struct buffer *buf, int maxlen, const char *desc)
832
1199
{
833
1200
  int i;
834
1201
  int ret = 0;
842
1209
      int len = buf_forward_capacity (buf);
843
1210
      if (maxlen < len)
844
1211
        len = maxlen;
 
1212
 
845
1213
      /*
846
 
       * Free the L_TLS lock prior to calling BIO routines
847
 
       * so that foreground thread can still call
848
 
       * tls_pre_decrypt or tls_pre_encrypt,
849
 
       * allowing tunnel packet forwarding to continue.
850
 
       *
851
1214
       * BIO_read brackets most of the serious RSA
852
1215
       * key negotiation number crunching.
853
1216
       */
854
 
      mutex_unlock (L_TLS);
855
1217
      i = BIO_read (bio, BPTR (buf), len);
856
 
      mutex_lock (L_TLS);
 
1218
 
 
1219
      VALGRIND_MAKE_READABLE ((void *) &i, sizeof (i));
 
1220
 
857
1221
#ifdef BIO_DEBUG
858
1222
      bio_debug_data ("read", bio, BPTR (buf), i, desc);
859
1223
#endif
877
1241
        }
878
1242
      else
879
1243
        {                       /* successful read */
880
 
          msg (D_HANDSHAKE_VERBOSE, "BIO read %s %d bytes", desc, i);
 
1244
          dmsg (D_HANDSHAKE_VERBOSE, "BIO read %s %d bytes", desc, i);
881
1245
          buf->len = i;
882
1246
          ret = 1;
 
1247
          VALGRIND_MAKE_READABLE ((void *) BPTR (buf), BLEN (buf));
883
1248
        }
884
1249
    }
885
1250
  return ret;
890
1255
 * to BIOs.
891
1256
 */
892
1257
 
893
 
static inline int
894
 
key_state_write_plaintext (struct key_state *ks, struct buffer *buf)
895
 
{
896
 
  return bio_write (ks->ssl_bio, buf, "tls_write_plaintext");
897
 
}
898
 
 
899
 
static inline int
900
 
key_state_write_ciphertext (struct key_state *ks, struct buffer *buf)
901
 
{
902
 
  return bio_write (ks->ct_in, buf, "tls_write_ciphertext");
903
 
}
904
 
 
905
 
static inline int
906
 
key_state_read_plaintext (struct key_state *ks, struct buffer *buf,
 
1258
static void
 
1259
bio_write_post (const int status, struct buffer *buf)
 
1260
{
 
1261
  if (status == 1) /* success status return from bio_write? */
 
1262
    {
 
1263
      memset (BPTR (buf), 0, BLEN (buf)); /* erase data just written */
 
1264
      buf->len = 0;
 
1265
    }
 
1266
}
 
1267
 
 
1268
static int
 
1269
key_state_write_plaintext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf)
 
1270
{
 
1271
  int ret;
 
1272
  perf_push (PERF_BIO_WRITE_PLAINTEXT);
 
1273
  ret = bio_write (multi, ks->ssl_bio, BPTR(buf), BLEN(buf), "tls_write_plaintext");
 
1274
  bio_write_post (ret, buf);
 
1275
  perf_pop ();
 
1276
  return ret;
 
1277
}
 
1278
 
 
1279
static int
 
1280
key_state_write_plaintext_const (struct tls_multi *multi, struct key_state *ks, const uint8_t *data, int len)
 
1281
{
 
1282
  int ret;
 
1283
  perf_push (PERF_BIO_WRITE_PLAINTEXT);
 
1284
  ret = bio_write (multi, ks->ssl_bio, data, len, "tls_write_plaintext_const");
 
1285
  perf_pop ();
 
1286
  return ret;
 
1287
}
 
1288
 
 
1289
static int
 
1290
key_state_write_ciphertext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf)
 
1291
{
 
1292
  int ret;
 
1293
  perf_push (PERF_BIO_WRITE_CIPHERTEXT);
 
1294
  ret = bio_write (multi, ks->ct_in, BPTR(buf), BLEN(buf), "tls_write_ciphertext");
 
1295
  bio_write_post (ret, buf);
 
1296
  perf_pop ();
 
1297
  return ret;
 
1298
}
 
1299
 
 
1300
static int
 
1301
key_state_read_plaintext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf,
907
1302
                          int maxlen)
908
1303
{
909
 
  return bio_read (ks->ssl_bio, buf, maxlen, "tls_read_plaintext");
 
1304
  int ret;
 
1305
  perf_push (PERF_BIO_READ_PLAINTEXT);
 
1306
  ret = bio_read (multi, ks->ssl_bio, buf, maxlen, "tls_read_plaintext");
 
1307
  perf_pop ();
 
1308
  return ret;
910
1309
}
911
1310
 
912
 
static inline int
913
 
key_state_read_ciphertext (struct key_state *ks, struct buffer *buf,
 
1311
static int
 
1312
key_state_read_ciphertext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf,
914
1313
                           int maxlen)
915
1314
{
916
 
  return bio_read (ks->ct_out, buf, maxlen, "tls_read_ciphertext");
 
1315
  int ret;
 
1316
  perf_push (PERF_BIO_READ_CIPHERTEXT);
 
1317
  ret = bio_read (multi, ks->ct_out, buf, maxlen, "tls_read_ciphertext");
 
1318
  perf_pop ();
 
1319
  return ret;
917
1320
}
918
1321
 
919
1322
/*
921
1324
 * a specific SSL/TLS session.
922
1325
 */
923
1326
static void
924
 
key_state_init (struct tls_session *session, struct key_state *ks,
925
 
                time_t current)
 
1327
key_state_init (struct tls_session *session, struct key_state *ks)
926
1328
{
 
1329
  update_time ();
 
1330
 
927
1331
  /*
928
1332
   * Build TLS object that reads/writes ciphertext
929
1333
   * to/from memory BIOs.
934
1338
  if (!ks->ssl)
935
1339
    msg (M_SSLERR, "SSL_new failed");
936
1340
 
 
1341
  /* put session * in ssl object so we can access it
 
1342
     from verify callback*/
 
1343
  SSL_set_ex_data (ks->ssl, mydata_index, session);
 
1344
 
937
1345
  ks->ssl_bio = getbio (BIO_f_ssl (), "ssl_bio");
938
1346
  ks->ct_in = getbio (BIO_s_mem (), "ct_in");
939
1347
  ks->ct_out = getbio (BIO_s_mem (), "ct_out");
967
1375
  if (!session->key_id)
968
1376
    session->key_id = 1;
969
1377
 
 
1378
  /* allocate key source material object */
 
1379
  ALLOC_OBJ_CLEAR (ks->key_src, struct key_source2);
 
1380
 
 
1381
  /* allocate reliability objects */
 
1382
  ALLOC_OBJ_CLEAR (ks->send_reliable, struct reliable);
 
1383
  ALLOC_OBJ_CLEAR (ks->rec_reliable, struct reliable);
 
1384
  ALLOC_OBJ_CLEAR (ks->rec_ack, struct reliable_ack);
 
1385
 
970
1386
  /* allocate buffers */
971
1387
  ks->plaintext_read_buf = alloc_buf (PLAINTEXT_BUFFER_SIZE);
972
1388
  ks->plaintext_write_buf = alloc_buf (PLAINTEXT_BUFFER_SIZE);
973
1389
  ks->ack_write_buf = alloc_buf (BUF_SIZE (&session->opt->frame));
974
 
  reliable_init (&ks->send_reliable, BUF_SIZE (&session->opt->frame),
 
1390
  reliable_init (ks->send_reliable, BUF_SIZE (&session->opt->frame),
975
1391
                 FRAME_HEADROOM (&session->opt->frame), TLS_RELIABLE_N_SEND_BUFFERS);
976
 
  reliable_init (&ks->rec_reliable, BUF_SIZE (&session->opt->frame),
 
1392
  reliable_init (ks->rec_reliable, BUF_SIZE (&session->opt->frame),
977
1393
                 FRAME_HEADROOM (&session->opt->frame), TLS_RELIABLE_N_REC_BUFFERS);
978
 
  reliable_set_timeout (&ks->send_reliable, session->opt->packet_timeout);
 
1394
  reliable_set_timeout (ks->send_reliable, session->opt->packet_timeout);
979
1395
 
980
1396
  /* init packet ID tracker */
981
1397
  packet_id_init (&ks->packet_id,
1002
1418
  free_buf (&ks->plaintext_read_buf);
1003
1419
  free_buf (&ks->plaintext_write_buf);
1004
1420
  free_buf (&ks->ack_write_buf);
1005
 
  reliable_free (&ks->send_reliable);
1006
 
  reliable_free (&ks->rec_reliable);
 
1421
 
 
1422
  if (ks->send_reliable)
 
1423
    {
 
1424
      reliable_free (ks->send_reliable);
 
1425
      free (ks->send_reliable);
 
1426
    }
 
1427
 
 
1428
  if (ks->rec_reliable)
 
1429
    {
 
1430
      reliable_free (ks->rec_reliable);
 
1431
      free (ks->rec_reliable);
 
1432
    }
 
1433
 
 
1434
  if (ks->rec_ack)
 
1435
    free (ks->rec_ack);
 
1436
 
 
1437
  if (ks->key_src)
 
1438
    free (ks->key_src);
1007
1439
 
1008
1440
  packet_id_free (&ks->packet_id);
1009
1441
 
1025
1457
static void
1026
1458
tls_session_init (struct tls_multi *multi, struct tls_session *session)
1027
1459
{
1028
 
  msg (D_TLS_DEBUG, "tls_session_init: entry");
 
1460
  struct gc_arena gc = gc_new ();
 
1461
 
 
1462
  dmsg (D_TLS_DEBUG, "TLS: tls_session_init: entry");
1029
1463
 
1030
1464
  CLEAR (*session);
1031
1465
 
1063
1497
  /* load most recent packet-id to replay protect on --tls-auth */
1064
1498
  packet_id_persist_load_obj (session->tls_auth.pid_persist, session->tls_auth.packet_id);
1065
1499
 
1066
 
  key_state_init (session, &session->key[KS_PRIMARY], time (NULL));
1067
 
 
1068
 
  msg (D_TLS_DEBUG, "tls_session_init: new session object, sid=%s",
1069
 
       session_id_print (&session->session_id));
 
1500
  key_state_init (session, &session->key[KS_PRIMARY]);
 
1501
 
 
1502
  dmsg (D_TLS_DEBUG, "TLS: tls_session_init: new session object, sid=%s",
 
1503
       session_id_print (&session->session_id, &gc));
 
1504
 
 
1505
  gc_free (&gc);
1070
1506
}
1071
1507
 
1072
1508
static void
1080
1516
  for (i = 0; i < KS_SIZE; ++i)
1081
1517
    key_state_free (&session->key[i], false);
1082
1518
 
 
1519
  if (session->common_name)
 
1520
    free (session->common_name);
 
1521
 
1083
1522
  if (clear)
1084
1523
    CLEAR (*session);
1085
1524
}
1086
1525
 
1087
1526
static void
1088
 
move_session(struct tls_multi* multi, int dest, int src, bool reinit_src)
 
1527
move_session (struct tls_multi* multi, int dest, int src, bool reinit_src)
1089
1528
{
1090
1529
  msg (D_TLS_DEBUG_LOW, "TLS: move_session: dest=%s src=%s reinit_src=%d",
1091
1530
       session_index_name(dest),
1103
1542
  else
1104
1543
    CLEAR (multi->session[src]);
1105
1544
 
1106
 
  msg (D_TLS_DEBUG, "move_session: exit");
 
1545
  dmsg (D_TLS_DEBUG, "TLS: move_session: exit");
1107
1546
}
1108
1547
 
1109
1548
static void
1146
1585
 * no longer be used.
1147
1586
 */
1148
1587
static inline bool
1149
 
lame_duck_must_die (const struct tls_session* session, interval_t *wakeup, time_t current)
 
1588
lame_duck_must_die (const struct tls_session* session, interval_t *wakeup)
1150
1589
{
1151
1590
  const struct key_state* lame = &session->key[KS_LAME_DUCK];
1152
1591
  if (lame->state >= S_INITIAL)
1153
1592
    {
 
1593
      const time_t local_now = now;
1154
1594
      ASSERT (lame->must_die); /* a lame duck key must always have an expiration */
1155
 
      if (current < lame->must_die)
 
1595
      if (local_now < lame->must_die)
1156
1596
        {
1157
 
          compute_earliest_wakeup (wakeup, lame->must_die - current);
 
1597
          compute_earliest_wakeup (wakeup, lame->must_die - local_now);
1158
1598
          return false;
1159
1599
        }
1160
1600
      else
1175
1615
{
1176
1616
  struct tls_multi *ret;
1177
1617
 
1178
 
  ret = (struct tls_multi *) malloc (sizeof (struct tls_multi));
1179
 
  ASSERT (ret);
1180
 
  CLEAR (*ret);
 
1618
  ALLOC_OBJ_CLEAR (ret, struct tls_multi);
1181
1619
 
1182
1620
  /* get command line derived options */
1183
1621
  ret->opt = *tls_options;
1198
1636
 * Finalize our computation of frame sizes.
1199
1637
 */
1200
1638
void
1201
 
tls_multi_init_finalize(struct tls_multi* multi, const struct frame* frame)
 
1639
tls_multi_init_finalize (struct tls_multi* multi, const struct frame* frame)
1202
1640
{
1203
 
  tls_init_control_channel_frame_parameters(frame, &multi->opt.frame);
 
1641
  tls_init_control_channel_frame_parameters (frame, &multi->opt.frame);
1204
1642
  
1205
1643
  /* initialize the active and untrusted sessions */
 
1644
 
1206
1645
  tls_session_init (multi, &multi->session[TM_ACTIVE]);
1207
 
  tls_session_init (multi, &multi->session[TM_UNTRUSTED]);
 
1646
 
 
1647
  if (!multi->opt.single_session)
 
1648
    tls_session_init (multi, &multi->session[TM_UNTRUSTED]);
 
1649
}
 
1650
 
 
1651
/*
 
1652
 * Initialize and finalize a standalone tls-auth verification object.
 
1653
 */
 
1654
 
 
1655
struct tls_auth_standalone *
 
1656
tls_auth_standalone_init (struct tls_options *tls_options,
 
1657
                          struct gc_arena *gc)
 
1658
{
 
1659
  struct tls_auth_standalone *tas;
 
1660
 
 
1661
  ALLOC_OBJ_CLEAR_GC (tas, struct tls_auth_standalone, gc);
 
1662
 
 
1663
  /* set up pointer to HMAC object for TLS packet authentication */
 
1664
  tas->tls_auth_key = tls_options->tls_auth_key;
 
1665
  tas->tls_auth_options.key_ctx_bi = &tas->tls_auth_key;
 
1666
  tas->tls_auth_options.flags |= CO_PACKET_ID_LONG_FORM;
 
1667
 
 
1668
  /* get initial frame parms, still need to finalize */
 
1669
  tas->frame = tls_options->frame;
 
1670
 
 
1671
  return tas;
 
1672
}
 
1673
 
 
1674
void
 
1675
tls_auth_standalone_finalize (struct tls_auth_standalone *tas,
 
1676
                              const struct frame *frame)
 
1677
{
 
1678
  tls_init_control_channel_frame_parameters (frame, &tas->frame);
1208
1679
}
1209
1680
 
1210
1681
/*
1213
1684
 * sets.
1214
1685
 */
1215
1686
void
1216
 
tls_multi_init_set_options(struct tls_multi* multi,
 
1687
tls_multi_init_set_options (struct tls_multi* multi,
1217
1688
                           const char *local,
1218
1689
                           const char *remote)
1219
1690
{
 
1691
#ifdef ENABLE_OCC
1220
1692
  /* initialize options string */
1221
1693
  multi->opt.local_options = local;
1222
1694
  multi->opt.remote_options = remote;
 
1695
#endif
1223
1696
}
1224
1697
 
1225
1698
void
1229
1702
 
1230
1703
  ASSERT (multi);
1231
1704
 
 
1705
  if (multi->locked_cn)
 
1706
    free (multi->locked_cn);
 
1707
 
1232
1708
  for (i = 0; i < TM_SIZE; ++i)
1233
1709
    tls_session_free (&multi->session[i], false);
1234
1710
 
1309
1785
                    struct sockaddr_in *to_link_addr,
1310
1786
                    int opcode,
1311
1787
                    int max_ack,
1312
 
                    bool prepend_ack,
1313
 
                    time_t current)
 
1788
                    bool prepend_ack)
1314
1789
{
1315
1790
  uint8_t *header;
1316
1791
  struct buffer null = clear_buf ();
1317
1792
 
1318
1793
  ASSERT (addr_defined (&ks->remote_addr));
1319
1794
  ASSERT (reliable_ack_write
1320
 
          (&ks->rec_ack, buf, &ks->session_id_remote, max_ack, prepend_ack));
 
1795
          (ks->rec_ack, buf, &ks->session_id_remote, max_ack, prepend_ack));
1321
1796
  ASSERT (session_id_write_prepend (&session->session_id, buf));
1322
1797
  ASSERT (header = buf_prepend (buf, 1));
1323
1798
  *header = ks->key_id | (opcode << P_OPCODE_SHIFT);
1324
1799
  if (session->tls_auth.key_ctx_bi->encrypt.hmac)
1325
1800
    {
1326
1801
      /* no encryption, only write hmac */
1327
 
      openvpn_encrypt (buf, null, &session->tls_auth, NULL, current);
 
1802
      openvpn_encrypt (buf, null, &session->tls_auth, NULL);
1328
1803
      ASSERT (swap_hmac (buf, &session->tls_auth, false));
1329
1804
    }
1330
1805
  *to_link_addr = ks->remote_addr;
1335
1810
 */
1336
1811
static bool
1337
1812
read_control_auth (struct buffer *buf,
1338
 
                   struct crypto_options *co,
1339
 
                   struct sockaddr_in *from,
1340
 
                   time_t current)
 
1813
                   const struct crypto_options *co,
 
1814
                   const struct sockaddr_in *from)
1341
1815
{
 
1816
  struct gc_arena gc = gc_new ();
 
1817
 
1342
1818
  if (co->key_ctx_bi->decrypt.hmac)
1343
1819
    {
1344
1820
      struct buffer null = clear_buf ();
1348
1824
        {
1349
1825
          msg (D_TLS_ERRORS,
1350
1826
               "TLS Error: cannot locate HMAC in incoming packet from %s",
1351
 
               print_sockaddr (from));
 
1827
               print_sockaddr (from, &gc));
 
1828
          gc_free (&gc);
1352
1829
          return false;
1353
1830
        }
1354
1831
 
1355
1832
      /* authenticate only (no decrypt) and remove the hmac record
1356
1833
         from the head of the buffer */
1357
 
      openvpn_decrypt (buf, null, co, NULL, current);
 
1834
      openvpn_decrypt (buf, null, co, NULL);
1358
1835
      if (!buf->len)
1359
1836
        {
1360
1837
          msg (D_TLS_ERRORS,
1361
1838
               "TLS Error: incoming packet authentication failed from %s",
1362
 
               print_sockaddr (from));
 
1839
               print_sockaddr (from, &gc));
 
1840
          gc_free (&gc);
1363
1841
          return false;
1364
1842
        }
1365
1843
 
1369
1847
     already read it */
1370
1848
  buf_advance (buf, SID_SIZE + 1);
1371
1849
 
 
1850
  gc_free (&gc);
1372
1851
  return true;
1373
1852
}
1374
1853
 
1380
1859
key_source_print (const struct key_source *k,
1381
1860
                  const char *prefix)
1382
1861
{
1383
 
  msg (D_SHOW_KEY_SOURCE,
 
1862
  struct gc_arena gc = gc_new ();
 
1863
 
 
1864
  VALGRIND_MAKE_READABLE ((void *)k->pre_master, sizeof (k->pre_master));
 
1865
  VALGRIND_MAKE_READABLE ((void *)k->random1, sizeof (k->random1));
 
1866
  VALGRIND_MAKE_READABLE ((void *)k->random2, sizeof (k->random2));
 
1867
 
 
1868
  dmsg (D_SHOW_KEY_SOURCE,
1384
1869
       "%s pre_master: %s",
1385
1870
       prefix,
1386
 
       format_hex (k->pre_master, sizeof (k->pre_master), 0));
1387
 
  msg (D_SHOW_KEY_SOURCE,
 
1871
       format_hex (k->pre_master, sizeof (k->pre_master), 0, &gc));
 
1872
  dmsg (D_SHOW_KEY_SOURCE,
1388
1873
       "%s random1: %s",
1389
1874
       prefix,
1390
 
       format_hex (k->random1, sizeof (k->random1), 0));
1391
 
  msg (D_SHOW_KEY_SOURCE,
 
1875
       format_hex (k->random1, sizeof (k->random1), 0, &gc));
 
1876
  dmsg (D_SHOW_KEY_SOURCE,
1392
1877
       "%s random2: %s",
1393
1878
       prefix,
1394
 
       format_hex (k->random2, sizeof (k->random2), 0));
 
1879
       format_hex (k->random2, sizeof (k->random2), 0, &gc));
 
1880
 
 
1881
  gc_free (&gc);
1395
1882
}
1396
1883
 
1397
1884
static void
1430
1917
            uint8_t *out,
1431
1918
            int olen)
1432
1919
{
 
1920
  struct gc_arena gc = gc_new ();
1433
1921
  int chunk,n;
1434
1922
  unsigned int j;
1435
1923
  HMAC_CTX ctx;
1436
1924
  HMAC_CTX ctx_tmp;
1437
1925
  uint8_t A1[EVP_MAX_MD_SIZE];
1438
1926
  unsigned int A1_len;
 
1927
 
 
1928
#ifdef ENABLE_DEBUG
1439
1929
  const int olen_orig = olen;
1440
1930
  const uint8_t *out_orig = out;
 
1931
#endif
1441
1932
        
1442
 
  msg (D_SHOW_KEY_SOURCE, "tls1_P_hash sec: %s", format_hex (sec, sec_len, 0));
1443
 
  msg (D_SHOW_KEY_SOURCE, "tls1_P_hash seed: %s", format_hex (seed, seed_len, 0));
 
1933
  dmsg (D_SHOW_KEY_SOURCE, "tls1_P_hash sec: %s", format_hex (sec, sec_len, 0, &gc));
 
1934
  dmsg (D_SHOW_KEY_SOURCE, "tls1_P_hash seed: %s", format_hex (seed, seed_len, 0, &gc));
1444
1935
 
1445
1936
  chunk=EVP_MD_size(md);
1446
1937
 
1478
1969
  HMAC_CTX_cleanup(&ctx_tmp);
1479
1970
  CLEAR (A1);
1480
1971
 
1481
 
  msg (D_SHOW_KEY_SOURCE, "tls1_P_hash out: %s", format_hex (out_orig, olen_orig, 0));
 
1972
  dmsg (D_SHOW_KEY_SOURCE, "tls1_P_hash out: %s", format_hex (out_orig, olen_orig, 0, &gc));
 
1973
  gc_free (&gc);
1482
1974
}
1483
1975
 
1484
1976
static void
1489
1981
         uint8_t *out1,
1490
1982
         int olen)
1491
1983
{
 
1984
  struct gc_arena gc = gc_new ();
1492
1985
  const EVP_MD *md5 = EVP_md5();
1493
1986
  const EVP_MD *sha1 = EVP_sha1();
1494
1987
  int len,i;
1495
1988
  const uint8_t *S1,*S2;
1496
1989
  uint8_t *out2;
1497
1990
 
1498
 
  out2 = (uint8_t *) malloc (olen);
1499
 
  ASSERT (out2);
 
1991
  out2 = (uint8_t *) gc_malloc (olen, false, &gc);
1500
1992
 
1501
1993
  len=slen/2;
1502
1994
  S1=sec;
1511
2003
    out1[i]^=out2[i];
1512
2004
 
1513
2005
  memset (out2, 0, olen);
1514
 
  free (out2);
1515
 
 
1516
 
  msg (D_SHOW_KEY_SOURCE, "tls1_PRF out[%d]: %s", olen, format_hex (out1, olen, 0));
 
2006
 
 
2007
  dmsg (D_SHOW_KEY_SOURCE, "tls1_PRF out[%d]: %s", olen, format_hex (out1, olen, 0, &gc));
 
2008
 
 
2009
  gc_free (&gc);
1517
2010
}
1518
2011
 
1519
2012
static void
1550
2043
 
1551
2044
  buf_clear (&seed);
1552
2045
  free_buf (&seed);
 
2046
 
 
2047
  VALGRIND_MAKE_READABLE ((void *)output, output_len);
1553
2048
}
1554
2049
 
1555
2050
/* 
1578
2073
  /* compute master secret */
1579
2074
  openvpn_PRF (key_src->client.pre_master,
1580
2075
               sizeof(key_src->client.pre_master),
1581
 
               PACKAGE_NAME " master secret",
 
2076
               KEY_EXPANSION_ID " master secret",
1582
2077
               key_src->client.random1,
1583
2078
               sizeof(key_src->client.random1),
1584
2079
               key_src->server.random1,
1591
2086
  /* compute key expansion */
1592
2087
  openvpn_PRF (master,
1593
2088
               sizeof(master),
1594
 
               PACKAGE_NAME " key expansion",
 
2089
               KEY_EXPANSION_ID " key expansion",
1595
2090
               key_src->client.random2,
1596
2091
               sizeof(key_src->client.random2),
1597
2092
               key_src->server.random2,
1608
2103
  /* check for weak keys */
1609
2104
  for (i = 0; i < 2; ++i)
1610
2105
    {
 
2106
      fixup_key (&key2.keys[i], key_type);
1611
2107
      if (!check_key (&key2.keys[i], key_type))
1612
2108
        {
1613
2109
          msg (D_TLS_ERRORS, "TLS Error: Bad dynamic key generated");
1640
2136
  return ret;
1641
2137
}
1642
2138
 
1643
 
static void
 
2139
static bool
1644
2140
random_bytes_to_buf (struct buffer *buf,
1645
2141
                     uint8_t *out,
1646
2142
                     int outlen)
1647
2143
{
1648
 
  ASSERT (RAND_bytes (out, outlen));
1649
 
  ASSERT (buf_write (buf, out, outlen));
 
2144
  if (!RAND_bytes (out, outlen))
 
2145
    msg (M_FATAL, "ERROR: Random number generator cannot obtain entropy for key generation [SSL]");
 
2146
  if (!buf_write (buf, out, outlen))
 
2147
    return false;
 
2148
  return true;
1650
2149
}
1651
2150
 
1652
 
static void
 
2151
static bool
1653
2152
key_source2_randomize_write (struct key_source2 *k2,
1654
2153
                             struct buffer *buf,
1655
2154
                             bool server)
1661
2160
  CLEAR (*k);
1662
2161
 
1663
2162
  if (!server)
1664
 
    random_bytes_to_buf (buf, k->pre_master, sizeof (k->pre_master));
1665
 
 
1666
 
  random_bytes_to_buf (buf, k->random1, sizeof (k->random1));
1667
 
  random_bytes_to_buf (buf, k->random2, sizeof (k->random2));
 
2163
    {
 
2164
      if (!random_bytes_to_buf (buf, k->pre_master, sizeof (k->pre_master)))
 
2165
        return false;
 
2166
    }
 
2167
 
 
2168
  if (!random_bytes_to_buf (buf, k->random1, sizeof (k->random1)))
 
2169
    return false;
 
2170
  if (!random_bytes_to_buf (buf, k->random2, sizeof (k->random2)))
 
2171
    return false;
 
2172
 
 
2173
  return true;
1668
2174
}
1669
2175
 
1670
2176
static int
1701
2207
 
1702
2208
/* true if no in/out acknowledgements pending */
1703
2209
#define FULL_SYNC \
1704
 
  (reliable_empty(&ks->send_reliable) && reliable_ack_empty(&ks->rec_ack))
 
2210
  (reliable_empty(ks->send_reliable) && reliable_ack_empty (ks->rec_ack))
1705
2211
 
1706
2212
/*
1707
2213
 * Move the active key to the lame duck key and reinitialize the
1708
2214
 * active key.
1709
2215
 */
1710
2216
static void
1711
 
key_state_soft_reset (struct tls_session *session, time_t current)
 
2217
key_state_soft_reset (struct tls_session *session)
1712
2218
{
1713
 
  ks->must_die = current + session->opt->transition_window; /* remaining lifetime of old key */
 
2219
  ks->must_die = now + session->opt->transition_window; /* remaining lifetime of old key */
1714
2220
  key_state_free (ks_lame, false);
1715
2221
  *ks_lame = *ks;
1716
2222
 
1717
 
  key_state_init (session, ks, current);
 
2223
  key_state_init (session, ks);
1718
2224
  ks->session_id_remote = ks_lame->session_id_remote;
1719
2225
  ks->remote_addr = ks_lame->remote_addr;
1720
2226
}
1721
2227
 
1722
2228
/*
 
2229
 * Read/write strings from/to a struct buffer with a u16 length prefix.
 
2230
 */
 
2231
 
 
2232
static bool
 
2233
write_string (struct buffer *buf, const char *str, const int maxlen)
 
2234
{
 
2235
  const int len = strlen (str) + 1;
 
2236
  if (len < 1 || (maxlen >= 0 && len > maxlen))
 
2237
    return false;
 
2238
  if (!buf_write_u16 (buf, len))
 
2239
    return false;
 
2240
  if (!buf_write (buf, str, len))
 
2241
    return false;
 
2242
  return true;
 
2243
}
 
2244
 
 
2245
static bool
 
2246
read_string (struct buffer *buf, char *str, const unsigned int capacity)
 
2247
{
 
2248
  const int len = buf_read_u16 (buf);
 
2249
  if (len < 1 || len > (int)capacity)
 
2250
    return false;
 
2251
  if (!buf_read (buf, str, len))
 
2252
    return false;
 
2253
  str[len-1] = '\0';
 
2254
  return true;
 
2255
}
 
2256
 
 
2257
/*
 
2258
 * Authenticate a client using username/password.
 
2259
 * Runs on server.
 
2260
 *
 
2261
 * If you want to add new authentication methods,
 
2262
 * this is the place to start.
 
2263
 */
 
2264
 
 
2265
static bool
 
2266
verify_user_pass_script (struct tls_session *session, const struct user_pass *up)
 
2267
{
 
2268
  struct gc_arena gc = gc_new ();
 
2269
  struct buffer cmd = alloc_buf_gc (256, &gc);
 
2270
  const char *tmp_file = "";
 
2271
  int retval;
 
2272
  bool ret = false;
 
2273
 
 
2274
  /* Is username defined? */
 
2275
  if (strlen (up->username))
 
2276
    {
 
2277
      /* Set environmental variables prior to calling script */
 
2278
      setenv_str (session->opt->es, "script_type", "user-pass-verify");
 
2279
 
 
2280
      if (session->opt->auth_user_pass_verify_script_via_file)
 
2281
        {
 
2282
          struct status_output *so;
 
2283
 
 
2284
          tmp_file = create_temp_filename (session->opt->tmp_dir, &gc);
 
2285
          so = status_open (tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
 
2286
          status_printf (so, "%s", up->username);
 
2287
          status_printf (so, "%s", up->password);
 
2288
          if (!status_close (so))
 
2289
            {
 
2290
              msg (D_TLS_ERRORS, "TLS Auth Error: could not write username/password to file: %s",
 
2291
                   tmp_file);
 
2292
              goto done;
 
2293
            }
 
2294
        }
 
2295
      else
 
2296
        {
 
2297
          setenv_str (session->opt->es, "username", up->username);
 
2298
          setenv_str (session->opt->es, "password", up->password);
 
2299
        }
 
2300
 
 
2301
      /* setenv incoming cert common name for script */
 
2302
      setenv_str (session->opt->es, "common_name", session->common_name);
 
2303
 
 
2304
      /* setenv client real IP address */
 
2305
      setenv_untrusted (session);
 
2306
 
 
2307
      /* format command line */
 
2308
      buf_printf (&cmd, "%s %s", session->opt->auth_user_pass_verify_script, tmp_file);
 
2309
      
 
2310
      /* call command */
 
2311
      retval = openvpn_system (BSTR (&cmd), session->opt->es, S_SCRIPT);
 
2312
 
 
2313
      /* test return status of command */
 
2314
      if (system_ok (retval))
 
2315
        ret = true;
 
2316
      else if (!system_executed (retval))
 
2317
        msg (D_TLS_ERRORS, "TLS Auth Error: user-pass-verify script failed to execute: %s", BSTR (&cmd));
 
2318
          
 
2319
      if (!session->opt->auth_user_pass_verify_script_via_file)
 
2320
        setenv_del (session->opt->es, "password");
 
2321
    }
 
2322
  else
 
2323
    {
 
2324
      msg (D_TLS_ERRORS, "TLS Auth Error: peer provided a blank username");
 
2325
    }
 
2326
 
 
2327
 done:
 
2328
  if (strlen (tmp_file) > 0)
 
2329
    delete_file (tmp_file);
 
2330
 
 
2331
  gc_free (&gc);
 
2332
  return ret;
 
2333
}
 
2334
 
 
2335
static bool
 
2336
verify_user_pass_plugin (struct tls_session *session, const struct user_pass *up)
 
2337
{
 
2338
  int retval;
 
2339
  bool ret = false;
 
2340
 
 
2341
  /* Is username defined? */
 
2342
  if (strlen (up->username))
 
2343
    {
 
2344
      /* set username/password in private env space */
 
2345
      setenv_str (session->opt->es, "username", up->username);
 
2346
      setenv_str (session->opt->es, "password", up->password);
 
2347
 
 
2348
      /* setenv incoming cert common name for script */
 
2349
      setenv_str (session->opt->es, "common_name", session->common_name);
 
2350
 
 
2351
      /* setenv client real IP address */
 
2352
      setenv_untrusted (session);
 
2353
 
 
2354
      /* call command */
 
2355
      retval = plugin_call (session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY, NULL, session->opt->es);
 
2356
 
 
2357
      if (!retval)
 
2358
        ret = true;
 
2359
 
 
2360
      setenv_del (session->opt->es, "password");
 
2361
    }
 
2362
  else
 
2363
    {
 
2364
      msg (D_TLS_ERRORS, "TLS Auth Error: peer provided a blank username");
 
2365
    }
 
2366
 
 
2367
  return ret;
 
2368
}
 
2369
 
 
2370
/*
 
2371
 * Handle the reading and writing of key data to and from
 
2372
 * the TLS control channel (cleartext).
 
2373
 */
 
2374
 
 
2375
static bool
 
2376
key_method_1_write (struct buffer *buf, struct tls_session *session)
 
2377
{
 
2378
  struct key key;
 
2379
 
 
2380
  ASSERT (session->opt->key_method == 1);
 
2381
  ASSERT (buf_init (buf, 0));
 
2382
 
 
2383
  generate_key_random (&key, &session->opt->key_type);
 
2384
  if (!check_key (&key, &session->opt->key_type))
 
2385
    {
 
2386
      msg (D_TLS_ERRORS, "TLS Error: Bad encrypting key generated");
 
2387
      return false;
 
2388
    }
 
2389
 
 
2390
  if (!write_key (&key, &session->opt->key_type, buf))
 
2391
    {
 
2392
      msg (D_TLS_ERRORS, "TLS Error: write_key failed");
 
2393
      return false;
 
2394
    }
 
2395
 
 
2396
  init_key_ctx (&ks->key.encrypt, &key, &session->opt->key_type,
 
2397
                DO_ENCRYPT, "Data Channel Encrypt");
 
2398
  CLEAR (key);
 
2399
 
 
2400
  /* send local options string */
 
2401
  {
 
2402
    const char *local_options = local_options_string (session);
 
2403
    const int optlen = strlen (local_options) + 1;
 
2404
    if (!buf_write (buf, local_options, optlen))
 
2405
      {
 
2406
        msg (D_TLS_ERRORS, "TLS Error: KM1 write options failed");
 
2407
        return false;
 
2408
      }
 
2409
  }
 
2410
 
 
2411
  return true;
 
2412
}
 
2413
 
 
2414
static bool
 
2415
key_method_2_write (struct buffer *buf, struct tls_session *session)
 
2416
{
 
2417
  ASSERT (session->opt->key_method == 2);
 
2418
  ASSERT (buf_init (buf, 0));
 
2419
 
 
2420
  /* write a uint32 0 */
 
2421
  if (!buf_write_u32 (buf, 0))
 
2422
    goto error;
 
2423
 
 
2424
  /* write key_method + flags */
 
2425
  if (!buf_write_u8 (buf, (session->opt->key_method & KEY_METHOD_MASK)))
 
2426
    goto error;
 
2427
 
 
2428
  /* write key source material */
 
2429
  if (!key_source2_randomize_write (ks->key_src, buf, session->opt->server))
 
2430
    goto error;
 
2431
 
 
2432
  /* write options string */
 
2433
  {
 
2434
    if (!write_string (buf, local_options_string (session), TLS_OPTIONS_LEN))
 
2435
      goto error;
 
2436
  }
 
2437
 
 
2438
  /* write username/password if specified */
 
2439
  if (auth_user_pass_enabled)
 
2440
    {
 
2441
      auth_user_pass_setup (NULL);
 
2442
      if (!write_string (buf, auth_user_pass.username, -1))
 
2443
        goto error;
 
2444
      if (!write_string (buf, auth_user_pass.password, -1))
 
2445
        goto error;
 
2446
      purge_user_pass (&auth_user_pass);
 
2447
    }
 
2448
 
 
2449
  /*
 
2450
   * generate tunnel keys if server
 
2451
   */
 
2452
  if (session->opt->server)
 
2453
    {
 
2454
      if (ks->authenticated)
 
2455
        {
 
2456
          if (!generate_key_expansion (&ks->key,
 
2457
                                       &session->opt->key_type,
 
2458
                                       ks->key_src,
 
2459
                                       &ks->session_id_remote,
 
2460
                                       &session->session_id,
 
2461
                                       true))
 
2462
            {
 
2463
              msg (D_TLS_ERRORS, "TLS Error: server generate_key_expansion failed");
 
2464
              goto error;
 
2465
            }
 
2466
        }
 
2467
                      
 
2468
      CLEAR (*ks->key_src);
 
2469
    }
 
2470
 
 
2471
  return true;
 
2472
 
 
2473
 error:
 
2474
  msg (D_TLS_ERRORS, "TLS Error: Key Method #2 write failed");
 
2475
  CLEAR (*ks->key_src);
 
2476
  return false;
 
2477
}
 
2478
 
 
2479
static bool
 
2480
key_method_1_read (struct buffer *buf, struct tls_session *session)
 
2481
{
 
2482
  int status;
 
2483
  struct key key;
 
2484
 
 
2485
  ASSERT (session->opt->key_method == 1);
 
2486
 
 
2487
  if (!session->verified)
 
2488
    {
 
2489
      msg (D_TLS_ERRORS,
 
2490
           "TLS Error: Certificate verification failed (key-method 1)");
 
2491
      goto error;
 
2492
    }
 
2493
 
 
2494
  status = read_key (&key, &session->opt->key_type, buf);
 
2495
  if (status != 1)
 
2496
    {
 
2497
      msg (D_TLS_ERRORS,
 
2498
           "TLS Error: Error reading data channel key from plaintext buffer");
 
2499
      goto error;
 
2500
    }
 
2501
 
 
2502
  if (!check_key (&key, &session->opt->key_type))
 
2503
    {
 
2504
      msg (D_TLS_ERRORS, "TLS Error: Bad decrypting key received from peer");
 
2505
      goto error;
 
2506
    }
 
2507
 
 
2508
  if (buf->len < 1)
 
2509
    {
 
2510
      msg (D_TLS_ERRORS, "TLS Error: Missing options string");
 
2511
      goto error;
 
2512
    }
 
2513
 
 
2514
#ifdef ENABLE_OCC
 
2515
  /* compare received remote options string
 
2516
     with our locally computed options string */
 
2517
  if (!session->opt->disable_occ &&
 
2518
      !options_cmp_equal_safe (BPTR (buf), session->opt->remote_options, buf->len))
 
2519
    {
 
2520
      options_warning_safe (BPTR (buf), session->opt->remote_options, buf->len);
 
2521
    }
 
2522
#endif
 
2523
 
 
2524
  buf_clear (buf);
 
2525
 
 
2526
  init_key_ctx (&ks->key.decrypt, &key, &session->opt->key_type,
 
2527
                DO_DECRYPT, "Data Channel Decrypt");
 
2528
  CLEAR (key);
 
2529
  ks->authenticated = true;
 
2530
  return true;
 
2531
 
 
2532
 error:
 
2533
  buf_clear (buf);
 
2534
  CLEAR (key);
 
2535
  return false;
 
2536
}
 
2537
 
 
2538
static bool
 
2539
key_method_2_read (struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
 
2540
{
 
2541
  struct gc_arena gc = gc_new ();
 
2542
  int key_method_flags;
 
2543
  char *options;
 
2544
  struct user_pass *up;
 
2545
 
 
2546
  ASSERT (session->opt->key_method == 2);
 
2547
 
 
2548
  /* allocate temporary objects */
 
2549
  ALLOC_ARRAY_CLEAR_GC (options, char, TLS_OPTIONS_LEN, &gc);
 
2550
                  
 
2551
  /* discard leading uint32 */
 
2552
  ASSERT (buf_advance (buf, 4));
 
2553
 
 
2554
  /* get key method */
 
2555
  key_method_flags = buf_read_u8 (buf);
 
2556
  if ((key_method_flags & KEY_METHOD_MASK) != 2)
 
2557
    {
 
2558
      msg (D_TLS_ERRORS,
 
2559
           "TLS ERROR: Unknown key_method/flags=%d received from remote host",
 
2560
           key_method_flags);
 
2561
      goto error;
 
2562
    }
 
2563
 
 
2564
  /* get key source material (not actual keys yet) */
 
2565
  if (!key_source2_read (ks->key_src, buf, session->opt->server))
 
2566
    {
 
2567
      msg (D_TLS_ERRORS, "TLS Error: Error reading remote data channel key source entropy from plaintext buffer");
 
2568
      goto error;
 
2569
    }
 
2570
 
 
2571
  /* get options */
 
2572
  if (!read_string (buf, options, TLS_OPTIONS_LEN))
 
2573
    {
 
2574
      msg (D_TLS_ERRORS, "TLS Error: Failed to read required OCC options string");
 
2575
      goto error;
 
2576
    }
 
2577
 
 
2578
  /* should we check username/password? */
 
2579
  ks->authenticated = false;
 
2580
  if (session->opt->auth_user_pass_verify_script
 
2581
      || plugin_defined (session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY))
 
2582
    {
 
2583
      bool s1 = true;
 
2584
      bool s2 = true;
 
2585
 
 
2586
      /* get username/password from plaintext buffer */
 
2587
      ALLOC_OBJ_CLEAR_GC (up, struct user_pass, &gc);
 
2588
      if (!read_string (buf, up->username, USER_PASS_LEN)
 
2589
          || !read_string (buf, up->password, USER_PASS_LEN))
 
2590
        {
 
2591
          msg (D_TLS_ERRORS, "TLS Error: Auth Username/Password was not provided by peer");
 
2592
          CLEAR (*up);
 
2593
          goto error;
 
2594
        }
 
2595
 
 
2596
      /* enforce character class restrictions in username/password */
 
2597
      string_mod (up->username, COMMON_NAME_CHAR_CLASS, 0, '_');
 
2598
      string_mod (up->password, CC_PRINT, CC_CRLF, '_');
 
2599
 
 
2600
      /* call plugin(s) and/or script */
 
2601
      if (plugin_defined (session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY))
 
2602
        s1 = verify_user_pass_plugin (session, up);
 
2603
      if (session->opt->auth_user_pass_verify_script)
 
2604
        s2 = verify_user_pass_script (session, up);
 
2605
      
 
2606
      /* auth succeeded? */
 
2607
      if (s1 && s2)
 
2608
        {
 
2609
          ks->authenticated = true;
 
2610
          if (session->opt->username_as_common_name)
 
2611
            set_common_name (session, up->username);
 
2612
          msg (D_HANDSHAKE, "TLS: Username/Password authentication succeeded for username '%s' %s",
 
2613
               up->username,
 
2614
               session->opt->username_as_common_name ? "[CN SET]" : "");
 
2615
        }
 
2616
      else
 
2617
        {
 
2618
          msg (D_TLS_ERRORS, "TLS Auth Error: Auth Username/Password verification failed for peer");
 
2619
        }
 
2620
 
 
2621
      CLEAR (*up);
 
2622
    }
 
2623
  else
 
2624
    {
 
2625
      if (!session->verified)
 
2626
        {
 
2627
          msg (D_TLS_ERRORS,
 
2628
               "TLS Error: Certificate verification failed (key-method 2)");
 
2629
          goto error;
 
2630
        }
 
2631
      ks->authenticated = true;
 
2632
    }
 
2633
 
 
2634
  /* While it shouldn't really happen, don't allow the common name to be NULL */
 
2635
  if (!session->common_name)
 
2636
    set_common_name (session, "");
 
2637
 
 
2638
  /* Don't allow the CN to change once it's been locked */
 
2639
  if (ks->authenticated && multi->locked_cn)
 
2640
    {
 
2641
      const char *cn = session->common_name;
 
2642
      if (cn && strcmp (cn, multi->locked_cn))
 
2643
        {
 
2644
          msg (D_TLS_ERRORS, "TLS Auth Error: TLS object CN attempted to change from '%s' to '%s' -- tunnel disabled",
 
2645
               multi->locked_cn,
 
2646
               cn);
 
2647
 
 
2648
          /* change the common name back to its original value and disable the tunnel */
 
2649
          set_common_name (session, multi->locked_cn);
 
2650
          tls_deauthenticate (multi);
 
2651
        }
 
2652
    }
 
2653
 
 
2654
  /* verify --client-config-dir based authentication */
 
2655
  if (ks->authenticated && session->opt->client_config_dir_exclusive)
 
2656
    {
 
2657
      const char *cn = session->common_name;
 
2658
      const char *path = gen_path (session->opt->client_config_dir_exclusive, cn, &gc);
 
2659
      if (!cn || !strcmp (cn, CCD_DEFAULT) || !test_file (path))
 
2660
        {
 
2661
          ks->authenticated = false;
 
2662
          msg (D_TLS_ERRORS, "TLS Auth Error: --client-config-dir authentication failed for common name '%s' file='%s'",
 
2663
               session->common_name,
 
2664
               path ? path : "UNDEF");
 
2665
        }
 
2666
    }
 
2667
 
 
2668
#ifdef ENABLE_OCC
 
2669
  /* check options consistency */
 
2670
  if (!session->opt->disable_occ &&
 
2671
      !options_cmp_equal (options, session->opt->remote_options))
 
2672
    {
 
2673
      options_warning (options, session->opt->remote_options);
 
2674
    }
 
2675
#endif
 
2676
 
 
2677
  buf_clear (buf);
 
2678
 
 
2679
  /*
 
2680
   * generate tunnel keys if client
 
2681
   */
 
2682
  if (!session->opt->server)
 
2683
    {
 
2684
      if (!generate_key_expansion (&ks->key,
 
2685
                                   &session->opt->key_type,
 
2686
                                   ks->key_src,
 
2687
                                   &session->session_id,
 
2688
                                   &ks->session_id_remote,
 
2689
                                   false))
 
2690
        {
 
2691
          msg (D_TLS_ERRORS, "TLS Error: client generate_key_expansion failed");
 
2692
          goto error;
 
2693
        }
 
2694
                      
 
2695
      CLEAR (*ks->key_src);
 
2696
    }
 
2697
 
 
2698
  gc_free (&gc);
 
2699
  return true;
 
2700
 
 
2701
 error:
 
2702
  CLEAR (*ks->key_src);
 
2703
  buf_clear (buf);
 
2704
  gc_free (&gc);
 
2705
  return false;
 
2706
}
 
2707
 
 
2708
/*
1723
2709
 * This is the primary routine for processing TLS stuff inside the
1724
 
 * the main event loop (see openvpn.c).  When this routine exits
 
2710
 * the main event loop.  When this routine exits
1725
2711
 * with non-error status, it will set *wakeup to the number of seconds
1726
2712
 * when it wants to be called again.
1727
2713
 *
1733
2719
             struct tls_session *session,
1734
2720
             struct buffer *to_link,
1735
2721
             struct sockaddr_in *to_link_addr,
1736
 
             struct link_socket *to_link_socket,
1737
 
             interval_t *wakeup,
1738
 
             time_t current)
 
2722
             struct link_socket_info *to_link_socket_info,
 
2723
             interval_t *wakeup)
1739
2724
{
 
2725
  struct gc_arena gc = gc_new ();
1740
2726
  struct buffer *buf;
1741
2727
  bool state_change = false;
1742
2728
  bool active = false;
1749
2735
  /* Should we trigger a soft reset? -- new key, keeps old key for a while */
1750
2736
  if (ks->state >= S_ACTIVE &&
1751
2737
      ((session->opt->renegotiate_seconds
1752
 
        && current >= ks->established + session->opt->renegotiate_seconds)
 
2738
        && now >= ks->established + session->opt->renegotiate_seconds)
1753
2739
       || (session->opt->renegotiate_bytes
1754
2740
           && ks->n_bytes >= session->opt->renegotiate_bytes)
1755
2741
       || (session->opt->renegotiate_packets
1757
2743
       || (packet_id_close_to_wrapping (&ks->packet_id.send))))
1758
2744
    {
1759
2745
      msg (D_TLS_DEBUG_LOW, "TLS: soft reset sec=%d bytes=%d/%d pkts=%d/%d",
1760
 
           (int)(ks->established + session->opt->renegotiate_seconds - current),
 
2746
           (int)(ks->established + session->opt->renegotiate_seconds - now),
1761
2747
           ks->n_bytes, session->opt->renegotiate_bytes,
1762
2748
           ks->n_packets, session->opt->renegotiate_packets);
1763
 
      key_state_soft_reset (session, current);
 
2749
      key_state_soft_reset (session);
1764
2750
    }
1765
2751
 
1766
2752
  /* Kill lame duck key transition_window seconds after primary key negotiation */
1767
 
  if (lame_duck_must_die (session, wakeup, current)) {
 
2753
  if (lame_duck_must_die (session, wakeup)) {
1768
2754
        key_state_free (ks_lame, true);
1769
2755
        msg (D_TLS_DEBUG_LOW, "TLS: tls_process: killed expiring key");
1770
2756
  }
1771
2757
 
1772
 
  mutex_cycle (L_TLS);
 
2758
  //mutex_cycle (multi->mutex);
1773
2759
 
1774
2760
  do
1775
2761
    {
1776
 
      current = time (NULL);
 
2762
      update_time ();
1777
2763
 
1778
 
      msg (D_TLS_DEBUG, "tls_process: chg=%d ks=%s lame=%s to_link->len=%d wakeup=%d",
 
2764
      dmsg (D_TLS_DEBUG, "TLS: tls_process: chg=%d ks=%s lame=%s to_link->len=%d wakeup=%d",
1779
2765
           state_change,
1780
2766
           state_name (ks->state),
1781
2767
           state_name (ks_lame->state),
1787
2773
      /*
1788
2774
       * TLS activity is finished once we get to S_ACTIVE,
1789
2775
       * though we will still process acknowledgements.
 
2776
       *
 
2777
       * CHANGED with 2.0 -> now we may send tunnel configuration
 
2778
       * info over the control channel.
1790
2779
       */
1791
 
      if (ks->state < S_NORMAL)
 
2780
      if (true)
1792
2781
        {
1793
2782
          /* Initial handshake */
1794
2783
          if (ks->state == S_INITIAL)
1795
2784
            {
1796
 
              buf = reliable_get_buf_output_sequenced (&ks->send_reliable);
 
2785
              buf = reliable_get_buf_output_sequenced (ks->send_reliable);
1797
2786
              if (buf)
1798
2787
                {
1799
 
                  ks->must_negotiate = current + session->opt->handshake_window;
 
2788
                  ks->must_negotiate = now + session->opt->handshake_window;
1800
2789
 
1801
2790
                  /* null buffer */
1802
 
                  reliable_mark_active_outgoing (&ks->send_reliable, buf, ks->initial_opcode);
 
2791
                  reliable_mark_active_outgoing (ks->send_reliable, buf, ks->initial_opcode);
1803
2792
                  INCR_GENERATED;
1804
2793
              
1805
2794
                  ks->state = S_PRE_START;
1806
2795
                  state_change = true;
1807
 
                  msg (D_TLS_DEBUG, "Initial Handshake, sid=%s",
1808
 
                       session_id_print (&session->session_id));
 
2796
                  dmsg (D_TLS_DEBUG, "TLS: Initial Handshake, sid=%s",
 
2797
                       session_id_print (&session->session_id, &gc));
 
2798
 
 
2799
#ifdef ENABLE_MANAGEMENT
 
2800
                  if (management && ks->initial_opcode != P_CONTROL_SOFT_RESET_V1)
 
2801
                    {
 
2802
                      management_set_state (management,
 
2803
                                            OPENVPN_STATE_WAIT,
 
2804
                                            NULL,
 
2805
                                            0);
 
2806
                    }
 
2807
#endif
1809
2808
                }
1810
2809
            }
1811
2810
 
1812
2811
          /* Are we timed out on receive? */
1813
 
          if (current >= ks->must_negotiate)
 
2812
          if (now >= ks->must_negotiate)
1814
2813
            {
1815
2814
              if (ks->state < S_ACTIVE)
1816
2815
                {
1817
2816
                  msg (D_TLS_ERRORS,
1818
 
                       "TLS Error: TLS key negotiation failed to occur within %d seconds",
 
2817
                       "TLS Error: TLS key negotiation failed to occur within %d seconds (check your network connectivity)",
1819
2818
                       session->opt->handshake_window);
1820
2819
                  goto error;
1821
2820
                }
1822
2821
              else /* assume that ks->state == S_ACTIVE */
1823
2822
                {
1824
 
                  msg (D_TLS_DEBUG_MED, "STATE S_NORMAL");
 
2823
                  dmsg (D_TLS_DEBUG_MED, "STATE S_NORMAL");
1825
2824
                  ks->state = S_NORMAL;
 
2825
                  ks->must_negotiate = 0;
1826
2826
                }
1827
2827
            }
1828
2828
 
1831
2831
            {
1832
2832
              ks->state = S_START;
1833
2833
              state_change = true;
1834
 
              msg (D_TLS_DEBUG_MED, "STATE S_START");
 
2834
              dmsg (D_TLS_DEBUG_MED, "STATE S_START");
1835
2835
            }
1836
2836
 
1837
2837
          /* Wait for ACK */
1840
2840
            {
1841
2841
              if (FULL_SYNC)
1842
2842
                {
1843
 
                  ks->established = current;
1844
 
                  msg (D_TLS_DEBUG_MED, "STATE S_ACTIVE");
 
2843
                  ks->established = now;
 
2844
                  dmsg (D_TLS_DEBUG_MED, "STATE S_ACTIVE");
1845
2845
                  if (check_debug_level (D_HANDSHAKE))
1846
2846
                    print_details (ks->ssl, "Control Channel:");
1847
2847
                  state_change = true;
1849
2849
                  INCR_SUCCESS;
1850
2850
 
1851
2851
                  /* Set outgoing address for data channel packets */
1852
 
                  link_socket_set_outgoing_addr (NULL, to_link_socket, &ks->remote_addr);
 
2852
                  link_socket_set_outgoing_addr (NULL, to_link_socket_info, &ks->remote_addr, session->common_name, session->opt->es);
1853
2853
 
1854
2854
#ifdef MEASURE_TLS_HANDSHAKE_STATS
1855
2855
                  show_tls_performance_stats();
1859
2859
 
1860
2860
          /* Reliable buffer to outgoing TCP/UDP (send up to CONTROL_SEND_ACK_MAX ACKs
1861
2861
             for previously received packets) */
1862
 
          if (!to_link->len && reliable_can_send (&ks->send_reliable, current))
 
2862
          if (!to_link->len && reliable_can_send (ks->send_reliable))
1863
2863
            {
1864
2864
              int opcode;
1865
2865
              struct buffer b;
1866
2866
 
1867
 
              buf = reliable_send (&ks->send_reliable, &opcode, current);
 
2867
              buf = reliable_send (ks->send_reliable, &opcode);
1868
2868
              ASSERT (buf);
1869
2869
              b = *buf;
1870
2870
              INCR_SENT;
1871
2871
 
1872
2872
              write_control_auth (session, ks, &b, to_link_addr, opcode,
1873
 
                                      CONTROL_SEND_ACK_MAX, true, current);
 
2873
                                  CONTROL_SEND_ACK_MAX, true);
1874
2874
              *to_link = b;
1875
2875
              active = true;
1876
2876
              state_change = true;
1877
 
              msg (D_TLS_DEBUG, "Reliable -> TCP/UDP");
 
2877
              dmsg (D_TLS_DEBUG, "Reliable -> TCP/UDP");
1878
2878
              break;
1879
2879
            }
1880
2880
 
1881
2881
#ifndef TLS_AGGREGATE_ACK
1882
2882
          /* Send 1 or more ACKs (each received control packet gets one ACK) */
1883
 
          if (!to_link->len && !reliable_ack_empty (&ks->rec_ack))
 
2883
          if (!to_link->len && !reliable_ack_empty (ks->rec_ack))
1884
2884
            {
1885
2885
              buf = &ks->ack_write_buf;
1886
2886
              ASSERT (buf_init (buf, FRAME_HEADROOM (&multi->opt.frame)));
1887
2887
              write_control_auth (session, ks, buf, to_link_addr, P_ACK_V1,
1888
 
                                  RELIABLE_ACK_SIZE, false, current);
 
2888
                                  RELIABLE_ACK_SIZE, false);
1889
2889
              *to_link = *buf;
1890
2890
              active = true;
1891
2891
              state_change = true;
1892
 
              msg (D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP");
 
2892
              dmsg (D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP");
1893
2893
              break;
1894
2894
            }
1895
2895
#endif
1896
2896
 
1897
2897
          /* Write incoming ciphertext to TLS object */
1898
 
          buf = reliable_get_buf_sequenced (&ks->rec_reliable);
 
2898
          buf = reliable_get_buf_sequenced (ks->rec_reliable);
1899
2899
          if (buf)
1900
2900
            {
1901
2901
              int status = 0;
1902
2902
              if (buf->len)
1903
2903
                {
1904
 
                  status = key_state_write_ciphertext (ks, buf);
 
2904
                  status = key_state_write_ciphertext (multi, ks, buf);
1905
2905
                  if (status == -1)
1906
2906
                    {
1907
2907
                      msg (D_TLS_ERRORS,
1915
2915
                }
1916
2916
              if (status == 1)
1917
2917
                {
1918
 
                  reliable_mark_deleted (&ks->rec_reliable, buf, true);
 
2918
                  reliable_mark_deleted (ks->rec_reliable, buf, true);
1919
2919
                  state_change = true;
1920
 
                  msg (D_TLS_DEBUG, "Incoming Ciphertext -> TLS");
 
2920
                  dmsg (D_TLS_DEBUG, "Incoming Ciphertext -> TLS");
1921
2921
                }
1922
2922
            }
1923
2923
 
1928
2928
              int status;
1929
2929
 
1930
2930
              ASSERT (buf_init (buf, 0));
1931
 
              status = key_state_read_plaintext (ks, buf, PLAINTEXT_BUFFER_SIZE);
1932
 
              current = time (NULL);
 
2931
              status = key_state_read_plaintext (multi, ks, buf, PLAINTEXT_BUFFER_SIZE);
 
2932
              update_time ();
1933
2933
              if (status == -1)
1934
2934
                {
1935
2935
                  msg (D_TLS_ERRORS, "TLS Error: TLS object -> incoming plaintext read error");
1938
2938
              if (status == 1)
1939
2939
                {
1940
2940
                  state_change = true;
1941
 
                  msg (D_TLS_DEBUG, "TLS -> Incoming Plaintext");
 
2941
                  dmsg (D_TLS_DEBUG, "TLS -> Incoming Plaintext");
1942
2942
                }
 
2943
#if 0 // show null plaintext reads
 
2944
              if (!status)
 
2945
                msg (M_INFO, "TLS plaintext read -> NULL return");
 
2946
#endif
1943
2947
            }
1944
2948
 
1945
2949
          /* Send Key */
1947
2951
          if (!buf->len && ((ks->state == S_START && !session->opt->server) ||
1948
2952
                            (ks->state == S_GOT_KEY && session->opt->server)))
1949
2953
            {
1950
 
              const int optlen = strlen (session->opt->local_options) + 1;
1951
2954
              if (session->opt->key_method == 1)
1952
2955
                {
1953
 
                  struct key key;
1954
 
                  ASSERT (buf_init (buf, 0));
1955
 
                  generate_key_random (&key, &session->opt->key_type);
1956
 
                  if (!check_key (&key, &session->opt->key_type))
1957
 
                    {
1958
 
                      msg (D_TLS_ERRORS, "TLS Error: Bad encrypting key generated");
1959
 
                      goto error;
1960
 
                    }
1961
 
                  write_key (&key, &session->opt->key_type, buf);
1962
 
                  init_key_ctx (&ks->key.encrypt, &key, &session->opt->key_type,
1963
 
                                DO_ENCRYPT, "Data Channel Encrypt");
1964
 
                  CLEAR (key);
1965
 
 
1966
 
                  /* send local options string */
1967
 
                  ASSERT (buf_write (buf, session->opt->local_options, optlen));
 
2956
                  if (!key_method_1_write (buf, session))
 
2957
                    goto error;
 
2958
                }
 
2959
              else if (session->opt->key_method == 2)
 
2960
                {
 
2961
                  if (!key_method_2_write (buf, session))
 
2962
                    goto error;
1968
2963
                }
1969
2964
              else
1970
2965
                {
1971
 
                  ASSERT (session->opt->key_method == 2);
1972
 
                  ASSERT (buf_init (buf, 0));
1973
 
 
1974
 
                  /* write a uin32 0 */
1975
 
                  ASSERT (buf_write_u32 (buf, 0));
1976
 
 
1977
 
                  /* write key_method */
1978
 
                  ASSERT (buf_write_u8 (buf, session->opt->key_method));
1979
 
 
1980
 
                  /* write key source material */
1981
 
                  key_source2_randomize_write (&ks->key_src, buf, session->opt->server);
1982
 
 
1983
 
                  /* write options string */
1984
 
                  ASSERT (optlen >= 0 && optlen < 65536);
1985
 
                  ASSERT (buf_write_u16 (buf, optlen));
1986
 
                  ASSERT (buf_write (buf, session->opt->local_options, optlen));
1987
 
 
1988
 
                  if (session->opt->server)
1989
 
                    {
1990
 
                      if (!generate_key_expansion (&ks->key,
1991
 
                                                   &session->opt->key_type,
1992
 
                                                   &ks->key_src,
1993
 
                                                   &ks->session_id_remote,
1994
 
                                                   &session->session_id,
1995
 
                                                   true))
1996
 
                        goto error;
1997
 
                      
1998
 
                      CLEAR (ks->key_src);
1999
 
                    }
 
2966
                  ASSERT (0);
2000
2967
                }
2001
2968
 
2002
2969
              state_change = true;
2003
 
              msg (D_TLS_DEBUG_MED, "STATE S_SENT_KEY");
 
2970
              dmsg (D_TLS_DEBUG_MED, "STATE S_SENT_KEY");
2004
2971
              ks->state = S_SENT_KEY;
2005
2972
            }
2006
2973
 
2012
2979
            {
2013
2980
              if (session->opt->key_method == 1)
2014
2981
                {
2015
 
                  int status;
2016
 
                  struct key key;
2017
 
 
2018
 
                  status = read_key (&key, &session->opt->key_type, buf);
2019
 
                  if (status == -1)
2020
 
                    {
2021
 
                      msg (D_TLS_ERRORS,
2022
 
                           "TLS Error: Error reading data channel key from plaintext buffer");
2023
 
                      goto error;
2024
 
                    }
2025
 
 
2026
 
                  if (!check_key (&key, &session->opt->key_type))
2027
 
                    {
2028
 
                      msg (D_TLS_ERRORS, "TLS Error: Bad decrypting key received from peer");
2029
 
                      goto error;
2030
 
                    }
2031
 
 
2032
 
                  ASSERT (buf->len > 0);
2033
 
 
2034
 
                  /* compare received remote options string
2035
 
                     with our locally computed options string */
2036
 
                  if (!session->opt->disable_occ &&
2037
 
                      !options_cmp_equal (BPTR (buf),
2038
 
                                          session->opt->remote_options, buf->len))
2039
 
                    {
2040
 
                      options_warning (BPTR (buf),
2041
 
                                       session->opt->remote_options, buf->len);
2042
 
                    }
2043
 
                  buf_clear (buf);
2044
 
 
2045
 
                  if (status == 1)
2046
 
                    {
2047
 
                      init_key_ctx (&ks->key.decrypt, &key, &session->opt->key_type,
2048
 
                                    DO_DECRYPT, "Data Channel Decrypt");
2049
 
                    }
2050
 
                  CLEAR (key);
2051
 
 
2052
 
                  if (status == 0)
 
2982
                  if (!key_method_1_read (buf, session))
 
2983
                    goto error;
 
2984
                }
 
2985
              else if (session->opt->key_method == 2)
 
2986
                {
 
2987
                  if (!key_method_2_read (buf, multi, session))
2053
2988
                    goto error;
2054
2989
                }
2055
2990
              else
2056
2991
                {
2057
 
                  int key_method;
2058
 
                  int status;
2059
 
                  int optlen;
2060
 
 
2061
 
                  ASSERT (session->opt->key_method >= 2);
2062
 
                  status = 0;
2063
 
                  
2064
 
                  /* discard leading uint32 */
2065
 
                  ASSERT (buf_advance (buf, 4));
2066
 
 
2067
 
                  /* get key method */
2068
 
                  key_method = buf_read_u8 (buf);
2069
 
                  if (key_method != 2)
2070
 
                    {
2071
 
                      msg (D_TLS_ERRORS,
2072
 
                           "TLS ERROR: Unknown key_method=%d received from remote host",
2073
 
                           key_method);
2074
 
                      goto error;
2075
 
                    }
2076
 
                  
2077
 
                  /* get key source material (not actual keys yet) */
2078
 
                  if (!key_source2_read (&ks->key_src, buf, session->opt->server))
2079
 
                    {
2080
 
                      msg (D_TLS_ERRORS, "TLS Error: Error reading remote data channel key source entropy from plaintext buffer");
2081
 
                      goto error;
2082
 
                    }
2083
 
 
2084
 
                  /* get options */
2085
 
                  optlen = buf_read_u16 (buf);
2086
 
                  if (optlen < 0 || optlen >= 65536)
2087
 
                    {
2088
 
                      msg (D_TLS_ERRORS, "TLS Error: Bad options string length: %d", optlen);
2089
 
                      goto error;
2090
 
                    }
2091
 
 
2092
 
                  if (BLEN(buf) < optlen)
2093
 
                    {
2094
 
                      msg (D_TLS_ERRORS, "TLS Error: Options string truncation");
2095
 
                      goto error;
2096
 
                    }
2097
 
 
2098
 
                  /* check options consistency */
2099
 
 
2100
 
                  if (!session->opt->disable_occ &&
2101
 
                      !options_cmp_equal (BPTR (buf),
2102
 
                                          session->opt->remote_options, buf->len))
2103
 
                    {
2104
 
                      options_warning (BPTR (buf),
2105
 
                                       session->opt->remote_options, buf->len);
2106
 
                    }
2107
 
 
2108
 
                  buf_clear (buf);
2109
 
 
2110
 
                  if (!session->opt->server)
2111
 
                    {
2112
 
                      if (!generate_key_expansion (&ks->key,
2113
 
                                                   &session->opt->key_type,
2114
 
                                                   &ks->key_src,
2115
 
                                                   &session->session_id,
2116
 
                                                   &ks->session_id_remote,
2117
 
                                                   false))
2118
 
                        goto error;
2119
 
                      
2120
 
                      CLEAR (ks->key_src);
2121
 
                    }
 
2992
                  ASSERT (0);
2122
2993
                }
2123
2994
 
2124
2995
              state_change = true;
2125
 
              msg (D_TLS_DEBUG_MED, "STATE S_GOT_KEY");
 
2996
              dmsg (D_TLS_DEBUG_MED, "STATE S_GOT_KEY");
2126
2997
              ks->state = S_GOT_KEY;
2127
2998
            }
2128
2999
 
2130
3001
          buf = &ks->plaintext_write_buf;
2131
3002
          if (buf->len)
2132
3003
            {
2133
 
              int status = key_state_write_plaintext (ks, buf);
 
3004
              int status = key_state_write_plaintext (multi, ks, buf);
2134
3005
              if (status == -1)
2135
3006
                {
2136
3007
                  msg (D_TLS_ERRORS,
2140
3011
              if (status == 1)
2141
3012
                {
2142
3013
                  state_change = true;
2143
 
                  msg (D_TLS_DEBUG, "Outgoing Plaintext -> TLS");
 
3014
                  dmsg (D_TLS_DEBUG, "Outgoing Plaintext -> TLS");
2144
3015
                }
2145
3016
            }
2146
3017
 
2147
3018
          /* Outgoing Ciphertext to reliable buffer */
2148
3019
          if (ks->state >= S_START)
2149
3020
            {
2150
 
              buf = reliable_get_buf_output_sequenced (&ks->send_reliable);
 
3021
              buf = reliable_get_buf_output_sequenced (ks->send_reliable);
2151
3022
              if (buf)
2152
3023
                {
2153
 
                  int status = key_state_read_ciphertext (ks, buf, PAYLOAD_SIZE_DYNAMIC (&multi->opt.frame));
 
3024
                  int status = key_state_read_ciphertext (multi, ks, buf, PAYLOAD_SIZE_DYNAMIC (&multi->opt.frame));
2154
3025
                  if (status == -1)
2155
3026
                    {
2156
3027
                      msg (D_TLS_ERRORS,
2159
3030
                    }
2160
3031
                  if (status == 1)
2161
3032
                    {
2162
 
                      reliable_mark_active_outgoing (&ks->send_reliable, buf, P_CONTROL_V1);
 
3033
                      reliable_mark_active_outgoing (ks->send_reliable, buf, P_CONTROL_V1);
2163
3034
                      INCR_GENERATED;
2164
3035
                      state_change = true;
2165
 
                      msg (D_TLS_DEBUG, "Outgoing Ciphertext -> Reliable");
 
3036
                      dmsg (D_TLS_DEBUG, "Outgoing Ciphertext -> Reliable");
2166
3037
                    }
2167
3038
                }
2168
3039
            }
2169
3040
        }
2170
 
      mutex_cycle (L_TLS); 
 
3041
      //mutex_cycle (multi->mutex);
2171
3042
    }
2172
3043
  while (state_change);
2173
3044
 
2174
 
  current = time (NULL);
 
3045
  update_time ();
2175
3046
 
2176
3047
#ifdef TLS_AGGREGATE_ACK
2177
3048
  /* Send 1 or more ACKs (each received control packet gets one ACK) */
2178
 
  if (!to_link->len && !reliable_ack_empty (&ks->rec_ack))
 
3049
  if (!to_link->len && !reliable_ack_empty (ks->rec_ack))
2179
3050
    {
2180
3051
      buf = &ks->ack_write_buf;
2181
3052
      ASSERT (buf_init (buf, FRAME_HEADROOM (&multi->opt.frame)));
2182
3053
      write_control_auth (session, ks, buf, to_link_addr, P_ACK_V1,
2183
 
                          RELIABLE_ACK_SIZE, false, current);
 
3054
                          RELIABLE_ACK_SIZE, false);
2184
3055
      *to_link = *buf;
2185
3056
      active = true;
2186
3057
      state_change = true;
2187
 
      msg (D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP");
 
3058
      dmsg (D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP");
2188
3059
    }
2189
3060
#endif
2190
3061
 
2191
3062
  /* When should we wake up again? */
2192
3063
  {
2193
 
    if (ks->state >= S_INITIAL && ks->state < S_NORMAL)
 
3064
    if (ks->state >= S_INITIAL)
2194
3065
      {
2195
3066
        compute_earliest_wakeup (wakeup,
2196
 
          reliable_send_timeout (&ks->send_reliable, current));
 
3067
          reliable_send_timeout (ks->send_reliable));
2197
3068
        
2198
3069
        if (ks->must_negotiate)
2199
 
          compute_earliest_wakeup (wakeup, ks->must_negotiate - current);
 
3070
          compute_earliest_wakeup (wakeup, ks->must_negotiate - now);
2200
3071
      }
2201
3072
 
2202
3073
    if (ks->established && session->opt->renegotiate_seconds)
2203
3074
      compute_earliest_wakeup (wakeup,
2204
 
        ks->established + session->opt->renegotiate_seconds - current);
 
3075
        ks->established + session->opt->renegotiate_seconds - now);
2205
3076
 
2206
3077
    /* prevent event-loop spinning by setting minimum wakeup of 1 second */
2207
3078
    if (*wakeup <= 0)
2213
3084
        active = true;
2214
3085
      }
2215
3086
 
2216
 
    msg (D_TLS_DEBUG, "tls_process: timeout set to %d", *wakeup);
 
3087
    dmsg (D_TLS_DEBUG, "TLS: tls_process: timeout set to %d", *wakeup);
2217
3088
 
 
3089
    gc_free (&gc);
2218
3090
    return active;
2219
3091
  }
2220
3092
 
2222
3094
  ks->state = S_ERROR;
2223
3095
  msg (D_TLS_ERRORS, "TLS Error: TLS handshake failed");
2224
3096
  INCR_ERROR;
 
3097
  gc_free (&gc);
2225
3098
  return false;
2226
3099
}
2227
3100
 
2229
3102
#undef ks_lame
2230
3103
 
2231
3104
/*
2232
 
 * Called at the top of the event loop in openvpn.c.
 
3105
 * Called by the top-level event loop.
2233
3106
 *
2234
3107
 * Basically decides if we should call tls_process for
2235
3108
 * the active or untrusted sessions.
2239
3112
tls_multi_process (struct tls_multi *multi,
2240
3113
                   struct buffer *to_link,
2241
3114
                   struct sockaddr_in *to_link_addr,
2242
 
                   struct link_socket *to_link_socket,
2243
 
                   interval_t *wakeup,
2244
 
                   time_t current)
 
3115
                   struct link_socket_info *to_link_socket_info,
 
3116
                   interval_t *wakeup)
2245
3117
{
 
3118
  struct gc_arena gc = gc_new ();
2246
3119
  int i;
2247
3120
  bool active = false;
 
3121
  bool error = false;
2248
3122
 
2249
 
  mutex_lock (L_TLS);
 
3123
  perf_push (PERF_TLS_MULTI_PROCESS);
2250
3124
 
2251
3125
  /*
2252
3126
   * Process each session object having state of S_INITIAL or greater,
2261
3135
 
2262
3136
      /* set initial remote address */
2263
3137
      if (i == TM_ACTIVE && ks->state == S_INITIAL &&
2264
 
          addr_defined (&to_link_socket->lsa->actual))
2265
 
        ks->remote_addr = to_link_socket->lsa->actual;
 
3138
          addr_defined (&to_link_socket_info->lsa->actual))
 
3139
        ks->remote_addr = to_link_socket_info->lsa->actual;
2266
3140
 
2267
 
      msg (D_TLS_DEBUG,
2268
 
           "tls_multi_process: i=%d state=%s, mysid=%s, stored-sid=%s, stored-ip=%s",
 
3141
      dmsg (D_TLS_DEBUG,
 
3142
           "TLS: tls_multi_process: i=%d state=%s, mysid=%s, stored-sid=%s, stored-ip=%s",
2269
3143
           i,
2270
3144
           state_name (ks->state),
2271
 
           session_id_print (&session->session_id),
2272
 
           session_id_print (&ks->session_id_remote),
2273
 
           print_sockaddr (&ks->remote_addr));
 
3145
           session_id_print (&session->session_id, &gc),
 
3146
           session_id_print (&ks->session_id_remote, &gc),
 
3147
           print_sockaddr (&ks->remote_addr, &gc));
2274
3148
 
2275
3149
      if (ks->state >= S_INITIAL && addr_defined (&ks->remote_addr))
2276
3150
        {
2277
 
          current = time (NULL);
 
3151
          update_time ();
2278
3152
 
2279
3153
          if (tls_process (multi, session, to_link, to_link_addr,
2280
 
                           to_link_socket, wakeup, current))
 
3154
                           to_link_socket_info, wakeup))
2281
3155
            active = true;
2282
3156
 
2283
3157
          /*
2284
3158
           * If tls_process hits an error:
2285
3159
           * (1) If the session has an unexpired lame duck key, preserve it.
2286
3160
           * (2) Reinitialize the session.
 
3161
           * (3) Increment soft error count
2287
3162
           */
2288
3163
          if (ks->state == S_ERROR)
2289
3164
            {
2290
 
              ++multi->n_errors;
2291
 
              if (i == TM_ACTIVE && ks_lame->state >= S_ACTIVE)
 
3165
              ++multi->n_soft_errors;
 
3166
 
 
3167
              if (i == TM_ACTIVE)
 
3168
                error = true;
 
3169
 
 
3170
              if (i == TM_ACTIVE
 
3171
                  && ks_lame->state >= S_ACTIVE
 
3172
                  && !multi->opt.single_session)
2292
3173
                move_session (multi, TM_LAME_DUCK, TM_ACTIVE, true);
2293
3174
              else
2294
3175
                reset_session (multi, session);
2295
3176
            }
2296
3177
        }
2297
 
      mutex_cycle (L_TLS);
 
3178
      //mutex_cycle (multi->mutex);
2298
3179
    }
2299
3180
 
2300
 
  current = time (NULL);
 
3181
  update_time ();
2301
3182
 
2302
3183
  /*
2303
3184
   * If lame duck session expires, kill it.
2304
3185
   */
2305
 
  if (lame_duck_must_die (&multi->session[TM_LAME_DUCK], wakeup, current)) {
2306
 
    tls_session_free(&multi->session[TM_LAME_DUCK], true);
 
3186
  if (lame_duck_must_die (&multi->session[TM_LAME_DUCK], wakeup)) {
 
3187
    tls_session_free (&multi->session[TM_LAME_DUCK], true);
2307
3188
    msg (D_TLS_DEBUG_LOW, "TLS: tls_multi_process: killed expiring key");
2308
3189
  }
2309
3190
 
2310
3191
  /*
2311
3192
   * If untrusted session achieves TLS authentication,
2312
3193
   * move it to active session, usurping any prior session.
 
3194
   *
 
3195
   * A semi-trusted session is one in which the certificate authentication
 
3196
   * succeeded (if cert verification is enabled) but the username/password
 
3197
   * verification failed.  A semi-trusted session can forward data on the
 
3198
   * TLS control channel but not on the tunnel channel.
2313
3199
   */
2314
3200
  if (DECRYPT_KEY_ENABLED (multi, &multi->session[TM_UNTRUSTED].key[KS_PRIMARY])) {
2315
3201
    move_session (multi, TM_ACTIVE, TM_UNTRUSTED, true);
2316
 
    msg (D_TLS_DEBUG_LOW, "TLS: tls_multi_process: untrusted session promoted to trusted");
2317
 
  }
2318
 
 
2319
 
  mutex_unlock (L_TLS);
2320
 
 
 
3202
    msg (D_TLS_DEBUG_LOW, "TLS: tls_multi_process: untrusted session promoted to %strusted",
 
3203
         tls_authenticated (multi) ? "" : "semi-");
 
3204
  }
 
3205
 
 
3206
  /*
 
3207
   * A hard error means that TM_ACTIVE hit an S_ERROR state and that no
 
3208
   * other key state objects are S_ACTIVE or higher.
 
3209
   */
 
3210
  if (error)
 
3211
    {
 
3212
      for (i = 0; i < (int) SIZE (multi->key_scan); ++i)
 
3213
        {
 
3214
          if (multi->key_scan[i]->state >= S_ACTIVE)
 
3215
            goto nohard;
 
3216
        }
 
3217
      ++multi->n_hard_errors;
 
3218
    }
 
3219
 nohard:
 
3220
 
 
3221
#ifdef ENABLE_DEBUG
 
3222
  /* DEBUGGING -- flood peer with repeating connection attempts */
 
3223
  {
 
3224
    const int throw_level = GREMLIN_CONNECTION_FLOOD_LEVEL (multi->opt.gremlin);
 
3225
    if (throw_level)
 
3226
      {
 
3227
        for (i = 0; i < (int) SIZE (multi->key_scan); ++i)
 
3228
          {
 
3229
            if (multi->key_scan[i]->state >= throw_level)
 
3230
              {
 
3231
                ++multi->n_hard_errors;
 
3232
                ++multi->n_soft_errors;
 
3233
              }
 
3234
          }
 
3235
      }
 
3236
  }
 
3237
#endif
 
3238
 
 
3239
  perf_pop ();
 
3240
  gc_free (&gc);
2321
3241
  return active;
2322
3242
}
2323
3243
 
2324
3244
/*
2325
 
 * When OpenVPN is built in pthread-mode, thread_func
2326
 
 * will periodically call tls_multi_process.
2327
 
 */
2328
 
 
2329
 
#ifdef USE_PTHREAD
2330
 
 
2331
 
/*
2332
 
 * Main thread <-> TLS thread communication.
2333
 
 * Errors are fatal if they are of these types.
2334
 
 */
2335
 
static inline bool
2336
 
local_sock_fatal (int status)
2337
 
{
2338
 
  return status < 0 && (errno == ENOTCONN || errno == ECONNREFUSED);
2339
 
}
2340
 
 
2341
 
/*
2342
 
 * This routine is the TLS work thread.
2343
 
 */
2344
 
static void *
2345
 
thread_func (void *arg)
2346
 
{
2347
 
  const int gc_level = gc_new_level ();
2348
 
  const struct thread_parms *parm = (struct thread_parms*) arg;
2349
 
  struct buffer buf;
2350
 
 
2351
 
#if 0
2352
 
  /*
2353
 
   * Under Linux, Posix threads appear to inherit mlockall state
2354
 
   * from parent.  This is good news, since mlockall will fail
2355
 
   * if we restart after having downgraded privileges with
2356
 
   * --user or group.
2357
 
   */
2358
 
  if (parm->mlock) /* should we disable paging? */
2359
 
    do_mlockall (true);  
2360
 
#endif
2361
 
 
2362
 
  /* change thread priority if requested */
2363
 
  set_nice (parm->nice);
2364
 
 
2365
 
  /* buffer used to receive data from SSL/TLS */
2366
 
  CLEAR (buf);
2367
 
 
2368
 
  /* event loop */
2369
 
  while (true)
2370
 
    {
2371
 
      int stat, fatal;
2372
 
      struct tt_ret ret;
2373
 
      fd_set reads, writes;
2374
 
      struct timeval tv;
2375
 
 
2376
 
      time_t current = time (NULL);
2377
 
      interval_t wakeup = TLS_MULTI_REFRESH;
2378
 
 
2379
 
      msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: thread event loop");
2380
 
 
2381
 
      CLEAR (ret);
2382
 
  
2383
 
      /* do a quick garbage collect */
2384
 
      gc_collect (gc_level);
2385
 
 
2386
 
      /* do one SSL/TLS process pass */
2387
 
      tls_multi_process (parm->multi, &buf, &ret.to_link_addr,
2388
 
                         parm->link_socket, &wakeup, current);
2389
 
 
2390
 
      /* determine events to wait for */
2391
 
      FD_ZERO (&writes);
2392
 
      FD_ZERO (&reads);
2393
 
 
2394
 
      /* did tls_multi_process give us a buffer to forward
2395
 
         to foreground thread, on this or previous event
2396
 
         loop pass? */
2397
 
      if (buf.len)
2398
 
        FD_SET (parm->sd[TLS_THREAD_WORKER], &writes);
2399
 
 
2400
 
      /* always wait for incoming commands from foreground thread */
2401
 
      FD_SET (parm->sd[TLS_THREAD_WORKER], &reads);
2402
 
 
2403
 
      /* set select timeout */
2404
 
      tv.tv_sec = wakeup;
2405
 
      tv.tv_usec = 0;
2406
 
 
2407
 
      msg (D_SELECT, "THREAD SELECT %s|%s %d/%d",
2408
 
           FD_ISSET (parm->sd[TLS_THREAD_WORKER], &reads) ?   "FR" : "fr", 
2409
 
           FD_ISSET (parm->sd[TLS_THREAD_WORKER], &writes) ?  "FW" : "fw", 
2410
 
           (int)tv.tv_sec,
2411
 
           (int)tv.tv_usec);
2412
 
 
2413
 
      stat = select (parm->sd[TLS_THREAD_WORKER] + 1, &reads, &writes, NULL, &tv);
2414
 
      check_status (stat, "thread select", NULL, NULL);
2415
 
      if (!stat) /* timeout? */
2416
 
        continue;
2417
 
 
2418
 
      /* send buffer to foreground */
2419
 
      if (FD_ISSET (parm->sd[TLS_THREAD_WORKER], &writes))
2420
 
        {
2421
 
          ASSERT (buf.len);
2422
 
 
2423
 
          /* make a fresh copy of buf in ret, and release buf */
2424
 
          ret.to_link = clone_buf (&buf);
2425
 
          CLEAR (buf);
2426
 
 
2427
 
          /* send buffer to foreground where it will be forwarded to remote */
2428
 
          stat = write (parm->sd[TLS_THREAD_WORKER], &ret, sizeof (ret));
2429
 
          fatal = local_sock_fatal (stat);
2430
 
          check_status (stat, "write to foreground", NULL, NULL);
2431
 
          if (stat < 0)
2432
 
            free_buf (&ret.to_link);
2433
 
          if (fatal)
2434
 
            goto exit;
2435
 
        }
2436
 
 
2437
 
      /* get command from foreground */
2438
 
      if (FD_ISSET (parm->sd[TLS_THREAD_WORKER], &reads))
2439
 
        {
2440
 
          do {
2441
 
            struct tt_cmd tc;
2442
 
 
2443
 
            stat = read (parm->sd[TLS_THREAD_WORKER], &tc, sizeof (tc));
2444
 
            fatal = local_sock_fatal (stat);
2445
 
            check_status (stat, "read from foreground", NULL, NULL);
2446
 
            if (stat == sizeof (tc))
2447
 
              {
2448
 
                if (tc.cmd == TTCMD_PROCESS)
2449
 
                  {
2450
 
                    msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: TTCMD_PROCESS");
2451
 
                  }
2452
 
                else if (tc.cmd == TTCMD_EXIT)
2453
 
                  {
2454
 
                    msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: TTCMD_EXIT");
2455
 
                    goto exit;
2456
 
                  }
2457
 
                else
2458
 
                  msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: Unknown TTCMD code: %d", tc.cmd);
2459
 
              }
2460
 
            else if (fatal)
2461
 
              goto exit;
2462
 
          } while (stat > 0);
2463
 
        }
2464
 
    }
2465
 
 
2466
 
 exit:
2467
 
  msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: exiting");
2468
 
  close (parm->sd[TLS_THREAD_WORKER]);
2469
 
  gc_free_level (gc_level);
2470
 
  return NULL;
2471
 
}
2472
 
 
2473
 
/*
2474
 
 * All tls_thread functions below this point operate in the context of the main
2475
 
 * thread.
2476
 
 */
2477
 
 
2478
 
/*
2479
 
 * Send a command to TLS thread.
2480
 
 */
2481
 
static int
2482
 
tls_thread_send_command (struct thread_parms *state, int cmd, bool wait_if_necessary)
2483
 
{
2484
 
  struct tt_cmd tc;
2485
 
  int stat;
2486
 
  bool fatal;
2487
 
 
2488
 
  tc.cmd = cmd;
2489
 
  while (true)
2490
 
    {
2491
 
      stat = write (state->sd[TLS_THREAD_MAIN], &tc, sizeof (tc));
2492
 
      if (wait_if_necessary && stat < 0 && errno == EAGAIN)
2493
 
        {
2494
 
          msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: tls_thread_send_command WAIT");
2495
 
          sleep (1);
2496
 
        }
2497
 
      else
2498
 
        break;
2499
 
    }
2500
 
  fatal = local_sock_fatal (stat);
2501
 
  check_status (stat, "write command to tls thread", NULL, NULL);
2502
 
  if (stat == sizeof (tc))
2503
 
    return 1;
2504
 
  else if (fatal)
2505
 
    return -1;
2506
 
  else
2507
 
    return 0;
2508
 
}
2509
 
 
2510
 
/*
2511
 
 * Create the TLS thread.
2512
 
 */
2513
 
void
2514
 
tls_thread_create (struct thread_parms *state,
2515
 
                   struct tls_multi *multi,
2516
 
                   struct link_socket *link_socket,
2517
 
                   int nice, bool mlock)
2518
 
{
2519
 
  CLEAR (*state);
2520
 
  state->multi = multi;
2521
 
  state->link_socket = link_socket;
2522
 
  state->nice = nice;
2523
 
  state->mlock = mlock;
2524
 
 
2525
 
  /*
2526
 
   * Make a socket for foreground and background threads
2527
 
   * to communicate.  The background thread will set its
2528
 
   * end to blocking, while the foreground will set its
2529
 
   * end to non-blocking.
2530
 
   */
2531
 
  if (socketpair (PF_UNIX, SOCK_DGRAM, 0, state->sd) == -1)
2532
 
    msg (M_ERR, "socketpair call failed");
2533
 
  set_nonblock (state->sd[TLS_THREAD_MAIN]);
2534
 
  set_nonblock (state->sd[TLS_THREAD_WORKER]);
2535
 
  set_cloexec (state->sd[TLS_THREAD_MAIN]);
2536
 
  set_cloexec (state->sd[TLS_THREAD_WORKER]);
2537
 
  work_thread_create (thread_func, (void*)state);
2538
 
}
2539
 
 
2540
 
/*
2541
 
 * Send a command to TLS thread telling it to cycle
2542
 
 * through tls_multi_process() as long as there
2543
 
 * is data to process.
2544
 
 */
2545
 
int
2546
 
tls_thread_process (struct thread_parms *state)
2547
 
{
2548
 
  return tls_thread_send_command (state, TTCMD_PROCESS, false);
2549
 
}
2550
 
 
2551
 
/* free any unprocessed buffers sent from background to foreground */
2552
 
static void
2553
 
tls_thread_flush (struct thread_parms *state)
2554
 
{
2555
 
  struct tt_ret ttr;
2556
 
  while (tls_thread_rec_buf (state, &ttr, false) == 1)
2557
 
    {
2558
 
      free_buf (&ttr.to_link);
2559
 
    }
2560
 
}
2561
 
 
2562
 
/*
2563
 
 * Close the TLS thread
2564
 
 */
2565
 
void
2566
 
tls_thread_close (struct thread_parms *state)
2567
 
{
2568
 
  tls_thread_send_command (state, TTCMD_EXIT, true);
2569
 
  work_thread_join ();
2570
 
  tls_thread_flush (state);
2571
 
  close (state->sd[TLS_THREAD_MAIN]);
2572
 
}
2573
 
 
2574
 
/*
2575
 
 * Receive an object from the TLS thread which
2576
 
 * normally contains a buffer to be sent to
2577
 
 * the remote peer over the TCP/UDP port.
2578
 
 *
2579
 
 * Return:
2580
 
 *  1 if ok
2581
 
 *  0 if non-fatal error
2582
 
 *  -1 if fatal error
2583
 
 */
2584
 
int
2585
 
tls_thread_rec_buf (struct thread_parms *state, struct tt_ret* ttr, bool do_check_status)
2586
 
{
2587
 
  int stat;
2588
 
  bool fatal;
2589
 
 
2590
 
  stat = read (state->sd[TLS_THREAD_MAIN], ttr, sizeof (*ttr));
2591
 
  fatal = local_sock_fatal (stat);
2592
 
  if (do_check_status)
2593
 
    check_status (stat, "read buffer from tls thread", NULL, NULL);
2594
 
  if (stat == sizeof (*ttr))
2595
 
    return 1;
2596
 
  else if (fatal)
2597
 
    return -1;
2598
 
  else
2599
 
    return 0;
2600
 
}
2601
 
 
2602
 
#endif
2603
 
 
2604
 
/*
2605
3245
 * Pre and post-process the encryption & decryption buffers in order
2606
3246
 * to implement a multiplexed TLS channel over the TCP/UDP port.
2607
3247
 */
2635
3275
tls_pre_decrypt (struct tls_multi *multi,
2636
3276
                 struct sockaddr_in *from,
2637
3277
                 struct buffer *buf,
2638
 
                 struct crypto_options *opt,
2639
 
                 time_t current)
 
3278
                 struct crypto_options *opt)
2640
3279
{
 
3280
  struct gc_arena gc = gc_new ();
2641
3281
  bool ret = false;
2642
3282
 
2643
3283
  if (buf->len > 0)
2658
3298
          for (i = 0; i < KEY_SCAN_SIZE; ++i)
2659
3299
            {
2660
3300
              struct key_state *ks = multi->key_scan[i];
 
3301
 
 
3302
              /*
 
3303
               * This is the basic test of TLS state compatibility between a local OpenVPN 
 
3304
               * instance and its remote peer.
 
3305
               *
 
3306
               * If the test fails, it tells us that we are getting a packet from a source
 
3307
               * which claims reference to a prior negotiated TLS session, but the local
 
3308
               * OpenVPN instance has no memory of such a negotiation.
 
3309
               *
 
3310
               * It almost always occurs on UDP sessions when the passive side of the
 
3311
               * connection is restarted without the active side restarting as well (the 
 
3312
               * passive side is the server which only listens for the connections, the 
 
3313
               * active side is the client which initiates connections).
 
3314
               */
2661
3315
              if (DECRYPT_KEY_ENABLED (multi, ks)
2662
3316
                  && key_id == ks->key_id
 
3317
                  && ks->authenticated
2663
3318
                  && addr_port_match(from, &ks->remote_addr))
2664
3319
                {
2665
3320
                  /* return appropriate data channel decrypt key in opt */
2666
3321
                  opt->key_ctx_bi = &ks->key;
2667
3322
                  opt->packet_id = multi->opt.replay ? &ks->packet_id : NULL;
2668
3323
                  opt->pid_persist = NULL;
2669
 
                  opt->packet_id_long_form = multi->opt.packet_id_long_form;
 
3324
                  opt->flags &= multi->opt.crypto_flags_and;
 
3325
                  opt->flags |= multi->opt.crypto_flags_or;
2670
3326
                  ASSERT (buf_advance (buf, 1));
2671
3327
                  ++ks->n_packets;
2672
3328
                  ks->n_bytes += buf->len;
2673
 
                  msg (D_TLS_DEBUG,
2674
 
                       "tls_pre_decrypt: data channel, key_id=%d, IP=%s",
2675
 
                       key_id, print_sockaddr (from));
 
3329
                  dmsg (D_TLS_DEBUG,
 
3330
                       "TLS: data channel, key_id=%d, IP=%s",
 
3331
                       key_id, print_sockaddr (from, &gc));
 
3332
                  gc_free (&gc);
2676
3333
                  return ret;
2677
3334
                }
 
3335
#if 0 /* keys out of sync? */
 
3336
              else
 
3337
                {
 
3338
                  dmsg (D_TLS_DEBUG, "TLS_PRE_DECRYPT: [%d] dken=%d rkid=%d lkid=%d auth=%d match=%d",
 
3339
                       i,
 
3340
                       DECRYPT_KEY_ENABLED (multi, ks),
 
3341
                       key_id,
 
3342
                       ks->key_id,
 
3343
                       ks->authenticated,
 
3344
                       addr_port_match (from, &ks->remote_addr));
 
3345
                }
 
3346
#endif
2678
3347
            }
2679
3348
 
2680
3349
          msg (D_TLS_ERRORS,
2681
 
               "TLS Error: Unknown data channel key ID or IP address received from %s: %d (see FAQ for more info on this error)",
2682
 
               print_sockaddr (from), key_id);
 
3350
               "TLS Error: local/remote TLS keys are out of sync: %s [%d]",
 
3351
               print_sockaddr (from, &gc), key_id);
2683
3352
          goto error;
2684
3353
        }
2685
3354
      else                        /* control channel packet */
2693
3362
            {
2694
3363
              msg (D_TLS_ERRORS,
2695
3364
                   "TLS Error: unknown opcode received from %s op=%d",
2696
 
                   print_sockaddr (from), op);
 
3365
                   print_sockaddr (from, &gc), op);
2697
3366
              goto error;
2698
3367
            }
2699
3368
 
2701
3370
          if (is_hard_reset (op, 0))
2702
3371
            {
2703
3372
              /* verify client -> server or server -> client connection */
2704
 
              if (((op == P_CONTROL_HARD_RESET_CLIENT_V1 || op == P_CONTROL_HARD_RESET_CLIENT_V2) && !multi->opt.server) ||
2705
 
                  ((op == P_CONTROL_HARD_RESET_SERVER_V1 || op == P_CONTROL_HARD_RESET_SERVER_V2) && multi->opt.server))
 
3373
              if (((op == P_CONTROL_HARD_RESET_CLIENT_V1
 
3374
                    || op == P_CONTROL_HARD_RESET_CLIENT_V2) && !multi->opt.server)
 
3375
                  || ((op == P_CONTROL_HARD_RESET_SERVER_V1
 
3376
                       || op == P_CONTROL_HARD_RESET_SERVER_V2) && multi->opt.server))
2706
3377
                {
2707
3378
                  msg (D_TLS_ERRORS,
2708
3379
                       "TLS Error: client->client or server->server connection attempted from %s",
2709
 
                       print_sockaddr (from));
 
3380
                       print_sockaddr (from, &gc));
2710
3381
                  goto error;
2711
3382
                }
2712
3383
            }
2714
3385
          /*
2715
3386
           * Authenticate Packet
2716
3387
           */
2717
 
          msg (D_TLS_DEBUG, "tls_pre_decrypt: control channel, op=%s, IP=%s",
2718
 
               packet_opcode_name (op), print_sockaddr (from));
 
3388
          dmsg (D_TLS_DEBUG, "TLS: control channel, op=%s, IP=%s",
 
3389
               packet_opcode_name (op), print_sockaddr (from, &gc));
2719
3390
 
2720
3391
          /* get remote session-id */
2721
3392
          {
2725
3396
              {
2726
3397
                msg (D_TLS_ERRORS,
2727
3398
                     "TLS Error: session-id not found in packet from %s",
2728
 
                     print_sockaddr (from));
 
3399
                     print_sockaddr (from, &gc));
2729
3400
                goto error;
2730
3401
              }
2731
3402
          }
2736
3407
              struct tls_session *session = &multi->session[i];
2737
3408
              struct key_state *ks = &session->key[KS_PRIMARY];
2738
3409
 
2739
 
              msg (D_TLS_DEBUG,
2740
 
                   "tls_pre_decrypt: initial packet test, i=%d state=%s, mysid=%s, rec-sid=%s, rec-ip=%s, stored-sid=%s, stored-ip=%s",
 
3410
              dmsg (D_TLS_DEBUG,
 
3411
                   "TLS: initial packet test, i=%d state=%s, mysid=%s, rec-sid=%s, rec-ip=%s, stored-sid=%s, stored-ip=%s",
2741
3412
                   i,
2742
3413
                   state_name (ks->state),
2743
 
                   session_id_print (&session->session_id),
2744
 
                   session_id_print (&sid),
2745
 
                   print_sockaddr (from),
2746
 
                   session_id_print (&ks->session_id_remote),
2747
 
                   print_sockaddr (&ks->remote_addr));
 
3414
                   session_id_print (&session->session_id, &gc),
 
3415
                   session_id_print (&sid, &gc),
 
3416
                   print_sockaddr (from, &gc),
 
3417
                   session_id_print (&ks->session_id_remote, &gc),
 
3418
                   print_sockaddr (&ks->remote_addr, &gc));
2748
3419
 
2749
3420
              if (session_id_equal (&ks->session_id_remote, &sid))
2750
3421
                /* found a match */
2752
3423
                  if (i == TM_LAME_DUCK) {
2753
3424
                    msg (D_TLS_ERRORS,
2754
3425
                         "TLS ERROR: received control packet with stale session-id=%s",
2755
 
                         session_id_print (&sid));
 
3426
                         session_id_print (&sid, &gc));
2756
3427
                    goto error;
2757
3428
                  }
2758
 
                  msg (D_TLS_DEBUG,
2759
 
                       "tls_pre_decrypt: found match, session[%d], sid=%s",
2760
 
                       i, session_id_print (&sid));
 
3429
                  dmsg (D_TLS_DEBUG,
 
3430
                       "TLS: found match, session[%d], sid=%s",
 
3431
                       i, session_id_print (&sid, &gc));
2761
3432
                  break;
2762
3433
                }
2763
3434
            }
2764
3435
 
2765
3436
          /*
2766
 
           * check if this is the first response from a host to which
2767
 
           * we sent an initial packet
 
3437
           * Initial packet received.
2768
3438
           */
2769
3439
 
2770
3440
          if (i == TM_SIZE && is_hard_reset (op, 0))
2774
3444
 
2775
3445
              if (!is_hard_reset (op, multi->opt.key_method))
2776
3446
                {
2777
 
                  msg (D_TLS_ERRORS, "TLS ERROR: first response local/remote key_method mismatch, local key_method=%d, op=%s",
 
3447
                  msg (D_TLS_ERRORS, "TLS ERROR: initial packet local/remote key_method mismatch, local key_method=%d, op=%s",
2778
3448
                       multi->opt.key_method,
2779
3449
                       packet_opcode_name (op));
2780
3450
                  goto error;
2781
3451
                }
2782
3452
 
 
3453
              /*
 
3454
               * If we have no session currently in progress, the initial packet will
 
3455
               * open a new session in TM_ACTIVE rather than TM_UNTRUSTED.
 
3456
               */
2783
3457
              if (!session_id_defined (&ks->session_id_remote))
2784
3458
                {
 
3459
                  if (multi->opt.single_session && multi->n_sessions)
 
3460
                    {
 
3461
                      msg (D_TLS_ERRORS,
 
3462
                           "TLS Error: Cannot accept new session request from %s due to --single-session [1]",
 
3463
                           print_sockaddr (from, &gc));
 
3464
                      goto error;
 
3465
                    }
 
3466
 
 
3467
#ifdef ENABLE_MANAGEMENT
 
3468
                  if (management)
 
3469
                    {
 
3470
                      management_set_state (management,
 
3471
                                            OPENVPN_STATE_AUTH,
 
3472
                                            NULL,
 
3473
                                            0);
 
3474
                    }
 
3475
#endif
 
3476
 
2785
3477
                  msg (D_TLS_DEBUG_LOW,
2786
 
                       "TLS: tls_pre_decrypt: first response to initial packet from %s, sid=%s",
2787
 
                       print_sockaddr (from),
2788
 
                       session_id_print (&sid));
 
3478
                       "TLS: Initial packet from %s, sid=%s",
 
3479
                       print_sockaddr (from, &gc),
 
3480
                       session_id_print (&sid, &gc));
 
3481
 
2789
3482
                  do_burst = true;
2790
3483
                  new_link = true;
2791
3484
                  i = TM_ACTIVE;
2792
 
                  setenv_sockaddr ("untrusted", from);
 
3485
                  session->untrusted_sockaddr = *from;
2793
3486
                }
2794
3487
            }
2795
3488
 
2801
3494
               */
2802
3495
              struct tls_session *session = &multi->session[TM_UNTRUSTED];
2803
3496
 
 
3497
              /*
 
3498
               * If --single-session, don't allow any hard-reset connection request
 
3499
               * unless it the the first packet of the session.
 
3500
               */
 
3501
              if (multi->opt.single_session)
 
3502
                {
 
3503
                  msg (D_TLS_ERRORS,
 
3504
                       "TLS Error: Cannot accept new session request from %s due to --single-session [2]",
 
3505
                       print_sockaddr (from, &gc));
 
3506
                  goto error;
 
3507
                }
 
3508
              
2804
3509
              if (!is_hard_reset (op, multi->opt.key_method))
2805
3510
                {
2806
3511
                  msg (D_TLS_ERRORS, "TLS ERROR: new session local/remote key_method mismatch, local key_method=%d, op=%s",
2809
3514
                  goto error;
2810
3515
                }
2811
3516
 
2812
 
              if (!read_control_auth (buf, &session->tls_auth, from, current))
 
3517
              if (!read_control_auth (buf, &session->tls_auth, from))
2813
3518
                goto error;
2814
3519
 
2815
3520
              /*
2819
3524
               * Without --tls-auth, we leave authentication entirely up to TLS.
2820
3525
               */
2821
3526
              msg (D_TLS_DEBUG_LOW,
2822
 
                   "TLS: tls_pre_decrypt: new session incoming connection from %s",
2823
 
                   print_sockaddr (from));
 
3527
                   "TLS: new session incoming connection from %s",
 
3528
                   print_sockaddr (from, &gc));
2824
3529
 
2825
3530
              new_link = true;
2826
3531
              i = TM_UNTRUSTED;
2827
 
              setenv_sockaddr ("untrusted", from);
 
3532
              session->untrusted_sockaddr = *from;
2828
3533
            }
2829
3534
          else
2830
3535
            {
2838
3543
                {
2839
3544
                  msg (D_TLS_ERRORS,
2840
3545
                       "TLS Error: Unroutable control packet received from %s (si=%d op=%s)",
2841
 
                       print_sockaddr (from),
 
3546
                       print_sockaddr (from, &gc),
2842
3547
                       i,
2843
3548
                       packet_opcode_name (op));
2844
3549
                  goto error;
2850
3555
              if (!new_link && !addr_port_match (&ks->remote_addr, from))
2851
3556
                {
2852
3557
                  msg (D_TLS_ERRORS, "TLS Error: Received control packet from unexpected IP addr: %s",
2853
 
                      print_sockaddr (from));
 
3558
                      print_sockaddr (from, &gc));
2854
3559
                  goto error;
2855
3560
                }
2856
3561
 
2860
3565
              if (op == P_CONTROL_SOFT_RESET_V1
2861
3566
                  && DECRYPT_KEY_ENABLED (multi, ks))
2862
3567
                {
2863
 
                  if (!read_control_auth (buf, &session->tls_auth, from, current))
 
3568
                  if (!read_control_auth (buf, &session->tls_auth, from))
2864
3569
                    goto error;
2865
3570
 
2866
 
                  key_state_soft_reset (session, current);
 
3571
                  key_state_soft_reset (session);
2867
3572
 
2868
 
                  msg (D_TLS_DEBUG,
2869
 
                       "tls_pre_decrypt: received P_CONTROL_SOFT_RESET_V1 s=%d sid=%s",
2870
 
                       i, session_id_print (&sid));
 
3573
                  dmsg (D_TLS_DEBUG,
 
3574
                       "TLS: received P_CONTROL_SOFT_RESET_V1 s=%d sid=%s",
 
3575
                       i, session_id_print (&sid, &gc));
2871
3576
                }
2872
3577
              else
2873
3578
                {
2877
3582
                  if (op == P_CONTROL_SOFT_RESET_V1)
2878
3583
                    do_burst = true;
2879
3584
 
2880
 
                  if (!read_control_auth (buf, &session->tls_auth, from, current))
 
3585
                  if (!read_control_auth (buf, &session->tls_auth, from))
2881
3586
                    goto error;
2882
3587
 
2883
 
                  msg (D_TLS_DEBUG,
2884
 
                       "tls_pre_decrypt: received control channel packet s#=%d sid=%s",
2885
 
                       i, session_id_print (&sid));
 
3588
                  dmsg (D_TLS_DEBUG,
 
3589
                       "TLS: received control channel packet s#=%d sid=%s",
 
3590
                       i, session_id_print (&sid, &gc));
2886
3591
                }
2887
3592
            }
2888
3593
          
2889
3594
          /*
2890
 
           * If --single-session, don't allow more than one session.
2891
 
           */
2892
 
          if (multi->opt.single_session && new_link && multi->n_sessions)
2893
 
            {
2894
 
              msg (D_TLS_ERRORS,
2895
 
                   "TLS Error: Cannot accept new session request from %s due to --single-session",
2896
 
                   print_sockaddr (from));
2897
 
              goto error;
2898
 
            }
2899
 
 
2900
 
          /*
2901
3595
           * We have an authenticated packet (if --tls-auth was set).
2902
3596
           * Now pass to our reliability level which deals with
2903
3597
           * packet acknowledgements, retransmits, sequencing, etc.
2927
3621
              {
2928
3622
                msg (D_TLS_ERRORS,
2929
3623
                     "TLS Error: Existing session control channel packet from unknown IP address: %s",
2930
 
                     print_sockaddr (from));
 
3624
                     print_sockaddr (from, &gc));
2931
3625
                goto error;
2932
3626
              }
2933
3627
 
2938
3632
             */
2939
3633
            if (do_burst && !session->burst)
2940
3634
              {
2941
 
                reliable_schedule_now (&ks->send_reliable, current);
 
3635
                reliable_schedule_now (ks->send_reliable);
2942
3636
                session->burst = true;
2943
3637
              }
2944
3638
 
2947
3641
              {
2948
3642
                msg (D_TLS_ERRORS,
2949
3643
                     "TLS ERROR: local/remote key IDs out of sync (%d/%d) ID: %s",
2950
 
                     ks->key_id, key_id, print_key_id (multi));
 
3644
                     ks->key_id, key_id, print_key_id (multi, &gc));
2951
3645
                goto error;
2952
3646
              }
2953
3647
              
2966
3660
                       "TLS Error: reading acknowledgement record from packet");
2967
3661
                  goto error;
2968
3662
                }
2969
 
              reliable_send_purge (&ks->send_reliable, &send_ack);
 
3663
              reliable_send_purge (ks->send_reliable, &send_ack);
2970
3664
            }
2971
3665
 
2972
 
            if (op != P_ACK_V1 && reliable_can_get (&ks->rec_reliable))
 
3666
            if (op != P_ACK_V1 && reliable_can_get (ks->rec_reliable))
2973
3667
              {
2974
3668
                packet_id_type id;
2975
3669
 
2977
3671
                if (reliable_ack_read_packet_id (buf, &id))
2978
3672
                  {
2979
3673
                    /* Avoid deadlock by rejecting packet that would de-sequentialize receive buffer */
2980
 
                    if (reliable_wont_break_sequentiality (&ks->rec_reliable, id))
 
3674
                    if (reliable_wont_break_sequentiality (ks->rec_reliable, id))
2981
3675
                      {
2982
 
                        if (reliable_not_replay (&ks->rec_reliable, id))
 
3676
                        if (reliable_not_replay (ks->rec_reliable, id))
2983
3677
                          {
2984
3678
                            /* Save incoming ciphertext packet to reliable buffer */
2985
 
                            struct buffer *in = reliable_get_buf (&ks->rec_reliable);
 
3679
                            struct buffer *in = reliable_get_buf (ks->rec_reliable);
2986
3680
                            ASSERT (in);
2987
3681
                            ASSERT (buf_copy (in, buf));
2988
 
                            reliable_mark_active_incoming (&ks->rec_reliable, in, id, op);
 
3682
                            reliable_mark_active_incoming (ks->rec_reliable, in, id, op);
2989
3683
                          }
2990
3684
 
2991
3685
                        /* Process outgoing acknowledgment for packet just received, even if it's a replay */
2992
 
                        reliable_ack_acknowledge_packet_id (&ks->rec_ack, id);
 
3686
                        reliable_ack_acknowledge_packet_id (ks->rec_ack, id);
2993
3687
                      }
2994
3688
                  }
2995
3689
              }
3002
3696
  opt->key_ctx_bi = NULL;
3003
3697
  opt->packet_id = NULL;
3004
3698
  opt->pid_persist = NULL;
3005
 
  opt->packet_id_long_form = false;
 
3699
  opt->flags &= multi->opt.crypto_flags_and;
 
3700
  gc_free (&gc);
3006
3701
  return ret;
3007
3702
 
3008
3703
 error:
3009
 
  ++multi->n_errors;
 
3704
  ++multi->n_soft_errors;
3010
3705
  goto done;
3011
3706
}
3012
3707
 
 
3708
/*
 
3709
 * This function is similar to tls_pre_decrypt, except it is called
 
3710
 * when we are in server mode and receive an initial incoming
 
3711
 * packet.  Note that we don't modify
 
3712
 * any state in our parameter objects.  The purpose is solely to
 
3713
 * determine whether we should generate a client instance
 
3714
 * object, in which case true is returned.
 
3715
 *
 
3716
 * This function is essentially the first-line HMAC firewall
 
3717
 * on the UDP port listener in --mode server mode.
 
3718
 */
 
3719
bool
 
3720
tls_pre_decrypt_lite (const struct tls_auth_standalone *tas,
 
3721
                      const struct sockaddr_in *from,
 
3722
                      const struct buffer *buf)
 
3723
{
 
3724
  struct gc_arena gc = gc_new ();
 
3725
  bool ret = false;
 
3726
 
 
3727
  if (buf->len > 0)
 
3728
    {
 
3729
      int op;
 
3730
      int key_id;
 
3731
 
 
3732
      /* get opcode and key ID */
 
3733
      {
 
3734
        uint8_t c = *BPTR (buf);
 
3735
        op = c >> P_OPCODE_SHIFT;
 
3736
        key_id = c & P_KEY_ID_MASK;
 
3737
      }
 
3738
 
 
3739
      /* this packet is from an as-yet untrusted source, so
 
3740
         scrutinize carefully */
 
3741
 
 
3742
      if (op != P_CONTROL_HARD_RESET_CLIENT_V2)
 
3743
        {
 
3744
          /*
 
3745
           * This can occur due to bogus data or DoS packets.
 
3746
           */
 
3747
          dmsg (D_TLS_STATE_ERRORS,
 
3748
               "TLS State Error: No TLS state for client %s, opcode=%d",
 
3749
               print_sockaddr (from, &gc),
 
3750
               op);
 
3751
          goto error;
 
3752
        }
 
3753
 
 
3754
      if (key_id != 0)
 
3755
        {
 
3756
          dmsg (D_TLS_STATE_ERRORS,
 
3757
               "TLS State Error: Unknown key ID (%d) received from %s -- 0 was expected",
 
3758
               key_id,
 
3759
               print_sockaddr (from, &gc));
 
3760
          goto error;
 
3761
        }
 
3762
 
 
3763
      if (buf->len > EXPANDED_SIZE_DYNAMIC (&tas->frame))
 
3764
        {
 
3765
          dmsg (D_TLS_STATE_ERRORS,
 
3766
               "TLS State Error: Large packet (size %d) received from %s -- a packet no larger than %d bytes was expected",
 
3767
               buf->len,
 
3768
               print_sockaddr (from, &gc),
 
3769
               EXPANDED_SIZE_DYNAMIC (&tas->frame));
 
3770
          goto error;
 
3771
        }
 
3772
 
 
3773
      {
 
3774
        struct buffer newbuf = clone_buf (buf);
 
3775
        struct crypto_options co = tas->tls_auth_options;
 
3776
        bool status;
 
3777
 
 
3778
        /*
 
3779
         * We are in read-only mode at this point with respect to TLS
 
3780
         * control channel state.  After we build a new client instance
 
3781
         * object, we will process this session-initiating packet for real.
 
3782
         */
 
3783
        co.flags |= CO_IGNORE_PACKET_ID;
 
3784
 
 
3785
        /* HMAC test, if --tls-auth was specified */
 
3786
        status = read_control_auth (&newbuf, &co, from);
 
3787
        free_buf (&newbuf);
 
3788
        if (!status)
 
3789
          goto error;
 
3790
 
 
3791
        /*
 
3792
         * At this point, if --tls-auth is being used, we know that
 
3793
         * the packet has passed the HMAC test, but we don't know if
 
3794
         * it is a replay yet.  We will attempt to defeat replays
 
3795
         * by not advancing to the S_START state until we
 
3796
         * receive an ACK from our first reply to the client
 
3797
         * that includes an HMAC of our randomly generated 64 bit
 
3798
         * session ID.
 
3799
         *
 
3800
         * On the other hand if --tls-auth is not being used, we
 
3801
         * will proceed to begin the TLS authentication
 
3802
         * handshake with only cursory integrity checks having
 
3803
         * been performed, since we will be leaving the task
 
3804
         * of authentication solely up to TLS.
 
3805
         */
 
3806
 
 
3807
        ret = true;
 
3808
      }
 
3809
    }
 
3810
 error:
 
3811
  gc_free (&gc);
 
3812
  return ret;
 
3813
}
 
3814
 
3013
3815
/* Choose the key with which to encrypt a data packet */
3014
3816
void
3015
3817
tls_pre_encrypt (struct tls_multi *multi,
3022
3824
      for (i = 0; i < KEY_SCAN_SIZE; ++i)
3023
3825
        {
3024
3826
          struct key_state *ks = multi->key_scan[i];
3025
 
          if (ks->state >= S_ACTIVE)
 
3827
          if (ks->state >= S_ACTIVE && ks->authenticated)
3026
3828
            {
3027
3829
              opt->key_ctx_bi = &ks->key;
3028
3830
              opt->packet_id = multi->opt.replay ? &ks->packet_id : NULL;
3029
3831
              opt->pid_persist = NULL;
3030
 
              opt->packet_id_long_form = multi->opt.packet_id_long_form;
 
3832
              opt->flags &= multi->opt.crypto_flags_and;
 
3833
              opt->flags |= multi->opt.crypto_flags_or;
3031
3834
              multi->save_ks = ks;
3032
 
              msg (D_TLS_DEBUG, "tls_pre_encrypt: key_id=%d", ks->key_id);
 
3835
              dmsg (D_TLS_DEBUG, "TLS: tls_pre_encrypt: key_id=%d", ks->key_id);
3033
3836
              return;
3034
3837
            }
3035
3838
        }
3036
 
      msg (D_TLS_NO_SEND_KEY, "TLS Warning: no data channel send key available: %s",
3037
 
           print_key_id (multi));
 
3839
 
 
3840
      {
 
3841
        struct gc_arena gc = gc_new ();
 
3842
        dmsg (D_TLS_NO_SEND_KEY, "TLS Warning: no data channel send key available: %s",
 
3843
             print_key_id (multi, &gc));
 
3844
        gc_free (&gc);
 
3845
      }
3038
3846
    }
3039
3847
 
3040
3848
  buf->len = 0;
3041
3849
  opt->key_ctx_bi = NULL;
3042
3850
  opt->packet_id = NULL;
3043
3851
  opt->pid_persist = NULL;
3044
 
  opt->packet_id_long_form = false;
 
3852
  opt->flags &= multi->opt.crypto_flags_and;
3045
3853
}
3046
3854
 
3047
3855
/* Prepend the appropriate opcode to encrypted buffer prior to TCP/UDP send */
3064
3872
}
3065
3873
 
3066
3874
/*
 
3875
 * Send a payload over the TLS control channel.
 
3876
 * Called externally.
 
3877
 */
 
3878
 
 
3879
bool
 
3880
tls_send_payload (struct tls_multi *multi,
 
3881
                  const uint8_t *data,
 
3882
                  int size)
 
3883
{
 
3884
  struct tls_session *session;
 
3885
  struct key_state *ks;
 
3886
  bool ret = false;
 
3887
 
 
3888
  ASSERT (multi);
 
3889
 
 
3890
  session = &multi->session[TM_ACTIVE];
 
3891
  ks = &session->key[KS_PRIMARY];
 
3892
 
 
3893
  if (ks->state >= S_ACTIVE)
 
3894
    {
 
3895
      if (key_state_write_plaintext_const (multi, ks, data, size) == 1)
 
3896
        ret = true;
 
3897
    }
 
3898
 
 
3899
  return ret;
 
3900
}
 
3901
 
 
3902
bool
 
3903
tls_rec_payload (struct tls_multi *multi,
 
3904
                 struct buffer *buf)
 
3905
{
 
3906
  struct tls_session *session;
 
3907
  struct key_state *ks;
 
3908
  bool ret = false;
 
3909
 
 
3910
  ASSERT (multi);
 
3911
 
 
3912
  session = &multi->session[TM_ACTIVE];
 
3913
  ks = &session->key[KS_PRIMARY];
 
3914
 
 
3915
  if (ks->state >= S_ACTIVE && BLEN (&ks->plaintext_read_buf))
 
3916
    {
 
3917
      if (buf_copy (buf, &ks->plaintext_read_buf))
 
3918
        ret = true;
 
3919
      ks->plaintext_read_buf.len = 0;
 
3920
    }
 
3921
 
 
3922
  return ret;
 
3923
}
 
3924
 
 
3925
/*
3067
3926
 * Dump a human-readable rendition of an openvpn packet
3068
3927
 * into a garbage collectable string which is returned.
3069
3928
 */
3070
3929
const char *
3071
 
protocol_dump (struct buffer *buffer, unsigned int flags)
 
3930
protocol_dump (struct buffer *buffer, unsigned int flags, struct gc_arena *gc)
3072
3931
{
3073
 
  struct buffer out = alloc_buf_gc (256);
 
3932
  struct buffer out = alloc_buf_gc (256, gc);
3074
3933
  struct buffer buf = *buffer;
3075
3934
 
3076
3935
  uint8_t c;
3109
3968
    if (!session_id_read (&sid, &buf))
3110
3969
      goto done;
3111
3970
    if (flags & PD_VERBOSE)
3112
 
        buf_printf (&out, " sid=%s", session_id_print (&sid));
 
3971
        buf_printf (&out, " sid=%s", session_id_print (&sid, gc));
3113
3972
  }
3114
3973
 
3115
3974
  /*
3125
3984
      if (!buf_read (&buf, tls_auth_hmac, tls_auth_hmac_size))
3126
3985
        goto done;
3127
3986
      if (flags & PD_VERBOSE)
3128
 
        buf_printf (&out, " tls_hmac=%s", format_hex (tls_auth_hmac, tls_auth_hmac_size, 0));
 
3987
        buf_printf (&out, " tls_hmac=%s", format_hex (tls_auth_hmac, tls_auth_hmac_size, 0, gc));
3129
3988
 
3130
3989
      if (!packet_id_read (&pin, &buf, true))
3131
3990
        goto done;
3132
 
      buf_printf(&out, " pid=%s", packet_id_net_print (&pin, (flags & PD_VERBOSE)));
 
3991
      buf_printf(&out, " pid=%s", packet_id_net_print (&pin, (flags & PD_VERBOSE), gc));
3133
3992
    }
3134
3993
 
3135
3994
  /*
3136
3995
   * ACK list
3137
3996
   */
3138
 
  buf_printf (&out, " %s", reliable_ack_print(&buf, (flags & PD_VERBOSE)));
 
3997
  buf_printf (&out, " %s", reliable_ack_print(&buf, (flags & PD_VERBOSE), gc));
3139
3998
 
3140
3999
  if (op == P_ACK_V1)
3141
4000
    goto done;
3153
4012
 
3154
4013
print_data:
3155
4014
  if (flags & PD_SHOW_DATA)
3156
 
    buf_printf (&out, " DATA %s", format_hex (BPTR (&buf), BLEN (&buf), 80));
 
4015
    buf_printf (&out, " DATA %s", format_hex (BPTR (&buf), BLEN (&buf), 80, gc));
3157
4016
  else
3158
4017
    buf_printf (&out, " DATA len=%d", buf.len);
3159
4018
 
3161
4020
  return BSTR (&out);
3162
4021
}
3163
4022
 
 
4023
#ifdef EXTRACT_X509_FIELD_TEST
 
4024
 
 
4025
void
 
4026
extract_x509_field_test (void)
 
4027
{
 
4028
  char line[8];
 
4029
  char field[4];
 
4030
  static const char field_name[] = "CN";
 
4031
 
 
4032
  while (fgets (line, sizeof (line), stdin))
 
4033
    {
 
4034
      chomp (line);
 
4035
      extract_x509_field (line, field_name, field, sizeof (field));
 
4036
      printf ("CN: '%s'\n", field);
 
4037
    }
 
4038
}
 
4039
 
 
4040
#endif
 
4041
 
3164
4042
#else
3165
4043
static void dummy(void) {}
3166
4044
#endif /* USE_CRYPTO && USE_SSL*/