329
* Extract a field from an X509 subject name.
333
* /C=US/ST=CO/L=Denver/O=ORG/CN=Test-CA/Email=jim@yonan.net
335
* The common name is 'Test-CA'
338
extract_x509_field (const char *x509, const char *field_name, char *out, int size)
341
struct buffer x509_buf;
345
buf_set_read (&x509_buf, (uint8_t *)x509, strlen (x509));
346
while (buf_parse (&x509_buf, '/', field_buf, sizeof (field_buf)))
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))
356
strncpynt (out, field_value_buf, size);
363
setenv_untrusted (struct tls_session *session)
365
setenv_sockaddr (session->opt->es, "untrusted", &session->untrusted_sockaddr, SA_IP_PORT);
369
set_common_name (struct tls_session *session, const char *common_name)
371
if (session->common_name)
373
free (session->common_name);
374
session->common_name = NULL;
378
session->common_name = string_alloc (common_name, NULL);
383
* nsCertType checking
386
#define verify_nsCertType(x, usage) (((x)->ex_flags & EXFLAG_NSCERT) && ((x)->ex_nscert & (usage)))
389
print_nsCertType (int type)
266
403
* Our verify callback function -- check
267
404
* that an incoming peer certificate is good.
270
static const char *verify_command;
271
static const char *verify_x509name;
272
static const char *crl_file;
273
static int verify_maxlevel;
276
tls_set_verify_command (const char *cmd)
278
verify_command = cmd;
282
tls_set_verify_x509name (const char *x509name)
284
verify_x509name = x509name;
288
tls_set_crl_verify (const char *crl)
294
get_max_tls_verify_id ()
296
return verify_maxlevel;
300
408
verify_callback (int preverify_ok, X509_STORE_CTX * ctx)
303
411
char envname[64];
412
char common_name[TLS_CN_LEN];
414
struct tls_session *session;
415
const struct tls_options *opt;
304
416
const int max_depth = 8;
306
X509_NAME_oneline (X509_get_subject_name (ctx->current_cert), txt,
308
txt[sizeof (txt) - 1] = '\0';
418
/* get the tls_session pointer */
419
ssl = X509_STORE_CTX_get_ex_data (ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
421
session = (struct tls_session *) SSL_get_ex_data (ssl, mydata_index);
426
session->verified = false;
428
/* get the X509 name */
429
X509_NAME_oneline (X509_get_subject_name (ctx->current_cert), subject,
431
subject[sizeof (subject) - 1] = '\0';
433
/* enforce character class restrictions in X509 name */
434
string_mod (subject, X509_NAME_CHAR_CLASS, 0, '_');
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, '_');
440
#if 0 /* print some debugging info */
441
msg (D_LOW, "LOCAL OPT: %s", opt->local_options);
442
msg (D_LOW, "X509: %s", subject);
445
/* did peer present cert which was signed our root cert? */
311
446
if (!preverify_ok)
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 */
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);
458
/* save common name in session object */
459
if (ctx->error_depth == 0)
460
set_common_name (session, common_name);
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);
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);
327
473
/* export serial number as environmental variable */
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);
335
if (ctx->error_depth == 0)
337
if (strcmp (verify_x509name, txt) == 0)
338
msg (D_HANDSHAKE, "VERIFY X509NAME OK: %s", txt);
341
msg (D_HANDSHAKE, "VERIFY X509NAME ERROR: %s, must be %s",
342
txt, verify_x509name);
343
return 0; /* Reject connection */
353
setenv_str ("script_type", "tls-verify");
480
/* export current untrusted IP */
481
setenv_untrusted (session);
483
/* verify certificate nsCertType */
484
if (opt->ns_cert_type && ctx->error_depth == 0)
486
if (verify_nsCertType (ctx->current_cert, opt->ns_cert_type))
488
msg (D_HANDSHAKE, "VERIFY OK: nsCertType=%s",
489
print_nsCertType (opt->ns_cert_type));
493
msg (D_HANDSHAKE, "VERIFY nsCertType ERROR: %s, require nsCertType=%s",
494
subject, print_nsCertType (opt->ns_cert_type));
495
goto err; /* Reject connection */
499
/* verify X509 name or common name against --tls-remote */
500
if (opt->verify_x509name && strlen (opt->verify_x509name) > 0 && ctx->error_depth == 0)
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);
507
msg (D_HANDSHAKE, "VERIFY X509NAME ERROR: %s, must be %s",
508
subject, opt->verify_x509name);
509
goto err; /* Reject connection */
513
/* call --tls-verify plug-in(s) */
514
if (plugin_defined (opt->plugins, OPENVPN_PLUGIN_TLS_VERIFY))
520
buf_set_write (&out, (uint8_t*)command, sizeof (command));
521
buf_printf (&out, "%d %s",
525
ret = plugin_call (opt->plugins, OPENVPN_PLUGIN_TLS_VERIFY, command, opt->es);
529
msg (D_HANDSHAKE, "VERIFY PLUGIN OK: depth=%d, %s",
530
ctx->error_depth, subject);
534
msg (D_HANDSHAKE, "VERIFY PLUGIN ERROR: depth=%d, %s",
535
ctx->error_depth, subject);
536
goto err; /* Reject connection */
540
/* run --tls-verify script */
541
if (opt->verify_command)
547
setenv_str (opt->es, "script_type", "tls-verify");
355
549
buf_set_write (&out, (uint8_t*)command, sizeof (command));
356
550
buf_printf (&out, "%s %d %s",
358
552
ctx->error_depth,
360
msg (D_TLS_DEBUG, "executing verify command: %s", command);
361
ret = openvpn_system (command);
554
dmsg (D_TLS_DEBUG, "TLS: executing verify command: %s", command);
555
ret = openvpn_system (command, opt->es, S_SCRIPT);
362
557
if (system_ok (ret))
364
559
msg (D_HANDSHAKE, "VERIFY SCRIPT OK: depth=%d, %s",
365
ctx->error_depth, txt);
560
ctx->error_depth, subject);
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 */
572
/* check peer cert against CRL */
379
575
X509_CRL *crl=NULL;
380
576
X509_REVOKED *revoked;
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);
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);
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);
507
/* Check Private Key */
508
if (!SSL_CTX_check_private_key (ctx))
509
msg (M_SSLERR, "Private key does not match the certificate");
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);
515
/* Load names of CAs from file and use it as a client CA list */
517
STACK_OF(X509_NAME) *cert_names;
518
cert_names = SSL_load_client_CA_file (ca_file);
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);
771
if (options->pkcs12_file)
773
/* Use PKCS #12 file for key, cert and CA certs */
778
STACK_OF(X509) *ca = NULL;
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);
788
if (!p12) msg (M_SSLERR, "Error reading PKCS#12 file %s", options->pkcs12_file);
790
/* Parse the PKCS #12 file */
791
if (!PKCS12_parse(p12, "", &pkey, &cert, &ca))
793
pem_password_callback (password, sizeof(password) - 1, 0, NULL);
794
/* Reparse the PKCS #12 file with password */
796
if (!PKCS12_parse(p12, password, &pkey, &cert, &ca))
797
msg (M_SSLERR, "Error parsing PKCS#12 file %s", options->pkcs12_file);
801
/* Load Certificate */
802
if (!SSL_CTX_use_certificate (ctx, cert))
803
msg (M_SSLERR, "Cannot use certificate");
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);
810
/* Check Private Key */
811
if (!SSL_CTX_check_private_key (ctx))
812
msg (M_SSLERR, "Private key does not match the certificate");
814
/* Set Certificate Verification chain */
815
if (ca && sk_num(ca))
817
for (i = 0; i < sk_X509_num(ca); i++)
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)");
828
/* Use seperate PEM files for key, cert and CA certs */
831
if (options->cryptoapi_cert)
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);
841
/* Load Certificate */
842
if (options->cert_file)
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);
849
/* Load Private Key */
850
if (options->priv_key_file)
852
if (!SSL_CTX_use_PrivateKey_file (ctx, options->priv_key_file, SSL_FILETYPE_PEM))
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);
858
msg (M_SSLERR, "Cannot load private key file %s", options->priv_key_file);
860
warn_if_group_others_accessible (options->priv_key_file);
862
/* Check Private Key */
863
if (!SSL_CTX_check_private_key (ctx))
864
msg (M_SSLERR, "Private key does not match the certificate");
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);
873
/* Load names of CAs from file and use it as a client CA list */
875
STACK_OF(X509_NAME) *cert_names;
876
cert_names = SSL_load_client_CA_file (options->ca_file);
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);
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);
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);
528
891
/* Require peer certificate verification */
529
SSL_CTX_set_verify (ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
893
if (options->client_cert_not_required)
895
msg (M_WARN, "WARNING: This configuration may accept clients which do not present a certificate");
899
SSL_CTX_set_verify (ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
532
902
/* Connection information callback */
533
903
SSL_CTX_set_info_callback (ctx, info_callback);
535
905
/* Allowable ciphers */
906
if (options->cipher_list)
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);
894
key_state_write_plaintext (struct key_state *ks, struct buffer *buf)
896
return bio_write (ks->ssl_bio, buf, "tls_write_plaintext");
900
key_state_write_ciphertext (struct key_state *ks, struct buffer *buf)
902
return bio_write (ks->ct_in, buf, "tls_write_ciphertext");
906
key_state_read_plaintext (struct key_state *ks, struct buffer *buf,
1259
bio_write_post (const int status, struct buffer *buf)
1261
if (status == 1) /* success status return from bio_write? */
1263
memset (BPTR (buf), 0, BLEN (buf)); /* erase data just written */
1269
key_state_write_plaintext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf)
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);
1280
key_state_write_plaintext_const (struct tls_multi *multi, struct key_state *ks, const uint8_t *data, int len)
1283
perf_push (PERF_BIO_WRITE_PLAINTEXT);
1284
ret = bio_write (multi, ks->ssl_bio, data, len, "tls_write_plaintext_const");
1290
key_state_write_ciphertext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf)
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);
1301
key_state_read_plaintext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf,
909
return bio_read (ks->ssl_bio, buf, maxlen, "tls_read_plaintext");
1305
perf_push (PERF_BIO_READ_PLAINTEXT);
1306
ret = bio_read (multi, ks->ssl_bio, buf, maxlen, "tls_read_plaintext");
913
key_state_read_ciphertext (struct key_state *ks, struct buffer *buf,
1312
key_state_read_ciphertext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf,
916
return bio_read (ks->ct_out, buf, maxlen, "tls_read_ciphertext");
1316
perf_push (PERF_BIO_READ_CIPHERTEXT);
1317
ret = bio_read (multi, ks->ct_out, buf, maxlen, "tls_read_ciphertext");
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))
1707
2213
* Move the active key to the lame duck key and reinitialize the
1711
key_state_soft_reset (struct tls_session *session, time_t current)
2217
key_state_soft_reset (struct tls_session *session)
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;
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;
2229
* Read/write strings from/to a struct buffer with a u16 length prefix.
2233
write_string (struct buffer *buf, const char *str, const int maxlen)
2235
const int len = strlen (str) + 1;
2236
if (len < 1 || (maxlen >= 0 && len > maxlen))
2238
if (!buf_write_u16 (buf, len))
2240
if (!buf_write (buf, str, len))
2246
read_string (struct buffer *buf, char *str, const unsigned int capacity)
2248
const int len = buf_read_u16 (buf);
2249
if (len < 1 || len > (int)capacity)
2251
if (!buf_read (buf, str, len))
2258
* Authenticate a client using username/password.
2261
* If you want to add new authentication methods,
2262
* this is the place to start.
2266
verify_user_pass_script (struct tls_session *session, const struct user_pass *up)
2268
struct gc_arena gc = gc_new ();
2269
struct buffer cmd = alloc_buf_gc (256, &gc);
2270
const char *tmp_file = "";
2274
/* Is username defined? */
2275
if (strlen (up->username))
2277
/* Set environmental variables prior to calling script */
2278
setenv_str (session->opt->es, "script_type", "user-pass-verify");
2280
if (session->opt->auth_user_pass_verify_script_via_file)
2282
struct status_output *so;
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))
2290
msg (D_TLS_ERRORS, "TLS Auth Error: could not write username/password to file: %s",
2297
setenv_str (session->opt->es, "username", up->username);
2298
setenv_str (session->opt->es, "password", up->password);
2301
/* setenv incoming cert common name for script */
2302
setenv_str (session->opt->es, "common_name", session->common_name);
2304
/* setenv client real IP address */
2305
setenv_untrusted (session);
2307
/* format command line */
2308
buf_printf (&cmd, "%s %s", session->opt->auth_user_pass_verify_script, tmp_file);
2311
retval = openvpn_system (BSTR (&cmd), session->opt->es, S_SCRIPT);
2313
/* test return status of command */
2314
if (system_ok (retval))
2316
else if (!system_executed (retval))
2317
msg (D_TLS_ERRORS, "TLS Auth Error: user-pass-verify script failed to execute: %s", BSTR (&cmd));
2319
if (!session->opt->auth_user_pass_verify_script_via_file)
2320
setenv_del (session->opt->es, "password");
2324
msg (D_TLS_ERRORS, "TLS Auth Error: peer provided a blank username");
2328
if (strlen (tmp_file) > 0)
2329
delete_file (tmp_file);
2336
verify_user_pass_plugin (struct tls_session *session, const struct user_pass *up)
2341
/* Is username defined? */
2342
if (strlen (up->username))
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);
2348
/* setenv incoming cert common name for script */
2349
setenv_str (session->opt->es, "common_name", session->common_name);
2351
/* setenv client real IP address */
2352
setenv_untrusted (session);
2355
retval = plugin_call (session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY, NULL, session->opt->es);
2360
setenv_del (session->opt->es, "password");
2364
msg (D_TLS_ERRORS, "TLS Auth Error: peer provided a blank username");
2371
* Handle the reading and writing of key data to and from
2372
* the TLS control channel (cleartext).
2376
key_method_1_write (struct buffer *buf, struct tls_session *session)
2380
ASSERT (session->opt->key_method == 1);
2381
ASSERT (buf_init (buf, 0));
2383
generate_key_random (&key, &session->opt->key_type);
2384
if (!check_key (&key, &session->opt->key_type))
2386
msg (D_TLS_ERRORS, "TLS Error: Bad encrypting key generated");
2390
if (!write_key (&key, &session->opt->key_type, buf))
2392
msg (D_TLS_ERRORS, "TLS Error: write_key failed");
2396
init_key_ctx (&ks->key.encrypt, &key, &session->opt->key_type,
2397
DO_ENCRYPT, "Data Channel Encrypt");
2400
/* send local options string */
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))
2406
msg (D_TLS_ERRORS, "TLS Error: KM1 write options failed");
2415
key_method_2_write (struct buffer *buf, struct tls_session *session)
2417
ASSERT (session->opt->key_method == 2);
2418
ASSERT (buf_init (buf, 0));
2420
/* write a uint32 0 */
2421
if (!buf_write_u32 (buf, 0))
2424
/* write key_method + flags */
2425
if (!buf_write_u8 (buf, (session->opt->key_method & KEY_METHOD_MASK)))
2428
/* write key source material */
2429
if (!key_source2_randomize_write (ks->key_src, buf, session->opt->server))
2432
/* write options string */
2434
if (!write_string (buf, local_options_string (session), TLS_OPTIONS_LEN))
2438
/* write username/password if specified */
2439
if (auth_user_pass_enabled)
2441
auth_user_pass_setup (NULL);
2442
if (!write_string (buf, auth_user_pass.username, -1))
2444
if (!write_string (buf, auth_user_pass.password, -1))
2446
purge_user_pass (&auth_user_pass);
2450
* generate tunnel keys if server
2452
if (session->opt->server)
2454
if (ks->authenticated)
2456
if (!generate_key_expansion (&ks->key,
2457
&session->opt->key_type,
2459
&ks->session_id_remote,
2460
&session->session_id,
2463
msg (D_TLS_ERRORS, "TLS Error: server generate_key_expansion failed");
2468
CLEAR (*ks->key_src);
2474
msg (D_TLS_ERRORS, "TLS Error: Key Method #2 write failed");
2475
CLEAR (*ks->key_src);
2480
key_method_1_read (struct buffer *buf, struct tls_session *session)
2485
ASSERT (session->opt->key_method == 1);
2487
if (!session->verified)
2490
"TLS Error: Certificate verification failed (key-method 1)");
2494
status = read_key (&key, &session->opt->key_type, buf);
2498
"TLS Error: Error reading data channel key from plaintext buffer");
2502
if (!check_key (&key, &session->opt->key_type))
2504
msg (D_TLS_ERRORS, "TLS Error: Bad decrypting key received from peer");
2510
msg (D_TLS_ERRORS, "TLS Error: Missing options string");
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))
2520
options_warning_safe (BPTR (buf), session->opt->remote_options, buf->len);
2526
init_key_ctx (&ks->key.decrypt, &key, &session->opt->key_type,
2527
DO_DECRYPT, "Data Channel Decrypt");
2529
ks->authenticated = true;
2539
key_method_2_read (struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
2541
struct gc_arena gc = gc_new ();
2542
int key_method_flags;
2544
struct user_pass *up;
2546
ASSERT (session->opt->key_method == 2);
2548
/* allocate temporary objects */
2549
ALLOC_ARRAY_CLEAR_GC (options, char, TLS_OPTIONS_LEN, &gc);
2551
/* discard leading uint32 */
2552
ASSERT (buf_advance (buf, 4));
2554
/* get key method */
2555
key_method_flags = buf_read_u8 (buf);
2556
if ((key_method_flags & KEY_METHOD_MASK) != 2)
2559
"TLS ERROR: Unknown key_method/flags=%d received from remote host",
2564
/* get key source material (not actual keys yet) */
2565
if (!key_source2_read (ks->key_src, buf, session->opt->server))
2567
msg (D_TLS_ERRORS, "TLS Error: Error reading remote data channel key source entropy from plaintext buffer");
2572
if (!read_string (buf, options, TLS_OPTIONS_LEN))
2574
msg (D_TLS_ERRORS, "TLS Error: Failed to read required OCC options string");
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))
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))
2591
msg (D_TLS_ERRORS, "TLS Error: Auth Username/Password was not provided by peer");
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, '_');
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);
2606
/* auth succeeded? */
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",
2614
session->opt->username_as_common_name ? "[CN SET]" : "");
2618
msg (D_TLS_ERRORS, "TLS Auth Error: Auth Username/Password verification failed for peer");
2625
if (!session->verified)
2628
"TLS Error: Certificate verification failed (key-method 2)");
2631
ks->authenticated = true;
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, "");
2638
/* Don't allow the CN to change once it's been locked */
2639
if (ks->authenticated && multi->locked_cn)
2641
const char *cn = session->common_name;
2642
if (cn && strcmp (cn, multi->locked_cn))
2644
msg (D_TLS_ERRORS, "TLS Auth Error: TLS object CN attempted to change from '%s' to '%s' -- tunnel disabled",
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);
2654
/* verify --client-config-dir based authentication */
2655
if (ks->authenticated && session->opt->client_config_dir_exclusive)
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))
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");
2669
/* check options consistency */
2670
if (!session->opt->disable_occ &&
2671
!options_cmp_equal (options, session->opt->remote_options))
2673
options_warning (options, session->opt->remote_options);
2680
* generate tunnel keys if client
2682
if (!session->opt->server)
2684
if (!generate_key_expansion (&ks->key,
2685
&session->opt->key_type,
2687
&session->session_id,
2688
&ks->session_id_remote,
2691
msg (D_TLS_ERRORS, "TLS Error: client generate_key_expansion failed");
2695
CLEAR (*ks->key_src);
2702
CLEAR (*ks->key_src);
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.
2013
2980
if (session->opt->key_method == 1)
2018
status = read_key (&key, &session->opt->key_type, buf);
2022
"TLS Error: Error reading data channel key from plaintext buffer");
2026
if (!check_key (&key, &session->opt->key_type))
2028
msg (D_TLS_ERRORS, "TLS Error: Bad decrypting key received from peer");
2032
ASSERT (buf->len > 0);
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))
2040
options_warning (BPTR (buf),
2041
session->opt->remote_options, buf->len);
2047
init_key_ctx (&ks->key.decrypt, &key, &session->opt->key_type,
2048
DO_DECRYPT, "Data Channel Decrypt");
2982
if (!key_method_1_read (buf, session))
2985
else if (session->opt->key_method == 2)
2987
if (!key_method_2_read (buf, multi, session))
2061
ASSERT (session->opt->key_method >= 2);
2064
/* discard leading uint32 */
2065
ASSERT (buf_advance (buf, 4));
2067
/* get key method */
2068
key_method = buf_read_u8 (buf);
2069
if (key_method != 2)
2072
"TLS ERROR: Unknown key_method=%d received from remote host",
2077
/* get key source material (not actual keys yet) */
2078
if (!key_source2_read (&ks->key_src, buf, session->opt->server))
2080
msg (D_TLS_ERRORS, "TLS Error: Error reading remote data channel key source entropy from plaintext buffer");
2085
optlen = buf_read_u16 (buf);
2086
if (optlen < 0 || optlen >= 65536)
2088
msg (D_TLS_ERRORS, "TLS Error: Bad options string length: %d", optlen);
2092
if (BLEN(buf) < optlen)
2094
msg (D_TLS_ERRORS, "TLS Error: Options string truncation");
2098
/* check options consistency */
2100
if (!session->opt->disable_occ &&
2101
!options_cmp_equal (BPTR (buf),
2102
session->opt->remote_options, buf->len))
2104
options_warning (BPTR (buf),
2105
session->opt->remote_options, buf->len);
2110
if (!session->opt->server)
2112
if (!generate_key_expansion (&ks->key,
2113
&session->opt->key_type,
2115
&session->session_id,
2116
&ks->session_id_remote,
2120
CLEAR (ks->key_src);
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;
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;
2268
"tls_multi_process: i=%d state=%s, mysid=%s, stored-sid=%s, stored-ip=%s",
3142
"TLS: tls_multi_process: i=%d state=%s, mysid=%s, stored-sid=%s, stored-ip=%s",
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));
2275
3149
if (ks->state >= S_INITIAL && addr_defined (&ks->remote_addr))
2277
current = time (NULL);
2279
3153
if (tls_process (multi, session, to_link, to_link_addr,
2280
to_link_socket, wakeup, current))
3154
to_link_socket_info, wakeup))
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
2288
3163
if (ks->state == S_ERROR)
2291
if (i == TM_ACTIVE && ks_lame->state >= S_ACTIVE)
3165
++multi->n_soft_errors;
3171
&& ks_lame->state >= S_ACTIVE
3172
&& !multi->opt.single_session)
2292
3173
move_session (multi, TM_LAME_DUCK, TM_ACTIVE, true);
2294
3175
reset_session (multi, session);
2297
mutex_cycle (L_TLS);
3178
//mutex_cycle (multi->mutex);
2300
current = time (NULL);
2303
3184
* If lame duck session expires, kill it.
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");
2311
3192
* If untrusted session achieves TLS authentication,
2312
3193
* move it to active session, usurping any prior session.
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.
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");
2319
mutex_unlock (L_TLS);
3202
msg (D_TLS_DEBUG_LOW, "TLS: tls_multi_process: untrusted session promoted to %strusted",
3203
tls_authenticated (multi) ? "" : "semi-");
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.
3212
for (i = 0; i < (int) SIZE (multi->key_scan); ++i)
3214
if (multi->key_scan[i]->state >= S_ACTIVE)
3217
++multi->n_hard_errors;
3222
/* DEBUGGING -- flood peer with repeating connection attempts */
3224
const int throw_level = GREMLIN_CONNECTION_FLOOD_LEVEL (multi->opt.gremlin);
3227
for (i = 0; i < (int) SIZE (multi->key_scan); ++i)
3229
if (multi->key_scan[i]->state >= throw_level)
3231
++multi->n_hard_errors;
3232
++multi->n_soft_errors;
2325
* When OpenVPN is built in pthread-mode, thread_func
2326
* will periodically call tls_multi_process.
2332
* Main thread <-> TLS thread communication.
2333
* Errors are fatal if they are of these types.
2336
local_sock_fatal (int status)
2338
return status < 0 && (errno == ENOTCONN || errno == ECONNREFUSED);
2342
* This routine is the TLS work thread.
2345
thread_func (void *arg)
2347
const int gc_level = gc_new_level ();
2348
const struct thread_parms *parm = (struct thread_parms*) arg;
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
2358
if (parm->mlock) /* should we disable paging? */
2362
/* change thread priority if requested */
2363
set_nice (parm->nice);
2365
/* buffer used to receive data from SSL/TLS */
2373
fd_set reads, writes;
2376
time_t current = time (NULL);
2377
interval_t wakeup = TLS_MULTI_REFRESH;
2379
msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: thread event loop");
2383
/* do a quick garbage collect */
2384
gc_collect (gc_level);
2386
/* do one SSL/TLS process pass */
2387
tls_multi_process (parm->multi, &buf, &ret.to_link_addr,
2388
parm->link_socket, &wakeup, current);
2390
/* determine events to wait for */
2394
/* did tls_multi_process give us a buffer to forward
2395
to foreground thread, on this or previous event
2398
FD_SET (parm->sd[TLS_THREAD_WORKER], &writes);
2400
/* always wait for incoming commands from foreground thread */
2401
FD_SET (parm->sd[TLS_THREAD_WORKER], &reads);
2403
/* set select timeout */
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",
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? */
2418
/* send buffer to foreground */
2419
if (FD_ISSET (parm->sd[TLS_THREAD_WORKER], &writes))
2423
/* make a fresh copy of buf in ret, and release buf */
2424
ret.to_link = clone_buf (&buf);
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);
2432
free_buf (&ret.to_link);
2437
/* get command from foreground */
2438
if (FD_ISSET (parm->sd[TLS_THREAD_WORKER], &reads))
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))
2448
if (tc.cmd == TTCMD_PROCESS)
2450
msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: TTCMD_PROCESS");
2452
else if (tc.cmd == TTCMD_EXIT)
2454
msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: TTCMD_EXIT");
2458
msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: Unknown TTCMD code: %d", tc.cmd);
2467
msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: exiting");
2468
close (parm->sd[TLS_THREAD_WORKER]);
2469
gc_free_level (gc_level);
2474
* All tls_thread functions below this point operate in the context of the main
2479
* Send a command to TLS thread.
2482
tls_thread_send_command (struct thread_parms *state, int cmd, bool wait_if_necessary)
2491
stat = write (state->sd[TLS_THREAD_MAIN], &tc, sizeof (tc));
2492
if (wait_if_necessary && stat < 0 && errno == EAGAIN)
2494
msg (D_TLS_THREAD_DEBUG, "TLS_THREAD: tls_thread_send_command WAIT");
2500
fatal = local_sock_fatal (stat);
2501
check_status (stat, "write command to tls thread", NULL, NULL);
2502
if (stat == sizeof (tc))
2511
* Create the TLS thread.
2514
tls_thread_create (struct thread_parms *state,
2515
struct tls_multi *multi,
2516
struct link_socket *link_socket,
2517
int nice, bool mlock)
2520
state->multi = multi;
2521
state->link_socket = link_socket;
2523
state->mlock = mlock;
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.
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);
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.
2546
tls_thread_process (struct thread_parms *state)
2548
return tls_thread_send_command (state, TTCMD_PROCESS, false);
2551
/* free any unprocessed buffers sent from background to foreground */
2553
tls_thread_flush (struct thread_parms *state)
2556
while (tls_thread_rec_buf (state, &ttr, false) == 1)
2558
free_buf (&ttr.to_link);
2563
* Close the TLS thread
2566
tls_thread_close (struct thread_parms *state)
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]);
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.
2581
* 0 if non-fatal error
2585
tls_thread_rec_buf (struct thread_parms *state, struct tt_ret* ttr, bool do_check_status)
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))
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.
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;
3704
++multi->n_soft_errors;
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.
3716
* This function is essentially the first-line HMAC firewall
3717
* on the UDP port listener in --mode server mode.
3720
tls_pre_decrypt_lite (const struct tls_auth_standalone *tas,
3721
const struct sockaddr_in *from,
3722
const struct buffer *buf)
3724
struct gc_arena gc = gc_new ();
3732
/* get opcode and key ID */
3734
uint8_t c = *BPTR (buf);
3735
op = c >> P_OPCODE_SHIFT;
3736
key_id = c & P_KEY_ID_MASK;
3739
/* this packet is from an as-yet untrusted source, so
3740
scrutinize carefully */
3742
if (op != P_CONTROL_HARD_RESET_CLIENT_V2)
3745
* This can occur due to bogus data or DoS packets.
3747
dmsg (D_TLS_STATE_ERRORS,
3748
"TLS State Error: No TLS state for client %s, opcode=%d",
3749
print_sockaddr (from, &gc),
3756
dmsg (D_TLS_STATE_ERRORS,
3757
"TLS State Error: Unknown key ID (%d) received from %s -- 0 was expected",
3759
print_sockaddr (from, &gc));
3763
if (buf->len > EXPANDED_SIZE_DYNAMIC (&tas->frame))
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",
3768
print_sockaddr (from, &gc),
3769
EXPANDED_SIZE_DYNAMIC (&tas->frame));
3774
struct buffer newbuf = clone_buf (buf);
3775
struct crypto_options co = tas->tls_auth_options;
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.
3783
co.flags |= CO_IGNORE_PACKET_ID;
3785
/* HMAC test, if --tls-auth was specified */
3786
status = read_control_auth (&newbuf, &co, from);
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
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.
3013
3815
/* Choose the key with which to encrypt a data packet */
3015
3817
tls_pre_encrypt (struct tls_multi *multi,