big svn cleanup
[anytun.git] / src / openvpn / ssl.c
blob9cde47d423648b35f08efe10ecc3bdaf34913e51
1 /*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
8 * Copyright (C) 2002-2005 OpenVPN Solutions LLC <info@openvpn.net>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program (see the file COPYING included with this
21 * distribution); if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 * The routines in this file deal with dynamically negotiating
27 * the data channel HMAC and cipher keys through a TLS session.
29 * Both the TLS session and the data channel are multiplexed
30 * over the same TCP/UDP port.
33 #ifdef WIN32
34 #include "config-win32.h"
35 #else
36 #include "config.h"
37 #endif
39 #if defined(USE_CRYPTO) && defined(USE_SSL)
41 #include "syshead.h"
43 #include "ssl.h"
44 #include "error.h"
45 #include "common.h"
46 #include "integer.h"
47 #include "socket.h"
48 #include "thread.h"
49 #include "misc.h"
50 #include "fdmisc.h"
51 #include "interval.h"
52 #include "perf.h"
53 #include "status.h"
54 #include "gremlin.h"
56 #ifdef WIN32
57 #include "cryptoapi.h"
58 #endif
60 #include "memdbg.h"
62 #ifndef ENABLE_OCC
63 static const char ssl_default_options_string[] = "V0 UNDEF";
64 #endif
66 static inline const char *
67 local_options_string (const struct tls_session *session)
69 #ifdef ENABLE_OCC
70 return session->opt->local_options;
71 #else
72 return ssl_default_options_string;
73 #endif
76 #ifdef MEASURE_TLS_HANDSHAKE_STATS
78 static int tls_handshake_success; /* GLOBAL */
79 static int tls_handshake_error; /* GLOBAL */
80 static int tls_packets_generated; /* GLOBAL */
81 static int tls_packets_sent; /* GLOBAL */
83 #define INCR_SENT ++tls_packets_sent
84 #define INCR_GENERATED ++tls_packets_generated
85 #define INCR_SUCCESS ++tls_handshake_success
86 #define INCR_ERROR ++tls_handshake_error
88 void
89 show_tls_performance_stats(void)
91 msg (D_TLS_DEBUG_LOW, "TLS Handshakes, success=%f%% (good=%d, bad=%d), retransmits=%f%%",
92 (double) tls_handshake_success / (tls_handshake_success + tls_handshake_error) * 100.0,
93 tls_handshake_success, tls_handshake_error,
94 (double) (tls_packets_sent - tls_packets_generated) / tls_packets_generated * 100.0);
96 #else
98 #define INCR_SENT
99 #define INCR_GENERATED
100 #define INCR_SUCCESS
101 #define INCR_ERROR
103 #endif
105 #ifdef BIO_DEBUG
107 #warning BIO_DEBUG defined
109 static FILE *biofp; /* GLOBAL */
110 static bool biofp_toggle; /* GLOBAL */
111 static time_t biofp_last_open; /* GLOBAL */
112 static const int biofp_reopen_interval = 600; /* GLOBAL */
114 static void
115 close_biofp()
117 if (biofp)
119 ASSERT (!fclose (biofp));
120 biofp = NULL;
124 static void
125 open_biofp()
127 const time_t current = time (NULL);
128 const pid_t pid = getpid ();
130 if (biofp_last_open + biofp_reopen_interval < current)
131 close_biofp();
132 if (!biofp)
134 char fn[256];
135 openvpn_snprintf(fn, sizeof(fn), "bio/%d-%d.log", pid, biofp_toggle);
136 biofp = fopen (fn, "w");
137 ASSERT (biofp);
138 biofp_last_open = time (NULL);
139 biofp_toggle ^= 1;
143 static void
144 bio_debug_data (const char *mode, BIO *bio, const uint8_t *buf, int len, const char *desc)
146 struct gc_arena gc = gc_new ();
147 if (len > 0)
149 open_biofp();
150 fprintf(biofp, "BIO_%s %s time=" time_format " bio=" ptr_format " len=%d data=%s\n",
151 mode, desc, time (NULL), (ptr_type)bio, len, format_hex (buf, len, 0, &gc));
152 fflush (biofp);
154 gc_free (&gc);
157 static void
158 bio_debug_oc (const char *mode, BIO *bio)
160 open_biofp();
161 fprintf(biofp, "BIO %s time=" time_format " bio=" ptr_format "\n",
162 mode, time (NULL), (ptr_type)bio);
163 fflush (biofp);
166 #endif
169 * Max number of bytes we will add
170 * for data structures common to both
171 * data and control channel packets.
172 * (opcode only).
174 void
175 tls_adjust_frame_parameters(struct frame *frame)
177 frame_add_to_extra_frame (frame, 1); /* space for opcode */
181 * Max number of bytes we will add
182 * to control channel packet.
184 static void
185 tls_init_control_channel_frame_parameters(const struct frame *data_channel_frame,
186 struct frame *frame)
189 * frame->extra_frame is already initialized with tls_auth buffer requirements,
190 * if --tls-auth is enabled.
193 /* inherit link MTU and extra_link from data channel */
194 frame->link_mtu = data_channel_frame->link_mtu;
195 frame->extra_link = data_channel_frame->extra_link;
197 /* set extra_frame */
198 tls_adjust_frame_parameters (frame);
199 reliable_ack_adjust_frame_parameters (frame, CONTROL_SEND_ACK_MAX);
200 frame_add_to_extra_frame (frame, SID_SIZE + sizeof (packet_id_type));
202 /* set dynamic link MTU to minimum value */
203 frame_set_mtu_dynamic (frame, 0, SET_MTU_TUN);
207 * Allocate space in SSL objects
208 * in which to store a struct tls_session
209 * pointer back to parent.
212 static int mydata_index; /* GLOBAL */
214 static void
215 ssl_set_mydata_index ()
217 mydata_index = SSL_get_ex_new_index (0, "struct session *", NULL, NULL, NULL);
218 ASSERT (mydata_index >= 0);
221 void
222 init_ssl_lib ()
224 SSL_library_init ();
225 SSL_load_error_strings ();
226 OpenSSL_add_all_algorithms ();
228 init_crypto_lib();
231 * If you build the OpenSSL library and OpenVPN with
232 * CRYPTO_MDEBUG, you will get a listing of OpenSSL
233 * memory leaks on program termination.
235 #ifdef CRYPTO_MDEBUG
236 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
237 #endif
239 ssl_set_mydata_index ();
242 void
243 free_ssl_lib ()
245 #ifdef CRYPTO_MDEBUG
246 FILE* fp = fopen ("sdlog", "w");
247 ASSERT (fp);
248 CRYPTO_mem_leaks_fp (fp);
249 fclose (fp);
250 #endif
252 uninit_crypto_lib ();
253 EVP_cleanup ();
254 ERR_free_strings ();
258 * OpenSSL library calls pem_password_callback if the
259 * private key is protected by a password.
262 static struct user_pass passbuf; /* GLOBAL */
264 void
265 pem_password_setup (const char *auth_file)
267 if (!strlen (passbuf.password))
268 get_user_pass (&passbuf, auth_file, true, UP_TYPE_PRIVATE_KEY, GET_USER_PASS_MANAGEMENT|GET_USER_PASS_SENSITIVE);
272 pem_password_callback (char *buf, int size, int rwflag, void *u)
274 if (buf)
276 /* prompt for password even if --askpass wasn't specified */
277 pem_password_setup (NULL);
278 strncpynt (buf, passbuf.password, size);
279 purge_user_pass (&passbuf, false);
281 return strlen (buf);
283 return 0;
287 * Auth username/password handling
290 static bool auth_user_pass_enabled; /* GLOBAL */
291 static struct user_pass auth_user_pass; /* GLOBAL */
293 void
294 auth_user_pass_setup (const char *auth_file)
296 auth_user_pass_enabled = true;
297 if (!auth_user_pass.defined)
298 get_user_pass (&auth_user_pass, auth_file, false, UP_TYPE_AUTH, GET_USER_PASS_MANAGEMENT|GET_USER_PASS_SENSITIVE);
302 * Disable password caching
304 void
305 ssl_set_auth_nocache (void)
307 passbuf.nocache = true;
308 auth_user_pass.nocache = true;
312 * Forget private key password AND auth-user-pass username/password.
314 void
315 ssl_purge_auth (void)
317 #if 1 /* JYFIXME -- todo: bad private key should trigger a signal, then this code can be included */
318 purge_user_pass (&passbuf, true);
319 #endif
320 purge_user_pass (&auth_user_pass, true);
324 * OpenSSL callback to get a temporary RSA key, mostly
325 * used for export ciphers.
327 static RSA *
328 tmp_rsa_cb (SSL * s, int is_export, int keylength)
330 static RSA *rsa_tmp = NULL;
331 if (rsa_tmp == NULL)
333 msg (D_HANDSHAKE, "Generating temp (%d bit) RSA key", keylength);
334 rsa_tmp = RSA_generate_key (keylength, RSA_F4, NULL, NULL);
336 return (rsa_tmp);
340 * Extract a field from an X509 subject name.
342 * Example:
344 * /C=US/ST=CO/L=Denver/O=ORG/CN=Test-CA/Email=jim@yonan.net
346 * The common name is 'Test-CA'
348 static void
349 extract_x509_field (const char *x509, const char *field_name, char *out, int size)
351 char field_buf[256];
352 struct buffer x509_buf;
354 ASSERT (size > 0);
355 *out = '\0';
356 buf_set_read (&x509_buf, (uint8_t *)x509, strlen (x509));
357 while (buf_parse (&x509_buf, '/', field_buf, sizeof (field_buf)))
359 struct buffer component_buf;
360 char field_name_buf[64];
361 char field_value_buf[256];
362 buf_set_read (&component_buf, (const uint8_t *) field_buf, strlen (field_buf));
363 buf_parse (&component_buf, '=', field_name_buf, sizeof (field_name_buf));
364 buf_parse (&component_buf, '=', field_value_buf, sizeof (field_value_buf));
365 if (!strcmp (field_name_buf, field_name))
367 strncpynt (out, field_value_buf, size);
368 break;
373 static void
374 setenv_untrusted (struct tls_session *session)
376 setenv_sockaddr (session->opt->es, "untrusted", &session->untrusted_sockaddr, SA_IP_PORT);
379 static void
380 set_common_name (struct tls_session *session, const char *common_name)
382 if (session->common_name)
384 free (session->common_name);
385 session->common_name = NULL;
387 if (common_name)
389 session->common_name = string_alloc (common_name, NULL);
394 * nsCertType checking
397 #define verify_nsCertType(x, usage) (((x)->ex_flags & EXFLAG_NSCERT) && ((x)->ex_nscert & (usage)))
399 static const char *
400 print_nsCertType (int type)
402 switch (type)
404 case NS_SSL_SERVER:
405 return "SERVER";
406 case NS_SSL_CLIENT:
407 return "CLIENT";
408 default:
409 return "?";
414 * Our verify callback function -- check
415 * that an incoming peer certificate is good.
418 static int
419 verify_callback (int preverify_ok, X509_STORE_CTX * ctx)
421 char subject[256];
422 char envname[64];
423 char common_name[TLS_CN_LEN];
424 SSL *ssl;
425 struct tls_session *session;
426 const struct tls_options *opt;
427 const int max_depth = 8;
429 /* get the tls_session pointer */
430 ssl = X509_STORE_CTX_get_ex_data (ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
431 ASSERT (ssl);
432 session = (struct tls_session *) SSL_get_ex_data (ssl, mydata_index);
433 ASSERT (session);
434 opt = session->opt;
435 ASSERT (opt);
437 session->verified = false;
439 /* get the X509 name */
440 X509_NAME_oneline (X509_get_subject_name (ctx->current_cert), subject,
441 sizeof (subject));
442 subject[sizeof (subject) - 1] = '\0';
444 /* enforce character class restrictions in X509 name */
445 string_mod (subject, X509_NAME_CHAR_CLASS, 0, '_');
447 /* extract the common name */
448 extract_x509_field (subject, "CN", common_name, TLS_CN_LEN);
449 string_mod (common_name, COMMON_NAME_CHAR_CLASS, 0, '_');
451 #if 0 /* print some debugging info */
452 msg (D_LOW, "LOCAL OPT: %s", opt->local_options);
453 msg (D_LOW, "X509: %s", subject);
454 #endif
456 /* did peer present cert which was signed our root cert? */
457 if (!preverify_ok)
459 /* Remote site specified a certificate, but it's not correct */
460 msg (D_TLS_ERRORS, "VERIFY ERROR: depth=%d, error=%s: %s",
461 ctx->error_depth, X509_verify_cert_error_string (ctx->error), subject);
462 goto err; /* Reject connection */
465 /* warn if cert chain is too deep */
466 if (ctx->error_depth >= max_depth)
467 msg (M_WARN, "TLS Warning: Convoluted certificate chain detected with depth [%d] greater than %d", ctx->error_depth, max_depth);
469 /* save common name in session object */
470 if (ctx->error_depth == 0)
471 set_common_name (session, common_name);
473 /* export subject name string as environmental variable */
474 session->verify_maxlevel = max_int (session->verify_maxlevel, ctx->error_depth);
475 openvpn_snprintf (envname, sizeof(envname), "tls_id_%d", ctx->error_depth);
476 setenv_str (opt->es, envname, subject);
478 #if 0
479 /* export common name string as environmental variable */
480 openvpn_snprintf (envname, sizeof(envname), "tls_common_name_%d", ctx->error_depth);
481 setenv_str (opt->es, envname, common_name);
482 #endif
484 /* export serial number as environmental variable */
486 const int serial = (int) ASN1_INTEGER_get (X509_get_serialNumber (ctx->current_cert));
487 openvpn_snprintf (envname, sizeof(envname), "tls_serial_%d", ctx->error_depth);
488 setenv_int (opt->es, envname, serial);
491 /* export current untrusted IP */
492 setenv_untrusted (session);
494 /* verify certificate nsCertType */
495 if (opt->ns_cert_type && ctx->error_depth == 0)
497 if (verify_nsCertType (ctx->current_cert, opt->ns_cert_type))
499 msg (D_HANDSHAKE, "VERIFY OK: nsCertType=%s",
500 print_nsCertType (opt->ns_cert_type));
502 else
504 msg (D_HANDSHAKE, "VERIFY nsCertType ERROR: %s, require nsCertType=%s",
505 subject, print_nsCertType (opt->ns_cert_type));
506 goto err; /* Reject connection */
510 /* verify X509 name or common name against --tls-remote */
511 if (opt->verify_x509name && strlen (opt->verify_x509name) > 0 && ctx->error_depth == 0)
513 if (strcmp (opt->verify_x509name, subject) == 0
514 || strncmp (opt->verify_x509name, common_name, strlen (opt->verify_x509name)) == 0)
515 msg (D_HANDSHAKE, "VERIFY X509NAME OK: %s", subject);
516 else
518 msg (D_HANDSHAKE, "VERIFY X509NAME ERROR: %s, must be %s",
519 subject, opt->verify_x509name);
520 goto err; /* Reject connection */
524 /* call --tls-verify plug-in(s) */
525 if (plugin_defined (opt->plugins, OPENVPN_PLUGIN_TLS_VERIFY))
527 char command[256];
528 struct buffer out;
529 int ret;
531 buf_set_write (&out, (uint8_t*)command, sizeof (command));
532 buf_printf (&out, "%d %s",
533 ctx->error_depth,
534 subject);
536 ret = plugin_call (opt->plugins, OPENVPN_PLUGIN_TLS_VERIFY, command, opt->es);
538 if (!ret)
540 msg (D_HANDSHAKE, "VERIFY PLUGIN OK: depth=%d, %s",
541 ctx->error_depth, subject);
543 else
545 msg (D_HANDSHAKE, "VERIFY PLUGIN ERROR: depth=%d, %s",
546 ctx->error_depth, subject);
547 goto err; /* Reject connection */
551 /* run --tls-verify script */
552 if (opt->verify_command)
554 char command[256];
555 struct buffer out;
556 int ret;
558 setenv_str (opt->es, "script_type", "tls-verify");
560 buf_set_write (&out, (uint8_t*)command, sizeof (command));
561 buf_printf (&out, "%s %d %s",
562 opt->verify_command,
563 ctx->error_depth,
564 subject);
565 dmsg (D_TLS_DEBUG, "TLS: executing verify command: %s", command);
566 ret = openvpn_system (command, opt->es, S_SCRIPT);
568 if (system_ok (ret))
570 msg (D_HANDSHAKE, "VERIFY SCRIPT OK: depth=%d, %s",
571 ctx->error_depth, subject);
573 else
575 if (!system_executed (ret))
576 msg (M_ERR, "Verify command failed to execute: %s", command);
577 msg (D_HANDSHAKE, "VERIFY SCRIPT ERROR: depth=%d, %s",
578 ctx->error_depth, subject);
579 goto err; /* Reject connection */
583 /* check peer cert against CRL */
584 if (opt->crl_file)
586 X509_CRL *crl=NULL;
587 X509_REVOKED *revoked;
588 BIO *in=NULL;
589 int n,i,retval = 0;
591 in=BIO_new(BIO_s_file());
593 if (in == NULL) {
594 msg (M_ERR, "CRL: BIO err");
595 goto end;
597 if (BIO_read_filename(in, opt->crl_file) <= 0) {
598 msg (M_ERR, "CRL: cannot read: %s", opt->crl_file);
599 goto end;
601 crl=PEM_read_bio_X509_CRL(in,NULL,NULL,NULL);
602 if (crl == NULL) {
603 msg (M_ERR, "CRL: cannot read CRL from file %s", opt->crl_file);
604 goto end;
607 if (X509_NAME_cmp(X509_CRL_get_issuer(crl), X509_get_issuer_name(ctx->current_cert)) != 0) {
608 msg (M_WARN, "CRL: CRL %s is from a different issuer than the issuer of certificate %s", opt->crl_file, subject);
609 retval = 1;
610 goto end;
613 n = sk_num(X509_CRL_get_REVOKED(crl));
615 for (i = 0; i < n; i++) {
616 revoked = (X509_REVOKED *)sk_value(X509_CRL_get_REVOKED(crl), i);
617 if (ASN1_INTEGER_cmp(revoked->serialNumber, X509_get_serialNumber(ctx->current_cert)) == 0) {
618 msg (D_HANDSHAKE, "CRL CHECK FAILED: %s is REVOKED",subject);
619 goto end;
623 retval = 1;
624 msg (D_HANDSHAKE, "CRL CHECK OK: %s",subject);
626 end:
628 BIO_free(in);
629 if (crl)
630 X509_CRL_free (crl);
631 if (!retval)
632 goto err;
635 msg (D_HANDSHAKE, "VERIFY OK: depth=%d, %s", ctx->error_depth, subject);
637 session->verified = true;
638 return 1; /* Accept connection */
640 err:
641 ERR_clear_error ();
642 return 0; /* Reject connection */
645 void
646 tls_set_common_name (struct tls_multi *multi, const char *common_name)
648 if (multi)
649 set_common_name (&multi->session[TM_ACTIVE], common_name);
652 const char *
653 tls_common_name (struct tls_multi *multi, bool null)
655 const char *ret = NULL;
656 if (multi)
657 ret = multi->session[TM_ACTIVE].common_name;
658 if (ret && strlen (ret))
659 return ret;
660 else if (null)
661 return NULL;
662 else
663 return "UNDEF";
666 void
667 tls_lock_common_name (struct tls_multi *multi)
669 const char *cn = multi->session[TM_ACTIVE].common_name;
670 if (cn && !multi->locked_cn)
671 multi->locked_cn = string_alloc (cn, NULL);
675 * Return true if at least one valid key state exists
676 * which has passed authentication. If we are using
677 * username/password authentication, and the authentication
678 * failed, we may have a live S_ACTIVE/S_NORMAL key state
679 * even though the 'authenticated' var might be false.
681 * This is so that we can return an AUTH_FAILED error
682 * message to the client over the TLS channel.
684 * If 'authenticated' is false, tunnel traffic forwarding
685 * is disabled but TLS channel data can still be sent
686 * or received.
688 bool
689 tls_authenticated (struct tls_multi *multi)
691 if (multi)
693 int i;
694 for (i = 0; i < KEY_SCAN_SIZE; ++i)
696 const struct key_state *ks = multi->key_scan[i];
697 if (DECRYPT_KEY_ENABLED (multi, ks) && ks->authenticated)
698 return true;
701 return false;
704 void
705 tls_deauthenticate (struct tls_multi *multi)
707 if (multi)
709 int i, j;
710 for (i = 0; i < TM_SIZE; ++i)
711 for (j = 0; j < KS_SIZE; ++j)
712 multi->session[i].key[j].authenticated = false;
717 * Print debugging information on SSL/TLS session negotiation.
719 static void
720 info_callback (INFO_CALLBACK_SSL_CONST SSL * s, int where, int ret)
722 if (where & SSL_CB_LOOP)
724 dmsg (D_HANDSHAKE_VERBOSE, "SSL state (%s): %s",
725 where & SSL_ST_CONNECT ? "connect" :
726 where & SSL_ST_ACCEPT ? "accept" :
727 "undefined", SSL_state_string_long (s));
729 else if (where & SSL_CB_ALERT)
731 dmsg (D_HANDSHAKE_VERBOSE, "SSL alert (%s): %s: %s",
732 where & SSL_CB_READ ? "read" : "write",
733 SSL_alert_type_string_long (ret),
734 SSL_alert_desc_string_long (ret));
739 * Initialize SSL context.
740 * All files are in PEM format.
742 SSL_CTX *
743 init_ssl (const struct options *options)
745 SSL_CTX *ctx = NULL;
746 DH *dh;
747 BIO *bio;
748 bool using_cert_file = false;
750 ERR_clear_error ();
752 if (options->tls_server)
754 ctx = SSL_CTX_new (TLSv1_server_method ());
755 if (ctx == NULL)
756 msg (M_SSLERR, "SSL_CTX_new TLSv1_server_method");
758 SSL_CTX_set_tmp_rsa_callback (ctx, tmp_rsa_cb);
760 /* Get Diffie Hellman Parameters */
761 if (!(bio = BIO_new_file (options->dh_file, "r")))
762 msg (M_SSLERR, "Cannot open %s for DH parameters", options->dh_file);
763 dh = PEM_read_bio_DHparams (bio, NULL, NULL, NULL);
764 BIO_free (bio);
765 if (!dh)
766 msg (M_SSLERR, "Cannot load DH parameters from %s", options->dh_file);
767 if (!SSL_CTX_set_tmp_dh (ctx, dh))
768 msg (M_SSLERR, "SSL_CTX_set_tmp_dh");
769 msg (D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key",
770 8 * DH_size (dh));
771 DH_free (dh);
773 else /* if client */
775 ctx = SSL_CTX_new (TLSv1_client_method ());
776 if (ctx == NULL)
777 msg (M_SSLERR, "SSL_CTX_new TLSv1_client_method");
780 /* Set SSL options */
781 SSL_CTX_set_session_cache_mode (ctx, SSL_SESS_CACHE_OFF);
782 SSL_CTX_set_options (ctx, SSL_OP_SINGLE_DH_USE);
784 /* Set callback for getting password from user to decrypt private key */
785 SSL_CTX_set_default_passwd_cb (ctx, pem_password_callback);
787 if (options->pkcs12_file)
789 /* Use PKCS #12 file for key, cert and CA certs */
791 FILE *fp;
792 EVP_PKEY *pkey;
793 X509 *cert;
794 STACK_OF(X509) *ca = NULL;
795 PKCS12 *p12;
796 int i;
797 char password[256];
799 /* Load the PKCS #12 file */
800 if (!(fp = fopen(options->pkcs12_file, "rb")))
801 msg (M_SSLERR, "Error opening file %s", options->pkcs12_file);
802 p12 = d2i_PKCS12_fp(fp, NULL);
803 fclose (fp);
804 if (!p12) msg (M_SSLERR, "Error reading PKCS#12 file %s", options->pkcs12_file);
806 /* Parse the PKCS #12 file */
807 if (!PKCS12_parse(p12, "", &pkey, &cert, &ca))
809 pem_password_callback (password, sizeof(password) - 1, 0, NULL);
810 /* Reparse the PKCS #12 file with password */
811 ca = NULL;
812 if (!PKCS12_parse(p12, password, &pkey, &cert, &ca))
814 PKCS12_free(p12);
815 msg (M_WARN|M_SSL, "Error parsing PKCS#12 file %s", options->pkcs12_file);
816 goto err;
819 PKCS12_free(p12);
821 /* Load Certificate */
822 if (!SSL_CTX_use_certificate (ctx, cert))
823 msg (M_SSLERR, "Cannot use certificate");
825 /* Load Private Key */
826 if (!SSL_CTX_use_PrivateKey (ctx, pkey))
827 msg (M_SSLERR, "Cannot use private key");
828 warn_if_group_others_accessible (options->pkcs12_file);
830 /* Check Private Key */
831 if (!SSL_CTX_check_private_key (ctx))
832 msg (M_SSLERR, "Private key does not match the certificate");
834 /* Set Certificate Verification chain */
835 if (ca && sk_num(ca))
837 for (i = 0; i < sk_X509_num(ca); i++)
839 if (!X509_STORE_add_cert(ctx->cert_store,sk_X509_value(ca, i)))
840 msg (M_SSLERR, "Cannot add certificate to certificate chain (X509_STORE_add_cert)");
841 if (!SSL_CTX_add_client_CA(ctx, sk_X509_value(ca, i)))
842 msg (M_SSLERR, "Cannot add certificate to client CA list (SSL_CTX_add_client_CA)");
846 else
848 /* Use seperate PEM files for key, cert and CA certs */
850 #ifdef WIN32
851 if (options->cryptoapi_cert)
853 /* Load Certificate and Private Key */
854 if (!SSL_CTX_use_CryptoAPI_certificate (ctx, options->cryptoapi_cert))
855 msg (M_SSLERR, "Cannot load certificate \"%s\" from Microsoft Certificate Store",
856 options->cryptoapi_cert);
858 else
859 #endif
861 /* Load Certificate */
862 if (options->cert_file)
864 using_cert_file = true;
865 if (!SSL_CTX_use_certificate_file (ctx, options->cert_file, SSL_FILETYPE_PEM))
866 msg (M_SSLERR, "Cannot load certificate file %s", options->cert_file);
869 /* Load Private Key */
870 if (options->priv_key_file)
872 if (!SSL_CTX_use_PrivateKey_file (ctx, options->priv_key_file, SSL_FILETYPE_PEM))
874 #ifdef ENABLE_MANAGEMENT
875 if (management && (ERR_GET_REASON (ERR_peek_error()) == EVP_R_BAD_DECRYPT))
876 management_auth_failure (management, UP_TYPE_PRIVATE_KEY);
877 #endif
878 msg (M_WARN|M_SSL, "Cannot load private key file %s", options->priv_key_file);
879 goto err;
881 warn_if_group_others_accessible (options->priv_key_file);
883 /* Check Private Key */
884 if (!SSL_CTX_check_private_key (ctx))
885 msg (M_SSLERR, "Private key does not match the certificate");
889 /* Load CA file for verifying peer supplied certificate */
890 ASSERT (options->ca_file);
891 if (!SSL_CTX_load_verify_locations (ctx, options->ca_file, NULL))
892 msg (M_SSLERR, "Cannot load CA certificate file %s (SSL_CTX_load_verify_locations)", options->ca_file);
894 /* Load names of CAs from file and use it as a client CA list */
896 STACK_OF(X509_NAME) *cert_names;
897 cert_names = SSL_load_client_CA_file (options->ca_file);
898 if (!cert_names)
899 msg (M_SSLERR, "Cannot load CA certificate file %s (SSL_load_client_CA_file)", options->ca_file);
900 SSL_CTX_set_client_CA_list (ctx, cert_names);
905 /* Enable the use of certificate chains */
906 if (using_cert_file)
908 if (!SSL_CTX_use_certificate_chain_file (ctx, options->cert_file))
909 msg (M_SSLERR, "Cannot load certificate chain file %s (SSL_use_certificate_chain_file)", options->cert_file);
912 /* Require peer certificate verification */
913 #if P2MP_SERVER
914 if (options->client_cert_not_required)
916 msg (M_WARN, "WARNING: This configuration may accept clients which do not present a certificate");
918 else
919 #endif
920 SSL_CTX_set_verify (ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
921 verify_callback);
923 /* Connection information callback */
924 SSL_CTX_set_info_callback (ctx, info_callback);
926 /* Allowable ciphers */
927 if (options->cipher_list)
929 if (!SSL_CTX_set_cipher_list (ctx, options->cipher_list))
930 msg (M_SSLERR, "Problem with cipher list: %s", options->cipher_list);
933 ERR_clear_error ();
935 return ctx;
937 err:
938 ERR_clear_error ();
939 if (ctx)
940 SSL_CTX_free (ctx);
941 return NULL;
945 * Print a one line summary of SSL/TLS session handshake.
947 static void
948 print_details (SSL * c_ssl, const char *prefix)
950 SSL_CIPHER *ciph;
951 X509 *cert;
952 char s1[256];
953 char s2[256];
955 s1[0] = s2[0] = 0;
956 ciph = SSL_get_current_cipher (c_ssl);
957 openvpn_snprintf (s1, sizeof (s1), "%s %s, cipher %s %s",
958 prefix,
959 SSL_get_version (c_ssl),
960 SSL_CIPHER_get_version (ciph),
961 SSL_CIPHER_get_name (ciph));
962 cert = SSL_get_peer_certificate (c_ssl);
963 if (cert != NULL)
965 EVP_PKEY *pkey = X509_get_pubkey (cert);
966 if (pkey != NULL)
968 if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != NULL
969 && pkey->pkey.rsa->n != NULL)
971 openvpn_snprintf (s2, sizeof (s2), ", %d bit RSA",
972 BN_num_bits (pkey->pkey.rsa->n));
974 else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != NULL
975 && pkey->pkey.dsa->p != NULL)
977 openvpn_snprintf (s2, sizeof (s2), ", %d bit DSA",
978 BN_num_bits (pkey->pkey.dsa->p));
980 EVP_PKEY_free (pkey);
982 X509_free (cert);
984 /* The SSL API does not allow us to look at temporary RSA/DH keys,
985 * otherwise we should print their lengths too */
986 msg (D_HANDSHAKE, "%s%s", s1, s2);
990 * Show the TLS ciphers that are available for us to use
991 * in the OpenSSL library.
993 void
994 show_available_tls_ciphers ()
996 SSL_CTX *ctx;
997 SSL *ssl;
998 const char *cipher_name;
999 int priority = 0;
1001 ctx = SSL_CTX_new (TLSv1_method ());
1002 if (!ctx)
1003 msg (M_SSLERR, "Cannot create SSL_CTX object");
1004 ssl = SSL_new (ctx);
1005 if (!ssl)
1006 msg (M_SSLERR, "Cannot create SSL object");
1008 printf ("Available TLS Ciphers,\n");
1009 printf ("listed in order of preference:\n\n");
1010 while ((cipher_name = SSL_get_cipher_list (ssl, priority++)))
1011 printf ("%s\n", cipher_name);
1012 printf ("\n");
1014 SSL_free (ssl);
1015 SSL_CTX_free (ctx);
1019 * The OpenSSL library has a notion of preference in TLS
1020 * ciphers. Higher preference == more secure.
1021 * Return the highest preference cipher.
1023 void
1024 get_highest_preference_tls_cipher (char *buf, int size)
1026 SSL_CTX *ctx;
1027 SSL *ssl;
1028 const char *cipher_name;
1030 ctx = SSL_CTX_new (TLSv1_method ());
1031 if (!ctx)
1032 msg (M_SSLERR, "Cannot create SSL_CTX object");
1033 ssl = SSL_new (ctx);
1034 if (!ssl)
1035 msg (M_SSLERR, "Cannot create SSL object");
1037 cipher_name = SSL_get_cipher_list (ssl, 0);
1038 strncpynt (buf, cipher_name, size);
1040 SSL_free (ssl);
1041 SSL_CTX_free (ctx);
1045 * Map internal constants to ascii names.
1047 static const char *
1048 state_name (int state)
1050 switch (state)
1052 case S_UNDEF:
1053 return "S_UNDEF";
1054 case S_INITIAL:
1055 return "S_INITIAL";
1056 case S_PRE_START:
1057 return "S_PRE_START";
1058 case S_START:
1059 return "S_START";
1060 case S_SENT_KEY:
1061 return "S_SENT_KEY";
1062 case S_GOT_KEY:
1063 return "S_GOT_KEY";
1064 case S_ACTIVE:
1065 return "S_ACTIVE";
1066 case S_NORMAL:
1067 return "S_NORMAL";
1068 case S_ERROR:
1069 return "S_ERROR";
1070 default:
1071 return "S_???";
1075 static const char *
1076 packet_opcode_name (int op)
1078 switch (op)
1080 case P_CONTROL_HARD_RESET_CLIENT_V1:
1081 return "P_CONTROL_HARD_RESET_CLIENT_V1";
1082 case P_CONTROL_HARD_RESET_SERVER_V1:
1083 return "P_CONTROL_HARD_RESET_SERVER_V1";
1084 case P_CONTROL_HARD_RESET_CLIENT_V2:
1085 return "P_CONTROL_HARD_RESET_CLIENT_V2";
1086 case P_CONTROL_HARD_RESET_SERVER_V2:
1087 return "P_CONTROL_HARD_RESET_SERVER_V2";
1088 case P_CONTROL_SOFT_RESET_V1:
1089 return "P_CONTROL_SOFT_RESET_V1";
1090 case P_CONTROL_V1:
1091 return "P_CONTROL_V1";
1092 case P_ACK_V1:
1093 return "P_ACK_V1";
1094 case P_DATA_V1:
1095 return "P_DATA_V1";
1096 default:
1097 return "P_???";
1101 static const char *
1102 session_index_name (int index)
1104 switch (index)
1106 case TM_ACTIVE:
1107 return "TM_ACTIVE";
1108 case TM_UNTRUSTED:
1109 return "TM_UNTRUSTED";
1110 case TM_LAME_DUCK:
1111 return "TM_LAME_DUCK";
1112 default:
1113 return "TM_???";
1118 * For debugging.
1120 static const char *
1121 print_key_id (struct tls_multi *multi, struct gc_arena *gc)
1123 int i;
1124 struct buffer out = alloc_buf_gc (256, gc);
1126 for (i = 0; i < KEY_SCAN_SIZE; ++i)
1128 struct key_state *ks = multi->key_scan[i];
1129 buf_printf (&out, " [key#%d state=%s id=%d sid=%s]", i,
1130 state_name (ks->state), ks->key_id,
1131 session_id_print (&ks->session_id_remote, gc));
1134 return BSTR (&out);
1138 * Given a key_method, return true if op
1139 * represents the required form of hard_reset.
1141 * If key_method = 0, return true if any
1142 * form of hard reset is used.
1144 static bool
1145 is_hard_reset (int op, int key_method)
1147 if (!key_method || key_method == 1)
1148 if (op == P_CONTROL_HARD_RESET_CLIENT_V1 || op == P_CONTROL_HARD_RESET_SERVER_V1)
1149 return true;
1151 if (!key_method || key_method >= 2)
1152 if (op == P_CONTROL_HARD_RESET_CLIENT_V2 || op == P_CONTROL_HARD_RESET_SERVER_V2)
1153 return true;
1155 return false;
1159 * OpenVPN's interface to SSL/TLS authentication,
1160 * encryption, and decryption is exclusively
1161 * through "memory BIOs".
1163 static BIO *
1164 getbio (BIO_METHOD * type, const char *desc)
1166 BIO *ret;
1167 ret = BIO_new (type);
1168 if (!ret)
1169 msg (M_SSLERR, "Error creating %s BIO", desc);
1170 return ret;
1174 * Write to an OpenSSL BIO in non-blocking mode.
1176 static int
1177 bio_write (struct tls_multi* multi, BIO *bio, const uint8_t *data, int size, const char *desc)
1179 int i;
1180 int ret = 0;
1181 ASSERT (size >= 0);
1182 if (size)
1185 * Free the L_TLS lock prior to calling BIO routines
1186 * so that foreground thread can still call
1187 * tls_pre_decrypt or tls_pre_encrypt,
1188 * allowing tunnel packet forwarding to continue.
1190 #ifdef BIO_DEBUG
1191 bio_debug_data ("write", bio, data, size, desc);
1192 #endif
1193 i = BIO_write (bio, data, size);
1195 if (i < 0)
1197 if (BIO_should_retry (bio))
1201 else
1203 msg (D_TLS_ERRORS | M_SSL, "TLS ERROR: BIO write %s error",
1204 desc);
1205 ret = -1;
1206 ERR_clear_error ();
1209 else if (i != size)
1211 msg (D_TLS_ERRORS | M_SSL,
1212 "TLS ERROR: BIO write %s incomplete %d/%d", desc, i, size);
1213 ret = -1;
1214 ERR_clear_error ();
1216 else
1217 { /* successful write */
1218 dmsg (D_HANDSHAKE_VERBOSE, "BIO write %s %d bytes", desc, i);
1219 ret = 1;
1222 return ret;
1226 * Read from an OpenSSL BIO in non-blocking mode.
1228 static int
1229 bio_read (struct tls_multi* multi, BIO *bio, struct buffer *buf, int maxlen, const char *desc)
1231 int i;
1232 int ret = 0;
1233 ASSERT (buf->len >= 0);
1234 if (buf->len)
1238 else
1240 int len = buf_forward_capacity (buf);
1241 if (maxlen < len)
1242 len = maxlen;
1245 * BIO_read brackets most of the serious RSA
1246 * key negotiation number crunching.
1248 i = BIO_read (bio, BPTR (buf), len);
1250 VALGRIND_MAKE_READABLE ((void *) &i, sizeof (i));
1252 #ifdef BIO_DEBUG
1253 bio_debug_data ("read", bio, BPTR (buf), i, desc);
1254 #endif
1255 if (i < 0)
1257 if (BIO_should_retry (bio))
1261 else
1263 msg (D_TLS_ERRORS | M_SSL, "TLS_ERROR: BIO read %s error",
1264 desc);
1265 buf->len = 0;
1266 ret = -1;
1267 ERR_clear_error ();
1270 else if (!i)
1272 buf->len = 0;
1274 else
1275 { /* successful read */
1276 dmsg (D_HANDSHAKE_VERBOSE, "BIO read %s %d bytes", desc, i);
1277 buf->len = i;
1278 ret = 1;
1279 VALGRIND_MAKE_READABLE ((void *) BPTR (buf), BLEN (buf));
1282 return ret;
1286 * Inline functions for reading from and writing
1287 * to BIOs.
1290 static void
1291 bio_write_post (const int status, struct buffer *buf)
1293 if (status == 1) /* success status return from bio_write? */
1295 memset (BPTR (buf), 0, BLEN (buf)); /* erase data just written */
1296 buf->len = 0;
1300 static int
1301 key_state_write_plaintext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf)
1303 int ret;
1304 perf_push (PERF_BIO_WRITE_PLAINTEXT);
1305 ret = bio_write (multi, ks->ssl_bio, BPTR(buf), BLEN(buf), "tls_write_plaintext");
1306 bio_write_post (ret, buf);
1307 perf_pop ();
1308 return ret;
1311 static int
1312 key_state_write_plaintext_const (struct tls_multi *multi, struct key_state *ks, const uint8_t *data, int len)
1314 int ret;
1315 perf_push (PERF_BIO_WRITE_PLAINTEXT);
1316 ret = bio_write (multi, ks->ssl_bio, data, len, "tls_write_plaintext_const");
1317 perf_pop ();
1318 return ret;
1321 static int
1322 key_state_write_ciphertext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf)
1324 int ret;
1325 perf_push (PERF_BIO_WRITE_CIPHERTEXT);
1326 ret = bio_write (multi, ks->ct_in, BPTR(buf), BLEN(buf), "tls_write_ciphertext");
1327 bio_write_post (ret, buf);
1328 perf_pop ();
1329 return ret;
1332 static int
1333 key_state_read_plaintext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf,
1334 int maxlen)
1336 int ret;
1337 perf_push (PERF_BIO_READ_PLAINTEXT);
1338 ret = bio_read (multi, ks->ssl_bio, buf, maxlen, "tls_read_plaintext");
1339 perf_pop ();
1340 return ret;
1343 static int
1344 key_state_read_ciphertext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf,
1345 int maxlen)
1347 int ret;
1348 perf_push (PERF_BIO_READ_CIPHERTEXT);
1349 ret = bio_read (multi, ks->ct_out, buf, maxlen, "tls_read_ciphertext");
1350 perf_pop ();
1351 return ret;
1355 * Initialize a key_state. Each key_state corresponds to
1356 * a specific SSL/TLS session.
1358 static void
1359 key_state_init (struct tls_session *session, struct key_state *ks)
1361 update_time ();
1364 * Build TLS object that reads/writes ciphertext
1365 * to/from memory BIOs.
1367 CLEAR (*ks);
1369 ks->ssl = SSL_new (session->opt->ssl_ctx);
1370 if (!ks->ssl)
1371 msg (M_SSLERR, "SSL_new failed");
1373 /* put session * in ssl object so we can access it
1374 from verify callback*/
1375 SSL_set_ex_data (ks->ssl, mydata_index, session);
1377 ks->ssl_bio = getbio (BIO_f_ssl (), "ssl_bio");
1378 ks->ct_in = getbio (BIO_s_mem (), "ct_in");
1379 ks->ct_out = getbio (BIO_s_mem (), "ct_out");
1381 #ifdef BIO_DEBUG
1382 bio_debug_oc ("open ssl_bio", ks->ssl_bio);
1383 bio_debug_oc ("open ct_in", ks->ct_in);
1384 bio_debug_oc ("open ct_out", ks->ct_out);
1385 #endif
1387 if (session->opt->server)
1388 SSL_set_accept_state (ks->ssl);
1389 else
1390 SSL_set_connect_state (ks->ssl);
1392 SSL_set_bio (ks->ssl, ks->ct_in, ks->ct_out);
1393 BIO_set_ssl (ks->ssl_bio, ks->ssl, BIO_NOCLOSE);
1395 /* Set control-channel initiation mode */
1396 ks->initial_opcode = session->initial_opcode;
1397 session->initial_opcode = P_CONTROL_SOFT_RESET_V1;
1398 ks->state = S_INITIAL;
1399 ks->key_id = session->key_id;
1402 * key_id increments to KEY_ID_MASK then recycles back to 1.
1403 * This way you know that if key_id is 0, it is the first key.
1405 ++session->key_id;
1406 session->key_id &= P_KEY_ID_MASK;
1407 if (!session->key_id)
1408 session->key_id = 1;
1410 /* allocate key source material object */
1411 ALLOC_OBJ_CLEAR (ks->key_src, struct key_source2);
1413 /* allocate reliability objects */
1414 ALLOC_OBJ_CLEAR (ks->send_reliable, struct reliable);
1415 ALLOC_OBJ_CLEAR (ks->rec_reliable, struct reliable);
1416 ALLOC_OBJ_CLEAR (ks->rec_ack, struct reliable_ack);
1418 /* allocate buffers */
1419 ks->plaintext_read_buf = alloc_buf (PLAINTEXT_BUFFER_SIZE);
1420 ks->plaintext_write_buf = alloc_buf (PLAINTEXT_BUFFER_SIZE);
1421 ks->ack_write_buf = alloc_buf (BUF_SIZE (&session->opt->frame));
1422 reliable_init (ks->send_reliable, BUF_SIZE (&session->opt->frame),
1423 FRAME_HEADROOM (&session->opt->frame), TLS_RELIABLE_N_SEND_BUFFERS);
1424 reliable_init (ks->rec_reliable, BUF_SIZE (&session->opt->frame),
1425 FRAME_HEADROOM (&session->opt->frame), TLS_RELIABLE_N_REC_BUFFERS);
1426 reliable_set_timeout (ks->send_reliable, session->opt->packet_timeout);
1428 /* init packet ID tracker */
1429 packet_id_init (&ks->packet_id,
1430 session->opt->replay_window,
1431 session->opt->replay_time);
1434 static void
1435 key_state_free (struct key_state *ks, bool clear)
1437 ks->state = S_UNDEF;
1439 if (ks->ssl) {
1440 #ifdef BIO_DEBUG
1441 bio_debug_oc ("close ssl_bio", ks->ssl_bio);
1442 bio_debug_oc ("close ct_in", ks->ct_in);
1443 bio_debug_oc ("close ct_out", ks->ct_out);
1444 #endif
1445 BIO_free_all(ks->ssl_bio);
1446 SSL_free (ks->ssl);
1449 free_key_ctx_bi (&ks->key);
1450 free_buf (&ks->plaintext_read_buf);
1451 free_buf (&ks->plaintext_write_buf);
1452 free_buf (&ks->ack_write_buf);
1454 if (ks->send_reliable)
1456 reliable_free (ks->send_reliable);
1457 free (ks->send_reliable);
1460 if (ks->rec_reliable)
1462 reliable_free (ks->rec_reliable);
1463 free (ks->rec_reliable);
1466 if (ks->rec_ack)
1467 free (ks->rec_ack);
1469 if (ks->key_src)
1470 free (ks->key_src);
1472 packet_id_free (&ks->packet_id);
1474 if (clear)
1475 CLEAR (*ks);
1479 * Must be called if we move a tls_session in memory.
1481 static inline void tls_session_set_self_referential_pointers (struct tls_session* session) {
1482 session->tls_auth.packet_id = &session->tls_auth_pid;
1486 * Initialize a TLS session. A TLS session normally has 2 key_state objects,
1487 * one for the current key, and one for the lame duck (i.e. retiring) key.
1489 static void
1490 tls_session_init (struct tls_multi *multi, struct tls_session *session)
1492 struct gc_arena gc = gc_new ();
1494 dmsg (D_TLS_DEBUG, "TLS: tls_session_init: entry");
1496 CLEAR (*session);
1498 /* Set options data to point to parent's option structure */
1499 session->opt = &multi->opt;
1501 /* Randomize session # if it is 0 */
1502 while (!session_id_defined(&session->session_id))
1503 session_id_random (&session->session_id);
1505 /* Are we a TLS server or client? */
1506 ASSERT (session->opt->key_method >= 1);
1507 if (session->opt->key_method == 1)
1509 session->initial_opcode = session->opt->server ?
1510 P_CONTROL_HARD_RESET_SERVER_V1 : P_CONTROL_HARD_RESET_CLIENT_V1;
1512 else /* session->opt->key_method >= 2 */
1514 session->initial_opcode = session->opt->server ?
1515 P_CONTROL_HARD_RESET_SERVER_V2 : P_CONTROL_HARD_RESET_CLIENT_V2;
1518 /* Initialize control channel authentication parameters */
1519 session->tls_auth = session->opt->tls_auth;
1521 /* Set session internal pointers (also called if session object is moved in memory) */
1522 tls_session_set_self_referential_pointers (session);
1524 /* initialize packet ID replay window for --tls-auth */
1525 packet_id_init (session->tls_auth.packet_id,
1526 session->opt->replay_window,
1527 session->opt->replay_time);
1529 /* load most recent packet-id to replay protect on --tls-auth */
1530 packet_id_persist_load_obj (session->tls_auth.pid_persist, session->tls_auth.packet_id);
1532 key_state_init (session, &session->key[KS_PRIMARY]);
1534 dmsg (D_TLS_DEBUG, "TLS: tls_session_init: new session object, sid=%s",
1535 session_id_print (&session->session_id, &gc));
1537 gc_free (&gc);
1540 static void
1541 tls_session_free (struct tls_session *session, bool clear)
1543 int i;
1545 if (session->tls_auth.packet_id)
1546 packet_id_free (session->tls_auth.packet_id);
1548 for (i = 0; i < KS_SIZE; ++i)
1549 key_state_free (&session->key[i], false);
1551 if (session->common_name)
1552 free (session->common_name);
1554 if (clear)
1555 CLEAR (*session);
1558 static void
1559 move_session (struct tls_multi* multi, int dest, int src, bool reinit_src)
1561 msg (D_TLS_DEBUG_LOW, "TLS: move_session: dest=%s src=%s reinit_src=%d",
1562 session_index_name(dest),
1563 session_index_name(src),
1564 reinit_src);
1565 ASSERT (src != dest);
1566 ASSERT (src >= 0 && src < TM_SIZE);
1567 ASSERT (dest >= 0 && dest < TM_SIZE);
1568 tls_session_free (&multi->session[dest], false);
1569 multi->session[dest] = multi->session[src];
1570 tls_session_set_self_referential_pointers (&multi->session[dest]);
1572 if (reinit_src)
1573 tls_session_init (multi, &multi->session[src]);
1574 else
1575 CLEAR (multi->session[src]);
1577 dmsg (D_TLS_DEBUG, "TLS: move_session: exit");
1580 static void
1581 reset_session (struct tls_multi *multi, struct tls_session *session)
1583 tls_session_free (session, false);
1584 tls_session_init (multi, session);
1587 #if 0
1589 * Transmit a TLS reset on our untrusted channel.
1591 static void
1592 initiate_untrusted_session (struct tls_multi *multi, struct sockaddr_in *to)
1594 struct tls_session *session = &multi->session[TM_UNTRUSTED];
1595 struct key_state *ks = &session->key[KS_PRIMARY];
1597 reset_session (multi, session);
1598 ks->remote_addr = *to;
1599 msg (D_TLS_DEBUG_LOW, "TLS: initiate_untrusted_session: addr=%s", print_sockaddr (to));
1601 #endif
1604 * Used to determine in how many seconds we should be
1605 * called again.
1607 static inline void
1608 compute_earliest_wakeup (interval_t *earliest, interval_t seconds_from_now) {
1609 if (seconds_from_now < *earliest)
1610 *earliest = seconds_from_now;
1611 if (*earliest < 0)
1612 *earliest = 0;
1616 * Return true if "lame duck" or retiring key has expired and can
1617 * no longer be used.
1619 static inline bool
1620 lame_duck_must_die (const struct tls_session* session, interval_t *wakeup)
1622 const struct key_state* lame = &session->key[KS_LAME_DUCK];
1623 if (lame->state >= S_INITIAL)
1625 const time_t local_now = now;
1626 ASSERT (lame->must_die); /* a lame duck key must always have an expiration */
1627 if (local_now < lame->must_die)
1629 compute_earliest_wakeup (wakeup, lame->must_die - local_now);
1630 return false;
1632 else
1633 return true;
1635 else if (lame->state == S_ERROR)
1636 return true;
1637 else
1638 return false;
1642 * A tls_multi object fully encapsulates OpenVPN's TLS state.
1643 * See ssl.h for more comments.
1645 struct tls_multi *
1646 tls_multi_init (struct tls_options *tls_options)
1648 struct tls_multi *ret;
1650 ALLOC_OBJ_CLEAR (ret, struct tls_multi);
1652 /* get command line derived options */
1653 ret->opt = *tls_options;
1655 /* set up pointer to HMAC object for TLS packet authentication */
1656 ret->opt.tls_auth.key_ctx_bi = &ret->opt.tls_auth_key;
1658 /* set up list of keys to be scanned by data channel encrypt and decrypt routines */
1659 ASSERT (SIZE (ret->key_scan) == 3);
1660 ret->key_scan[0] = &ret->session[TM_ACTIVE].key[KS_PRIMARY];
1661 ret->key_scan[1] = &ret->session[TM_ACTIVE].key[KS_LAME_DUCK];
1662 ret->key_scan[2] = &ret->session[TM_LAME_DUCK].key[KS_LAME_DUCK];
1664 return ret;
1668 * Finalize our computation of frame sizes.
1670 void
1671 tls_multi_init_finalize (struct tls_multi* multi, const struct frame* frame)
1673 tls_init_control_channel_frame_parameters (frame, &multi->opt.frame);
1675 /* initialize the active and untrusted sessions */
1677 tls_session_init (multi, &multi->session[TM_ACTIVE]);
1679 if (!multi->opt.single_session)
1680 tls_session_init (multi, &multi->session[TM_UNTRUSTED]);
1684 * Initialize and finalize a standalone tls-auth verification object.
1687 struct tls_auth_standalone *
1688 tls_auth_standalone_init (struct tls_options *tls_options,
1689 struct gc_arena *gc)
1691 struct tls_auth_standalone *tas;
1693 ALLOC_OBJ_CLEAR_GC (tas, struct tls_auth_standalone, gc);
1695 /* set up pointer to HMAC object for TLS packet authentication */
1696 tas->tls_auth_key = tls_options->tls_auth_key;
1697 tas->tls_auth_options.key_ctx_bi = &tas->tls_auth_key;
1698 tas->tls_auth_options.flags |= CO_PACKET_ID_LONG_FORM;
1700 /* get initial frame parms, still need to finalize */
1701 tas->frame = tls_options->frame;
1703 return tas;
1706 void
1707 tls_auth_standalone_finalize (struct tls_auth_standalone *tas,
1708 const struct frame *frame)
1710 tls_init_control_channel_frame_parameters (frame, &tas->frame);
1714 * Set local and remote option compatibility strings.
1715 * Used to verify compatibility of local and remote option
1716 * sets.
1718 void
1719 tls_multi_init_set_options (struct tls_multi* multi,
1720 const char *local,
1721 const char *remote)
1723 #ifdef ENABLE_OCC
1724 /* initialize options string */
1725 multi->opt.local_options = local;
1726 multi->opt.remote_options = remote;
1727 #endif
1730 void
1731 tls_multi_free (struct tls_multi *multi, bool clear)
1733 int i;
1735 ASSERT (multi);
1737 if (multi->locked_cn)
1738 free (multi->locked_cn);
1740 for (i = 0; i < TM_SIZE; ++i)
1741 tls_session_free (&multi->session[i], false);
1743 if (clear)
1744 CLEAR (*multi);
1746 free(multi);
1750 * Move a packet authentication HMAC + related fields to or from the front
1751 * of the buffer so it can be processed by encrypt/decrypt.
1755 * Dependent on hmac size, opcode size, and session_id size.
1756 * Will assert if too small.
1758 #define SWAP_BUF_SIZE 256
1760 static bool
1761 swap_hmac (struct buffer *buf, const struct crypto_options *co, bool incoming)
1763 struct key_ctx *ctx;
1765 ASSERT (co);
1767 ctx = (incoming ? &co->key_ctx_bi->decrypt : &co->key_ctx_bi->encrypt);
1768 ASSERT (ctx->hmac);
1771 /* hmac + packet_id (8 bytes) */
1772 const int hmac_size = HMAC_size (ctx->hmac) + packet_id_size (true);
1774 /* opcode + session_id */
1775 const int osid_size = 1 + SID_SIZE;
1777 int e1, e2;
1778 uint8_t *b = BPTR (buf);
1779 uint8_t buf1[SWAP_BUF_SIZE];
1780 uint8_t buf2[SWAP_BUF_SIZE];
1782 if (incoming)
1784 e1 = osid_size;
1785 e2 = hmac_size;
1787 else
1789 e1 = hmac_size;
1790 e2 = osid_size;
1793 ASSERT (e1 <= SWAP_BUF_SIZE && e2 <= SWAP_BUF_SIZE);
1795 if (buf->len >= e1 + e2)
1797 memcpy (buf1, b, e1);
1798 memcpy (buf2, b + e1, e2);
1799 memcpy (b, buf2, e2);
1800 memcpy (b + e2, buf1, e1);
1801 return true;
1803 else
1804 return false;
1808 #undef SWAP_BUF_SIZE
1811 * Write a control channel authentication record.
1813 static void
1814 write_control_auth (struct tls_session *session,
1815 struct key_state *ks,
1816 struct buffer *buf,
1817 struct sockaddr_in *to_link_addr,
1818 int opcode,
1819 int max_ack,
1820 bool prepend_ack)
1822 uint8_t *header;
1823 struct buffer null = clear_buf ();
1825 ASSERT (addr_defined (&ks->remote_addr));
1826 ASSERT (reliable_ack_write
1827 (ks->rec_ack, buf, &ks->session_id_remote, max_ack, prepend_ack));
1828 ASSERT (session_id_write_prepend (&session->session_id, buf));
1829 ASSERT (header = buf_prepend (buf, 1));
1830 *header = ks->key_id | (opcode << P_OPCODE_SHIFT);
1831 if (session->tls_auth.key_ctx_bi->encrypt.hmac)
1833 /* no encryption, only write hmac */
1834 openvpn_encrypt (buf, null, &session->tls_auth, NULL);
1835 ASSERT (swap_hmac (buf, &session->tls_auth, false));
1837 *to_link_addr = ks->remote_addr;
1841 * Read a control channel authentication record.
1843 static bool
1844 read_control_auth (struct buffer *buf,
1845 const struct crypto_options *co,
1846 const struct sockaddr_in *from)
1848 struct gc_arena gc = gc_new ();
1850 if (co->key_ctx_bi->decrypt.hmac)
1852 struct buffer null = clear_buf ();
1854 /* move the hmac record to the front of the packet */
1855 if (!swap_hmac (buf, co, true))
1857 msg (D_TLS_ERRORS,
1858 "TLS Error: cannot locate HMAC in incoming packet from %s",
1859 print_sockaddr (from, &gc));
1860 gc_free (&gc);
1861 return false;
1864 /* authenticate only (no decrypt) and remove the hmac record
1865 from the head of the buffer */
1866 openvpn_decrypt (buf, null, co, NULL);
1867 if (!buf->len)
1869 msg (D_TLS_ERRORS,
1870 "TLS Error: incoming packet authentication failed from %s",
1871 print_sockaddr (from, &gc));
1872 gc_free (&gc);
1873 return false;
1878 /* advance buffer pointer past opcode & session_id since our caller
1879 already read it */
1880 buf_advance (buf, SID_SIZE + 1);
1882 gc_free (&gc);
1883 return true;
1887 * For debugging, print contents of key_source2 structure.
1890 static void
1891 key_source_print (const struct key_source *k,
1892 const char *prefix)
1894 struct gc_arena gc = gc_new ();
1896 VALGRIND_MAKE_READABLE ((void *)k->pre_master, sizeof (k->pre_master));
1897 VALGRIND_MAKE_READABLE ((void *)k->random1, sizeof (k->random1));
1898 VALGRIND_MAKE_READABLE ((void *)k->random2, sizeof (k->random2));
1900 dmsg (D_SHOW_KEY_SOURCE,
1901 "%s pre_master: %s",
1902 prefix,
1903 format_hex (k->pre_master, sizeof (k->pre_master), 0, &gc));
1904 dmsg (D_SHOW_KEY_SOURCE,
1905 "%s random1: %s",
1906 prefix,
1907 format_hex (k->random1, sizeof (k->random1), 0, &gc));
1908 dmsg (D_SHOW_KEY_SOURCE,
1909 "%s random2: %s",
1910 prefix,
1911 format_hex (k->random2, sizeof (k->random2), 0, &gc));
1913 gc_free (&gc);
1916 static void
1917 key_source2_print (const struct key_source2 *k)
1919 key_source_print (&k->client, "Client");
1920 key_source_print (&k->server, "Server");
1924 * Use the TLS PRF function for generating data channel keys.
1925 * This code is taken from the OpenSSL library.
1927 * TLS generates keys as such:
1929 * master_secret[48] = PRF(pre_master_secret[48], "master secret",
1930 * ClientHello.random[32] + ServerHello.random[32])
1932 * key_block[] = PRF(SecurityParameters.master_secret[48],
1933 * "key expansion",
1934 * SecurityParameters.server_random[32] +
1935 * SecurityParameters.client_random[32]);
1937 * Notes:
1939 * (1) key_block contains a full set of 4 keys.
1940 * (2) The pre-master secret is generated by the client.
1943 static void
1944 tls1_P_hash(const EVP_MD *md,
1945 const uint8_t *sec,
1946 int sec_len,
1947 const uint8_t *seed,
1948 int seed_len,
1949 uint8_t *out,
1950 int olen)
1952 struct gc_arena gc = gc_new ();
1953 int chunk,n;
1954 unsigned int j;
1955 HMAC_CTX ctx;
1956 HMAC_CTX ctx_tmp;
1957 uint8_t A1[EVP_MAX_MD_SIZE];
1958 unsigned int A1_len;
1960 #ifdef ENABLE_DEBUG
1961 const int olen_orig = olen;
1962 const uint8_t *out_orig = out;
1963 #endif
1965 dmsg (D_SHOW_KEY_SOURCE, "tls1_P_hash sec: %s", format_hex (sec, sec_len, 0, &gc));
1966 dmsg (D_SHOW_KEY_SOURCE, "tls1_P_hash seed: %s", format_hex (seed, seed_len, 0, &gc));
1968 chunk=EVP_MD_size(md);
1970 HMAC_CTX_init(&ctx);
1971 HMAC_CTX_init(&ctx_tmp);
1972 HMAC_Init_ex(&ctx,sec,sec_len,md, NULL);
1973 HMAC_Init_ex(&ctx_tmp,sec,sec_len,md, NULL);
1974 HMAC_Update(&ctx,seed,seed_len);
1975 HMAC_Final(&ctx,A1,&A1_len);
1977 n=0;
1978 for (;;)
1980 HMAC_Init_ex(&ctx,NULL,0,NULL,NULL); /* re-init */
1981 HMAC_Init_ex(&ctx_tmp,NULL,0,NULL,NULL); /* re-init */
1982 HMAC_Update(&ctx,A1,A1_len);
1983 HMAC_Update(&ctx_tmp,A1,A1_len);
1984 HMAC_Update(&ctx,seed,seed_len);
1986 if (olen > chunk)
1988 HMAC_Final(&ctx,out,&j);
1989 out+=j;
1990 olen-=j;
1991 HMAC_Final(&ctx_tmp,A1,&A1_len); /* calc the next A1 value */
1993 else /* last one */
1995 HMAC_Final(&ctx,A1,&A1_len);
1996 memcpy(out,A1,olen);
1997 break;
2000 HMAC_CTX_cleanup(&ctx);
2001 HMAC_CTX_cleanup(&ctx_tmp);
2002 CLEAR (A1);
2004 dmsg (D_SHOW_KEY_SOURCE, "tls1_P_hash out: %s", format_hex (out_orig, olen_orig, 0, &gc));
2005 gc_free (&gc);
2008 static void
2009 tls1_PRF(uint8_t *label,
2010 int label_len,
2011 const uint8_t *sec,
2012 int slen,
2013 uint8_t *out1,
2014 int olen)
2016 struct gc_arena gc = gc_new ();
2017 const EVP_MD *md5 = EVP_md5();
2018 const EVP_MD *sha1 = EVP_sha1();
2019 int len,i;
2020 const uint8_t *S1,*S2;
2021 uint8_t *out2;
2023 out2 = (uint8_t *) gc_malloc (olen, false, &gc);
2025 len=slen/2;
2026 S1=sec;
2027 S2= &(sec[len]);
2028 len+=(slen&1); /* add for odd, make longer */
2031 tls1_P_hash(md5 ,S1,len,label,label_len,out1,olen);
2032 tls1_P_hash(sha1,S2,len,label,label_len,out2,olen);
2034 for (i=0; i<olen; i++)
2035 out1[i]^=out2[i];
2037 memset (out2, 0, olen);
2039 dmsg (D_SHOW_KEY_SOURCE, "tls1_PRF out[%d]: %s", olen, format_hex (out1, olen, 0, &gc));
2041 gc_free (&gc);
2044 static void
2045 openvpn_PRF (const uint8_t *secret,
2046 int secret_len,
2047 const char *label,
2048 const uint8_t *client_seed,
2049 int client_seed_len,
2050 const uint8_t *server_seed,
2051 int server_seed_len,
2052 const struct session_id *client_sid,
2053 const struct session_id *server_sid,
2054 uint8_t *output,
2055 int output_len)
2057 /* concatenate seed components */
2059 struct buffer seed = alloc_buf (strlen (label)
2060 + client_seed_len
2061 + server_seed_len
2062 + SID_SIZE * 2);
2064 ASSERT (buf_write (&seed, label, strlen (label)));
2065 ASSERT (buf_write (&seed, client_seed, client_seed_len));
2066 ASSERT (buf_write (&seed, server_seed, server_seed_len));
2068 if (client_sid)
2069 ASSERT (buf_write (&seed, client_sid->id, SID_SIZE));
2070 if (server_sid)
2071 ASSERT (buf_write (&seed, server_sid->id, SID_SIZE));
2073 /* compute PRF */
2074 tls1_PRF (BPTR(&seed), BLEN(&seed), secret, secret_len, output, output_len);
2076 buf_clear (&seed);
2077 free_buf (&seed);
2079 VALGRIND_MAKE_READABLE ((void *)output, output_len);
2083 * Using source entropy from local and remote hosts, mix into
2084 * master key.
2086 static bool
2087 generate_key_expansion (struct key_ctx_bi *key,
2088 const struct key_type *key_type,
2089 const struct key_source2 *key_src,
2090 const struct session_id *client_sid,
2091 const struct session_id *server_sid,
2092 bool server)
2094 uint8_t master[48];
2095 struct key2 key2;
2096 bool ret = false;
2097 int i;
2099 CLEAR (master);
2100 CLEAR (key2);
2102 /* debugging print of source key material */
2103 key_source2_print (key_src);
2105 /* compute master secret */
2106 openvpn_PRF (key_src->client.pre_master,
2107 sizeof(key_src->client.pre_master),
2108 KEY_EXPANSION_ID " master secret",
2109 key_src->client.random1,
2110 sizeof(key_src->client.random1),
2111 key_src->server.random1,
2112 sizeof(key_src->server.random1),
2113 NULL,
2114 NULL,
2115 master,
2116 sizeof(master));
2118 /* compute key expansion */
2119 openvpn_PRF (master,
2120 sizeof(master),
2121 KEY_EXPANSION_ID " key expansion",
2122 key_src->client.random2,
2123 sizeof(key_src->client.random2),
2124 key_src->server.random2,
2125 sizeof(key_src->server.random2),
2126 client_sid,
2127 server_sid,
2128 (uint8_t*)key2.keys,
2129 sizeof(key2.keys));
2131 key2.n = 2;
2133 key2_print (&key2, key_type, "Master Encrypt", "Master Decrypt");
2135 /* check for weak keys */
2136 for (i = 0; i < 2; ++i)
2138 fixup_key (&key2.keys[i], key_type);
2139 if (!check_key (&key2.keys[i], key_type))
2141 msg (D_TLS_ERRORS, "TLS Error: Bad dynamic key generated");
2142 goto exit;
2146 /* Initialize OpenSSL key contexts */
2148 ASSERT (server == true || server == false);
2150 init_key_ctx (&key->encrypt,
2151 &key2.keys[(int)server],
2152 key_type,
2153 DO_ENCRYPT,
2154 "Data Channel Encrypt");
2156 init_key_ctx (&key->decrypt,
2157 &key2.keys[1-(int)server],
2158 key_type,
2159 DO_DECRYPT,
2160 "Data Channel Decrypt");
2162 ret = true;
2164 exit:
2165 CLEAR (master);
2166 CLEAR (key2);
2168 return ret;
2171 static bool
2172 random_bytes_to_buf (struct buffer *buf,
2173 uint8_t *out,
2174 int outlen)
2176 if (!RAND_bytes (out, outlen))
2177 msg (M_FATAL, "ERROR: Random number generator cannot obtain entropy for key generation [SSL]");
2178 if (!buf_write (buf, out, outlen))
2179 return false;
2180 return true;
2183 static bool
2184 key_source2_randomize_write (struct key_source2 *k2,
2185 struct buffer *buf,
2186 bool server)
2188 struct key_source *k = &k2->client;
2189 if (server)
2190 k = &k2->server;
2192 CLEAR (*k);
2194 if (!server)
2196 if (!random_bytes_to_buf (buf, k->pre_master, sizeof (k->pre_master)))
2197 return false;
2200 if (!random_bytes_to_buf (buf, k->random1, sizeof (k->random1)))
2201 return false;
2202 if (!random_bytes_to_buf (buf, k->random2, sizeof (k->random2)))
2203 return false;
2205 return true;
2208 static int
2209 key_source2_read (struct key_source2 *k2,
2210 struct buffer *buf,
2211 bool server)
2213 struct key_source *k = &k2->client;
2215 if (!server)
2216 k = &k2->server;
2218 CLEAR (*k);
2220 if (server)
2222 if (!buf_read (buf, k->pre_master, sizeof (k->pre_master)))
2223 return 0;
2226 if (!buf_read (buf, k->random1, sizeof (k->random1)))
2227 return 0;
2228 if (!buf_read (buf, k->random2, sizeof (k->random2)))
2229 return 0;
2231 return 1;
2235 * Macros for key_state_soft_reset & tls_process
2237 #define ks (&session->key[KS_PRIMARY]) /* primary key */
2238 #define ks_lame (&session->key[KS_LAME_DUCK]) /* retiring key */
2240 /* true if no in/out acknowledgements pending */
2241 #define FULL_SYNC \
2242 (reliable_empty(ks->send_reliable) && reliable_ack_empty (ks->rec_ack))
2245 * Move the active key to the lame duck key and reinitialize the
2246 * active key.
2248 static void
2249 key_state_soft_reset (struct tls_session *session)
2251 ks->must_die = now + session->opt->transition_window; /* remaining lifetime of old key */
2252 key_state_free (ks_lame, false);
2253 *ks_lame = *ks;
2255 key_state_init (session, ks);
2256 ks->session_id_remote = ks_lame->session_id_remote;
2257 ks->remote_addr = ks_lame->remote_addr;
2261 * Read/write strings from/to a struct buffer with a u16 length prefix.
2264 static bool
2265 write_string (struct buffer *buf, const char *str, const int maxlen)
2267 const int len = strlen (str) + 1;
2268 if (len < 1 || (maxlen >= 0 && len > maxlen))
2269 return false;
2270 if (!buf_write_u16 (buf, len))
2271 return false;
2272 if (!buf_write (buf, str, len))
2273 return false;
2274 return true;
2277 static bool
2278 read_string (struct buffer *buf, char *str, const unsigned int capacity)
2280 const int len = buf_read_u16 (buf);
2281 if (len < 1 || len > (int)capacity)
2282 return false;
2283 if (!buf_read (buf, str, len))
2284 return false;
2285 str[len-1] = '\0';
2286 return true;
2290 * Authenticate a client using username/password.
2291 * Runs on server.
2293 * If you want to add new authentication methods,
2294 * this is the place to start.
2297 static bool
2298 verify_user_pass_script (struct tls_session *session, const struct user_pass *up)
2300 struct gc_arena gc = gc_new ();
2301 struct buffer cmd = alloc_buf_gc (256, &gc);
2302 const char *tmp_file = "";
2303 int retval;
2304 bool ret = false;
2306 /* Is username defined? */
2307 if (strlen (up->username))
2309 /* Set environmental variables prior to calling script */
2310 setenv_str (session->opt->es, "script_type", "user-pass-verify");
2312 if (session->opt->auth_user_pass_verify_script_via_file)
2314 struct status_output *so;
2316 tmp_file = create_temp_filename (session->opt->tmp_dir, &gc);
2317 so = status_open (tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
2318 status_printf (so, "%s", up->username);
2319 status_printf (so, "%s", up->password);
2320 if (!status_close (so))
2322 msg (D_TLS_ERRORS, "TLS Auth Error: could not write username/password to file: %s",
2323 tmp_file);
2324 goto done;
2327 else
2329 setenv_str (session->opt->es, "username", up->username);
2330 setenv_str (session->opt->es, "password", up->password);
2333 /* setenv incoming cert common name for script */
2334 setenv_str (session->opt->es, "common_name", session->common_name);
2336 /* setenv client real IP address */
2337 setenv_untrusted (session);
2339 /* format command line */
2340 buf_printf (&cmd, "%s %s", session->opt->auth_user_pass_verify_script, tmp_file);
2342 /* call command */
2343 retval = openvpn_system (BSTR (&cmd), session->opt->es, S_SCRIPT);
2345 /* test return status of command */
2346 if (system_ok (retval))
2347 ret = true;
2348 else if (!system_executed (retval))
2349 msg (D_TLS_ERRORS, "TLS Auth Error: user-pass-verify script failed to execute: %s", BSTR (&cmd));
2351 if (!session->opt->auth_user_pass_verify_script_via_file)
2352 setenv_del (session->opt->es, "password");
2354 else
2356 msg (D_TLS_ERRORS, "TLS Auth Error: peer provided a blank username");
2359 done:
2360 if (strlen (tmp_file) > 0)
2361 delete_file (tmp_file);
2363 gc_free (&gc);
2364 return ret;
2367 static bool
2368 verify_user_pass_plugin (struct tls_session *session, const struct user_pass *up, const char *raw_username)
2370 int retval;
2371 bool ret = false;
2373 /* Is username defined? */
2374 if (strlen (up->username))
2376 /* set username/password in private env space */
2377 setenv_str (session->opt->es, "username", raw_username);
2378 setenv_str (session->opt->es, "password", up->password);
2380 /* setenv incoming cert common name for script */
2381 setenv_str (session->opt->es, "common_name", session->common_name);
2383 /* setenv client real IP address */
2384 setenv_untrusted (session);
2386 /* call command */
2387 retval = plugin_call (session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY, NULL, session->opt->es);
2389 if (!retval)
2390 ret = true;
2392 setenv_del (session->opt->es, "password");
2393 setenv_str (session->opt->es, "username", up->username);
2395 else
2397 msg (D_TLS_ERRORS, "TLS Auth Error: peer provided a blank username");
2400 return ret;
2404 * Handle the reading and writing of key data to and from
2405 * the TLS control channel (cleartext).
2408 static bool
2409 key_method_1_write (struct buffer *buf, struct tls_session *session)
2411 struct key key;
2413 ASSERT (session->opt->key_method == 1);
2414 ASSERT (buf_init (buf, 0));
2416 generate_key_random (&key, &session->opt->key_type);
2417 if (!check_key (&key, &session->opt->key_type))
2419 msg (D_TLS_ERRORS, "TLS Error: Bad encrypting key generated");
2420 return false;
2423 if (!write_key (&key, &session->opt->key_type, buf))
2425 msg (D_TLS_ERRORS, "TLS Error: write_key failed");
2426 return false;
2429 init_key_ctx (&ks->key.encrypt, &key, &session->opt->key_type,
2430 DO_ENCRYPT, "Data Channel Encrypt");
2431 CLEAR (key);
2433 /* send local options string */
2435 const char *local_options = local_options_string (session);
2436 const int optlen = strlen (local_options) + 1;
2437 if (!buf_write (buf, local_options, optlen))
2439 msg (D_TLS_ERRORS, "TLS Error: KM1 write options failed");
2440 return false;
2444 return true;
2447 static bool
2448 key_method_2_write (struct buffer *buf, struct tls_session *session)
2450 ASSERT (session->opt->key_method == 2);
2451 ASSERT (buf_init (buf, 0));
2453 /* write a uint32 0 */
2454 if (!buf_write_u32 (buf, 0))
2455 goto error;
2457 /* write key_method + flags */
2458 if (!buf_write_u8 (buf, (session->opt->key_method & KEY_METHOD_MASK)))
2459 goto error;
2461 /* write key source material */
2462 if (!key_source2_randomize_write (ks->key_src, buf, session->opt->server))
2463 goto error;
2465 /* write options string */
2467 if (!write_string (buf, local_options_string (session), TLS_OPTIONS_LEN))
2468 goto error;
2471 /* write username/password if specified */
2472 if (auth_user_pass_enabled)
2474 auth_user_pass_setup (NULL);
2475 if (!write_string (buf, auth_user_pass.username, -1))
2476 goto error;
2477 if (!write_string (buf, auth_user_pass.password, -1))
2478 goto error;
2479 purge_user_pass (&auth_user_pass, false);
2483 * generate tunnel keys if server
2485 if (session->opt->server)
2487 if (ks->authenticated)
2489 if (!generate_key_expansion (&ks->key,
2490 &session->opt->key_type,
2491 ks->key_src,
2492 &ks->session_id_remote,
2493 &session->session_id,
2494 true))
2496 msg (D_TLS_ERRORS, "TLS Error: server generate_key_expansion failed");
2497 goto error;
2501 CLEAR (*ks->key_src);
2504 return true;
2506 error:
2507 msg (D_TLS_ERRORS, "TLS Error: Key Method #2 write failed");
2508 CLEAR (*ks->key_src);
2509 return false;
2512 static bool
2513 key_method_1_read (struct buffer *buf, struct tls_session *session)
2515 int status;
2516 struct key key;
2518 ASSERT (session->opt->key_method == 1);
2520 if (!session->verified)
2522 msg (D_TLS_ERRORS,
2523 "TLS Error: Certificate verification failed (key-method 1)");
2524 goto error;
2527 status = read_key (&key, &session->opt->key_type, buf);
2528 if (status != 1)
2530 msg (D_TLS_ERRORS,
2531 "TLS Error: Error reading data channel key from plaintext buffer");
2532 goto error;
2535 if (!check_key (&key, &session->opt->key_type))
2537 msg (D_TLS_ERRORS, "TLS Error: Bad decrypting key received from peer");
2538 goto error;
2541 if (buf->len < 1)
2543 msg (D_TLS_ERRORS, "TLS Error: Missing options string");
2544 goto error;
2547 #ifdef ENABLE_OCC
2548 /* compare received remote options string
2549 with our locally computed options string */
2550 if (!session->opt->disable_occ &&
2551 !options_cmp_equal_safe ((char *) BPTR (buf), session->opt->remote_options, buf->len))
2553 options_warning_safe ((char *) BPTR (buf), session->opt->remote_options, buf->len);
2555 #endif
2557 buf_clear (buf);
2559 init_key_ctx (&ks->key.decrypt, &key, &session->opt->key_type,
2560 DO_DECRYPT, "Data Channel Decrypt");
2561 CLEAR (key);
2562 ks->authenticated = true;
2563 return true;
2565 error:
2566 buf_clear (buf);
2567 CLEAR (key);
2568 return false;
2571 static bool
2572 key_method_2_read (struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
2574 struct gc_arena gc = gc_new ();
2575 int key_method_flags;
2576 char *options;
2577 struct user_pass *up;
2579 ASSERT (session->opt->key_method == 2);
2581 /* allocate temporary objects */
2582 ALLOC_ARRAY_CLEAR_GC (options, char, TLS_OPTIONS_LEN, &gc);
2584 /* discard leading uint32 */
2585 ASSERT (buf_advance (buf, 4));
2587 /* get key method */
2588 key_method_flags = buf_read_u8 (buf);
2589 if ((key_method_flags & KEY_METHOD_MASK) != 2)
2591 msg (D_TLS_ERRORS,
2592 "TLS ERROR: Unknown key_method/flags=%d received from remote host",
2593 key_method_flags);
2594 goto error;
2597 /* get key source material (not actual keys yet) */
2598 if (!key_source2_read (ks->key_src, buf, session->opt->server))
2600 msg (D_TLS_ERRORS, "TLS Error: Error reading remote data channel key source entropy from plaintext buffer");
2601 goto error;
2604 /* get options */
2605 if (!read_string (buf, options, TLS_OPTIONS_LEN))
2607 msg (D_TLS_ERRORS, "TLS Error: Failed to read required OCC options string");
2608 goto error;
2611 /* should we check username/password? */
2612 ks->authenticated = false;
2613 if (session->opt->auth_user_pass_verify_script
2614 || plugin_defined (session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY))
2616 bool s1 = true;
2617 bool s2 = true;
2618 char *raw_username;
2620 /* get username/password from plaintext buffer */
2621 ALLOC_OBJ_CLEAR_GC (up, struct user_pass, &gc);
2622 if (!read_string (buf, up->username, USER_PASS_LEN)
2623 || !read_string (buf, up->password, USER_PASS_LEN))
2625 msg (D_TLS_ERRORS, "TLS Error: Auth Username/Password was not provided by peer");
2626 CLEAR (*up);
2627 goto error;
2630 /* preserve raw username before string_mod remapping, for plugins */
2631 ALLOC_ARRAY_CLEAR_GC (raw_username, char, USER_PASS_LEN, &gc);
2632 strcpy (raw_username, up->username);
2633 string_mod (raw_username, CC_PRINT, CC_CRLF, '_');
2635 /* enforce character class restrictions in username/password */
2636 string_mod (up->username, COMMON_NAME_CHAR_CLASS, 0, '_');
2637 string_mod (up->password, CC_PRINT, CC_CRLF, '_');
2639 /* call plugin(s) and/or script */
2640 if (plugin_defined (session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY))
2641 s1 = verify_user_pass_plugin (session, up, raw_username);
2642 if (session->opt->auth_user_pass_verify_script)
2643 s2 = verify_user_pass_script (session, up);
2645 /* auth succeeded? */
2646 if (s1 && s2)
2648 ks->authenticated = true;
2649 if (session->opt->username_as_common_name)
2650 set_common_name (session, up->username);
2651 msg (D_HANDSHAKE, "TLS: Username/Password authentication succeeded for username '%s' %s",
2652 up->username,
2653 session->opt->username_as_common_name ? "[CN SET]" : "");
2655 else
2657 msg (D_TLS_ERRORS, "TLS Auth Error: Auth Username/Password verification failed for peer");
2660 CLEAR (*up);
2662 else
2664 if (!session->verified)
2666 msg (D_TLS_ERRORS,
2667 "TLS Error: Certificate verification failed (key-method 2)");
2668 goto error;
2670 ks->authenticated = true;
2673 /* While it shouldn't really happen, don't allow the common name to be NULL */
2674 if (!session->common_name)
2675 set_common_name (session, "");
2677 /* Don't allow the CN to change once it's been locked */
2678 if (ks->authenticated && multi->locked_cn)
2680 const char *cn = session->common_name;
2681 if (cn && strcmp (cn, multi->locked_cn))
2683 msg (D_TLS_ERRORS, "TLS Auth Error: TLS object CN attempted to change from '%s' to '%s' -- tunnel disabled",
2684 multi->locked_cn,
2685 cn);
2687 /* change the common name back to its original value and disable the tunnel */
2688 set_common_name (session, multi->locked_cn);
2689 tls_deauthenticate (multi);
2693 /* verify --client-config-dir based authentication */
2694 if (ks->authenticated && session->opt->client_config_dir_exclusive)
2696 const char *cn = session->common_name;
2697 const char *path = gen_path (session->opt->client_config_dir_exclusive, cn, &gc);
2698 if (!cn || !strcmp (cn, CCD_DEFAULT) || !test_file (path))
2700 ks->authenticated = false;
2701 msg (D_TLS_ERRORS, "TLS Auth Error: --client-config-dir authentication failed for common name '%s' file='%s'",
2702 session->common_name,
2703 path ? path : "UNDEF");
2707 #ifdef ENABLE_OCC
2708 /* check options consistency */
2709 if (!session->opt->disable_occ &&
2710 !options_cmp_equal (options, session->opt->remote_options))
2712 options_warning (options, session->opt->remote_options);
2714 #endif
2716 buf_clear (buf);
2719 * generate tunnel keys if client
2721 if (!session->opt->server)
2723 if (!generate_key_expansion (&ks->key,
2724 &session->opt->key_type,
2725 ks->key_src,
2726 &session->session_id,
2727 &ks->session_id_remote,
2728 false))
2730 msg (D_TLS_ERRORS, "TLS Error: client generate_key_expansion failed");
2731 goto error;
2734 CLEAR (*ks->key_src);
2737 gc_free (&gc);
2738 return true;
2740 error:
2741 CLEAR (*ks->key_src);
2742 buf_clear (buf);
2743 gc_free (&gc);
2744 return false;
2748 * This is the primary routine for processing TLS stuff inside the
2749 * the main event loop. When this routine exits
2750 * with non-error status, it will set *wakeup to the number of seconds
2751 * when it wants to be called again.
2753 * Return value is true if we have placed a packet in *to_link which we
2754 * want to send to our peer.
2756 static bool
2757 tls_process (struct tls_multi *multi,
2758 struct tls_session *session,
2759 struct buffer *to_link,
2760 struct sockaddr_in *to_link_addr,
2761 struct link_socket_info *to_link_socket_info,
2762 interval_t *wakeup)
2764 struct gc_arena gc = gc_new ();
2765 struct buffer *buf;
2766 bool state_change = false;
2767 bool active = false;
2769 /* Make sure we were initialized and that we're not in an error state */
2770 ASSERT (ks->state != S_UNDEF);
2771 ASSERT (ks->state != S_ERROR);
2772 ASSERT (session_id_defined (&session->session_id));
2774 /* Should we trigger a soft reset? -- new key, keeps old key for a while */
2775 if (ks->state >= S_ACTIVE &&
2776 ((session->opt->renegotiate_seconds
2777 && now >= ks->established + session->opt->renegotiate_seconds)
2778 || (session->opt->renegotiate_bytes
2779 && ks->n_bytes >= session->opt->renegotiate_bytes)
2780 || (session->opt->renegotiate_packets
2781 && ks->n_packets >= session->opt->renegotiate_packets)
2782 || (packet_id_close_to_wrapping (&ks->packet_id.send))))
2784 msg (D_TLS_DEBUG_LOW, "TLS: soft reset sec=%d bytes=%d/%d pkts=%d/%d",
2785 (int)(ks->established + session->opt->renegotiate_seconds - now),
2786 ks->n_bytes, session->opt->renegotiate_bytes,
2787 ks->n_packets, session->opt->renegotiate_packets);
2788 key_state_soft_reset (session);
2791 /* Kill lame duck key transition_window seconds after primary key negotiation */
2792 if (lame_duck_must_die (session, wakeup)) {
2793 key_state_free (ks_lame, true);
2794 msg (D_TLS_DEBUG_LOW, "TLS: tls_process: killed expiring key");
2797 /*mutex_cycle (multi->mutex);*/
2801 update_time ();
2803 dmsg (D_TLS_DEBUG, "TLS: tls_process: chg=%d ks=%s lame=%s to_link->len=%d wakeup=%d",
2804 state_change,
2805 state_name (ks->state),
2806 state_name (ks_lame->state),
2807 to_link->len,
2808 *wakeup);
2810 state_change = false;
2813 * TLS activity is finished once we get to S_ACTIVE,
2814 * though we will still process acknowledgements.
2816 * CHANGED with 2.0 -> now we may send tunnel configuration
2817 * info over the control channel.
2819 if (true)
2821 /* Initial handshake */
2822 if (ks->state == S_INITIAL)
2824 buf = reliable_get_buf_output_sequenced (ks->send_reliable);
2825 if (buf)
2827 ks->must_negotiate = now + session->opt->handshake_window;
2829 /* null buffer */
2830 reliable_mark_active_outgoing (ks->send_reliable, buf, ks->initial_opcode);
2831 INCR_GENERATED;
2833 ks->state = S_PRE_START;
2834 state_change = true;
2835 dmsg (D_TLS_DEBUG, "TLS: Initial Handshake, sid=%s",
2836 session_id_print (&session->session_id, &gc));
2838 #ifdef ENABLE_MANAGEMENT
2839 if (management && ks->initial_opcode != P_CONTROL_SOFT_RESET_V1)
2841 management_set_state (management,
2842 OPENVPN_STATE_WAIT,
2843 NULL,
2846 #endif
2850 /* Are we timed out on receive? */
2851 if (now >= ks->must_negotiate)
2853 if (ks->state < S_ACTIVE)
2855 msg (D_TLS_ERRORS,
2856 "TLS Error: TLS key negotiation failed to occur within %d seconds (check your network connectivity)",
2857 session->opt->handshake_window);
2858 goto error;
2860 else /* assume that ks->state == S_ACTIVE */
2862 dmsg (D_TLS_DEBUG_MED, "STATE S_NORMAL");
2863 ks->state = S_NORMAL;
2864 ks->must_negotiate = 0;
2868 /* Wait for Initial Handshake ACK */
2869 if (ks->state == S_PRE_START && FULL_SYNC)
2871 ks->state = S_START;
2872 state_change = true;
2873 dmsg (D_TLS_DEBUG_MED, "STATE S_START");
2876 /* Wait for ACK */
2877 if (((ks->state == S_GOT_KEY && !session->opt->server) ||
2878 (ks->state == S_SENT_KEY && session->opt->server)))
2880 if (FULL_SYNC)
2882 ks->established = now;
2883 dmsg (D_TLS_DEBUG_MED, "STATE S_ACTIVE");
2884 if (check_debug_level (D_HANDSHAKE))
2885 print_details (ks->ssl, "Control Channel:");
2886 state_change = true;
2887 ks->state = S_ACTIVE;
2888 INCR_SUCCESS;
2890 /* Set outgoing address for data channel packets */
2891 link_socket_set_outgoing_addr (NULL, to_link_socket_info, &ks->remote_addr, session->common_name, session->opt->es);
2893 #ifdef MEASURE_TLS_HANDSHAKE_STATS
2894 show_tls_performance_stats();
2895 #endif
2899 /* Reliable buffer to outgoing TCP/UDP (send up to CONTROL_SEND_ACK_MAX ACKs
2900 for previously received packets) */
2901 if (!to_link->len && reliable_can_send (ks->send_reliable))
2903 int opcode;
2904 struct buffer b;
2906 buf = reliable_send (ks->send_reliable, &opcode);
2907 ASSERT (buf);
2908 b = *buf;
2909 INCR_SENT;
2911 write_control_auth (session, ks, &b, to_link_addr, opcode,
2912 CONTROL_SEND_ACK_MAX, true);
2913 *to_link = b;
2914 active = true;
2915 state_change = true;
2916 dmsg (D_TLS_DEBUG, "Reliable -> TCP/UDP");
2917 break;
2920 #ifndef TLS_AGGREGATE_ACK
2921 /* Send 1 or more ACKs (each received control packet gets one ACK) */
2922 if (!to_link->len && !reliable_ack_empty (ks->rec_ack))
2924 buf = &ks->ack_write_buf;
2925 ASSERT (buf_init (buf, FRAME_HEADROOM (&multi->opt.frame)));
2926 write_control_auth (session, ks, buf, to_link_addr, P_ACK_V1,
2927 RELIABLE_ACK_SIZE, false);
2928 *to_link = *buf;
2929 active = true;
2930 state_change = true;
2931 dmsg (D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP");
2932 break;
2934 #endif
2936 /* Write incoming ciphertext to TLS object */
2937 buf = reliable_get_buf_sequenced (ks->rec_reliable);
2938 if (buf)
2940 int status = 0;
2941 if (buf->len)
2943 status = key_state_write_ciphertext (multi, ks, buf);
2944 if (status == -1)
2946 msg (D_TLS_ERRORS,
2947 "TLS Error: Incoming Ciphertext -> TLS object write error");
2948 goto error;
2951 else
2953 status = 1;
2955 if (status == 1)
2957 reliable_mark_deleted (ks->rec_reliable, buf, true);
2958 state_change = true;
2959 dmsg (D_TLS_DEBUG, "Incoming Ciphertext -> TLS");
2963 /* Read incoming plaintext from TLS object */
2964 buf = &ks->plaintext_read_buf;
2965 if (!buf->len)
2967 int status;
2969 ASSERT (buf_init (buf, 0));
2970 status = key_state_read_plaintext (multi, ks, buf, PLAINTEXT_BUFFER_SIZE);
2971 update_time ();
2972 if (status == -1)
2974 msg (D_TLS_ERRORS, "TLS Error: TLS object -> incoming plaintext read error");
2975 goto error;
2977 if (status == 1)
2979 state_change = true;
2980 dmsg (D_TLS_DEBUG, "TLS -> Incoming Plaintext");
2982 #if 0 /* show null plaintext reads */
2983 if (!status)
2984 msg (M_INFO, "TLS plaintext read -> NULL return");
2985 #endif
2988 /* Send Key */
2989 buf = &ks->plaintext_write_buf;
2990 if (!buf->len && ((ks->state == S_START && !session->opt->server) ||
2991 (ks->state == S_GOT_KEY && session->opt->server)))
2993 if (session->opt->key_method == 1)
2995 if (!key_method_1_write (buf, session))
2996 goto error;
2998 else if (session->opt->key_method == 2)
3000 if (!key_method_2_write (buf, session))
3001 goto error;
3003 else
3005 ASSERT (0);
3008 state_change = true;
3009 dmsg (D_TLS_DEBUG_MED, "STATE S_SENT_KEY");
3010 ks->state = S_SENT_KEY;
3013 /* Receive Key */
3014 buf = &ks->plaintext_read_buf;
3015 if (buf->len
3016 && ((ks->state == S_SENT_KEY && !session->opt->server)
3017 || (ks->state == S_START && session->opt->server)))
3019 if (session->opt->key_method == 1)
3021 if (!key_method_1_read (buf, session))
3022 goto error;
3024 else if (session->opt->key_method == 2)
3026 if (!key_method_2_read (buf, multi, session))
3027 goto error;
3029 else
3031 ASSERT (0);
3034 state_change = true;
3035 dmsg (D_TLS_DEBUG_MED, "STATE S_GOT_KEY");
3036 ks->state = S_GOT_KEY;
3039 /* Write outgoing plaintext to TLS object */
3040 buf = &ks->plaintext_write_buf;
3041 if (buf->len)
3043 int status = key_state_write_plaintext (multi, ks, buf);
3044 if (status == -1)
3046 msg (D_TLS_ERRORS,
3047 "TLS ERROR: Outgoing Plaintext -> TLS object write error");
3048 goto error;
3050 if (status == 1)
3052 state_change = true;
3053 dmsg (D_TLS_DEBUG, "Outgoing Plaintext -> TLS");
3057 /* Outgoing Ciphertext to reliable buffer */
3058 if (ks->state >= S_START)
3060 buf = reliable_get_buf_output_sequenced (ks->send_reliable);
3061 if (buf)
3063 int status = key_state_read_ciphertext (multi, ks, buf, PAYLOAD_SIZE_DYNAMIC (&multi->opt.frame));
3064 if (status == -1)
3066 msg (D_TLS_ERRORS,
3067 "TLS Error: Ciphertext -> reliable TCP/UDP transport read error");
3068 goto error;
3070 if (status == 1)
3072 reliable_mark_active_outgoing (ks->send_reliable, buf, P_CONTROL_V1);
3073 INCR_GENERATED;
3074 state_change = true;
3075 dmsg (D_TLS_DEBUG, "Outgoing Ciphertext -> Reliable");
3080 /*mutex_cycle (multi->mutex);*/
3082 while (state_change);
3084 update_time ();
3086 #ifdef TLS_AGGREGATE_ACK
3087 /* Send 1 or more ACKs (each received control packet gets one ACK) */
3088 if (!to_link->len && !reliable_ack_empty (ks->rec_ack))
3090 buf = &ks->ack_write_buf;
3091 ASSERT (buf_init (buf, FRAME_HEADROOM (&multi->opt.frame)));
3092 write_control_auth (session, ks, buf, to_link_addr, P_ACK_V1,
3093 RELIABLE_ACK_SIZE, false);
3094 *to_link = *buf;
3095 active = true;
3096 state_change = true;
3097 dmsg (D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP");
3099 #endif
3101 /* When should we wake up again? */
3103 if (ks->state >= S_INITIAL)
3105 compute_earliest_wakeup (wakeup,
3106 reliable_send_timeout (ks->send_reliable));
3108 if (ks->must_negotiate)
3109 compute_earliest_wakeup (wakeup, ks->must_negotiate - now);
3112 if (ks->established && session->opt->renegotiate_seconds)
3113 compute_earliest_wakeup (wakeup,
3114 ks->established + session->opt->renegotiate_seconds - now);
3116 /* prevent event-loop spinning by setting minimum wakeup of 1 second */
3117 if (*wakeup <= 0)
3119 *wakeup = 1;
3121 /* if we had something to send to remote, but to_link was busy,
3122 let caller know we need to be called again soon */
3123 active = true;
3126 dmsg (D_TLS_DEBUG, "TLS: tls_process: timeout set to %d", *wakeup);
3128 gc_free (&gc);
3129 return active;
3132 error:
3133 ERR_clear_error ();
3134 ks->state = S_ERROR;
3135 msg (D_TLS_ERRORS, "TLS Error: TLS handshake failed");
3136 INCR_ERROR;
3137 gc_free (&gc);
3138 return false;
3141 #undef ks
3142 #undef ks_lame
3145 * Called by the top-level event loop.
3147 * Basically decides if we should call tls_process for
3148 * the active or untrusted sessions.
3151 bool
3152 tls_multi_process (struct tls_multi *multi,
3153 struct buffer *to_link,
3154 struct sockaddr_in *to_link_addr,
3155 struct link_socket_info *to_link_socket_info,
3156 interval_t *wakeup)
3158 struct gc_arena gc = gc_new ();
3159 int i;
3160 bool active = false;
3161 bool error = false;
3163 perf_push (PERF_TLS_MULTI_PROCESS);
3165 ERR_clear_error ();
3168 * Process each session object having state of S_INITIAL or greater,
3169 * and which has a defined remote IP addr.
3172 for (i = 0; i < TM_SIZE; ++i)
3174 struct tls_session *session = &multi->session[i];
3175 struct key_state *ks = &session->key[KS_PRIMARY];
3176 struct key_state *ks_lame = &session->key[KS_LAME_DUCK];
3178 /* set initial remote address */
3179 if (i == TM_ACTIVE && ks->state == S_INITIAL &&
3180 addr_defined (&to_link_socket_info->lsa->actual))
3181 ks->remote_addr = to_link_socket_info->lsa->actual;
3183 dmsg (D_TLS_DEBUG,
3184 "TLS: tls_multi_process: i=%d state=%s, mysid=%s, stored-sid=%s, stored-ip=%s",
3186 state_name (ks->state),
3187 session_id_print (&session->session_id, &gc),
3188 session_id_print (&ks->session_id_remote, &gc),
3189 print_sockaddr (&ks->remote_addr, &gc));
3191 if (ks->state >= S_INITIAL && addr_defined (&ks->remote_addr))
3193 update_time ();
3195 if (tls_process (multi, session, to_link, to_link_addr,
3196 to_link_socket_info, wakeup))
3197 active = true;
3200 * If tls_process hits an error:
3201 * (1) If the session has an unexpired lame duck key, preserve it.
3202 * (2) Reinitialize the session.
3203 * (3) Increment soft error count
3205 if (ks->state == S_ERROR)
3207 ++multi->n_soft_errors;
3209 if (i == TM_ACTIVE)
3210 error = true;
3212 if (i == TM_ACTIVE
3213 && ks_lame->state >= S_ACTIVE
3214 && !multi->opt.single_session)
3215 move_session (multi, TM_LAME_DUCK, TM_ACTIVE, true);
3216 else
3217 reset_session (multi, session);
3220 /*mutex_cycle (multi->mutex);*/
3223 update_time ();
3226 * If lame duck session expires, kill it.
3228 if (lame_duck_must_die (&multi->session[TM_LAME_DUCK], wakeup)) {
3229 tls_session_free (&multi->session[TM_LAME_DUCK], true);
3230 msg (D_TLS_DEBUG_LOW, "TLS: tls_multi_process: killed expiring key");
3234 * If untrusted session achieves TLS authentication,
3235 * move it to active session, usurping any prior session.
3237 * A semi-trusted session is one in which the certificate authentication
3238 * succeeded (if cert verification is enabled) but the username/password
3239 * verification failed. A semi-trusted session can forward data on the
3240 * TLS control channel but not on the tunnel channel.
3242 if (DECRYPT_KEY_ENABLED (multi, &multi->session[TM_UNTRUSTED].key[KS_PRIMARY])) {
3243 move_session (multi, TM_ACTIVE, TM_UNTRUSTED, true);
3244 msg (D_TLS_DEBUG_LOW, "TLS: tls_multi_process: untrusted session promoted to %strusted",
3245 tls_authenticated (multi) ? "" : "semi-");
3249 * A hard error means that TM_ACTIVE hit an S_ERROR state and that no
3250 * other key state objects are S_ACTIVE or higher.
3252 if (error)
3254 for (i = 0; i < (int) SIZE (multi->key_scan); ++i)
3256 if (multi->key_scan[i]->state >= S_ACTIVE)
3257 goto nohard;
3259 ++multi->n_hard_errors;
3261 nohard:
3263 #ifdef ENABLE_DEBUG
3264 /* DEBUGGING -- flood peer with repeating connection attempts */
3266 const int throw_level = GREMLIN_CONNECTION_FLOOD_LEVEL (multi->opt.gremlin);
3267 if (throw_level)
3269 for (i = 0; i < (int) SIZE (multi->key_scan); ++i)
3271 if (multi->key_scan[i]->state >= throw_level)
3273 ++multi->n_hard_errors;
3274 ++multi->n_soft_errors;
3279 #endif
3281 perf_pop ();
3282 gc_free (&gc);
3283 return active;
3287 * Pre and post-process the encryption & decryption buffers in order
3288 * to implement a multiplexed TLS channel over the TCP/UDP port.
3293 * When we are in TLS mode, this is the first routine which sees
3294 * an incoming packet.
3296 * If it's a data packet, we set opt so that our caller can
3297 * decrypt it. We also give our caller the appropriate decryption key.
3299 * If it's a control packet, we authenticate it and process it,
3300 * possibly creating a new tls_session if it represents the
3301 * first packet of a new session. For control packets, we will
3302 * also zero the size of *buf so that our caller ignores the
3303 * packet on our return.
3305 * Note that openvpn only allows one active session at a time,
3306 * so a new session (once authenticated) will always usurp
3307 * an old session.
3309 * Return true if input was an authenticated control channel
3310 * packet.
3312 * If we are running in TLS thread mode, all public routines
3313 * below this point must be called with the L_TLS lock held.
3316 bool
3317 tls_pre_decrypt (struct tls_multi *multi,
3318 struct sockaddr_in *from,
3319 struct buffer *buf,
3320 struct crypto_options *opt)
3322 struct gc_arena gc = gc_new ();
3323 bool ret = false;
3325 if (buf->len > 0)
3327 int i;
3328 int op;
3329 int key_id;
3331 /* get opcode and key ID */
3333 uint8_t c = *BPTR (buf);
3334 op = c >> P_OPCODE_SHIFT;
3335 key_id = c & P_KEY_ID_MASK;
3338 if (op == P_DATA_V1)
3339 { /* data channel packet */
3340 for (i = 0; i < KEY_SCAN_SIZE; ++i)
3342 struct key_state *ks = multi->key_scan[i];
3345 * This is the basic test of TLS state compatibility between a local OpenVPN
3346 * instance and its remote peer.
3348 * If the test fails, it tells us that we are getting a packet from a source
3349 * which claims reference to a prior negotiated TLS session, but the local
3350 * OpenVPN instance has no memory of such a negotiation.
3352 * It almost always occurs on UDP sessions when the passive side of the
3353 * connection is restarted without the active side restarting as well (the
3354 * passive side is the server which only listens for the connections, the
3355 * active side is the client which initiates connections).
3357 if (DECRYPT_KEY_ENABLED (multi, ks)
3358 && key_id == ks->key_id
3359 && ks->authenticated
3360 && addr_port_match(from, &ks->remote_addr))
3362 /* return appropriate data channel decrypt key in opt */
3363 opt->key_ctx_bi = &ks->key;
3364 opt->packet_id = multi->opt.replay ? &ks->packet_id : NULL;
3365 opt->pid_persist = NULL;
3366 opt->flags &= multi->opt.crypto_flags_and;
3367 opt->flags |= multi->opt.crypto_flags_or;
3368 ASSERT (buf_advance (buf, 1));
3369 ++ks->n_packets;
3370 ks->n_bytes += buf->len;
3371 dmsg (D_TLS_DEBUG,
3372 "TLS: data channel, key_id=%d, IP=%s",
3373 key_id, print_sockaddr (from, &gc));
3374 gc_free (&gc);
3375 return ret;
3377 #if 0 /* keys out of sync? */
3378 else
3380 dmsg (D_TLS_DEBUG, "TLS_PRE_DECRYPT: [%d] dken=%d rkid=%d lkid=%d auth=%d match=%d",
3382 DECRYPT_KEY_ENABLED (multi, ks),
3383 key_id,
3384 ks->key_id,
3385 ks->authenticated,
3386 addr_port_match (from, &ks->remote_addr));
3388 #endif
3391 msg (D_TLS_ERRORS,
3392 "TLS Error: local/remote TLS keys are out of sync: %s [%d]",
3393 print_sockaddr (from, &gc), key_id);
3394 goto error;
3396 else /* control channel packet */
3398 bool do_burst = false;
3399 bool new_link = false;
3400 struct session_id sid; /* remote session ID */
3402 /* verify legal opcode */
3403 if (op < P_FIRST_OPCODE || op > P_LAST_OPCODE)
3405 msg (D_TLS_ERRORS,
3406 "TLS Error: unknown opcode received from %s op=%d",
3407 print_sockaddr (from, &gc), op);
3408 goto error;
3411 /* hard reset ? */
3412 if (is_hard_reset (op, 0))
3414 /* verify client -> server or server -> client connection */
3415 if (((op == P_CONTROL_HARD_RESET_CLIENT_V1
3416 || op == P_CONTROL_HARD_RESET_CLIENT_V2) && !multi->opt.server)
3417 || ((op == P_CONTROL_HARD_RESET_SERVER_V1
3418 || op == P_CONTROL_HARD_RESET_SERVER_V2) && multi->opt.server))
3420 msg (D_TLS_ERRORS,
3421 "TLS Error: client->client or server->server connection attempted from %s",
3422 print_sockaddr (from, &gc));
3423 goto error;
3428 * Authenticate Packet
3430 dmsg (D_TLS_DEBUG, "TLS: control channel, op=%s, IP=%s",
3431 packet_opcode_name (op), print_sockaddr (from, &gc));
3433 /* get remote session-id */
3435 struct buffer tmp = *buf;
3436 buf_advance (&tmp, 1);
3437 if (!session_id_read (&sid, &tmp) || !session_id_defined (&sid))
3439 msg (D_TLS_ERRORS,
3440 "TLS Error: session-id not found in packet from %s",
3441 print_sockaddr (from, &gc));
3442 goto error;
3446 /* use session ID to match up packet with appropriate tls_session object */
3447 for (i = 0; i < TM_SIZE; ++i)
3449 struct tls_session *session = &multi->session[i];
3450 struct key_state *ks = &session->key[KS_PRIMARY];
3452 dmsg (D_TLS_DEBUG,
3453 "TLS: initial packet test, i=%d state=%s, mysid=%s, rec-sid=%s, rec-ip=%s, stored-sid=%s, stored-ip=%s",
3455 state_name (ks->state),
3456 session_id_print (&session->session_id, &gc),
3457 session_id_print (&sid, &gc),
3458 print_sockaddr (from, &gc),
3459 session_id_print (&ks->session_id_remote, &gc),
3460 print_sockaddr (&ks->remote_addr, &gc));
3462 if (session_id_equal (&ks->session_id_remote, &sid))
3463 /* found a match */
3465 if (i == TM_LAME_DUCK) {
3466 msg (D_TLS_ERRORS,
3467 "TLS ERROR: received control packet with stale session-id=%s",
3468 session_id_print (&sid, &gc));
3469 goto error;
3471 dmsg (D_TLS_DEBUG,
3472 "TLS: found match, session[%d], sid=%s",
3473 i, session_id_print (&sid, &gc));
3474 break;
3479 * Initial packet received.
3482 if (i == TM_SIZE && is_hard_reset (op, 0))
3484 struct tls_session *session = &multi->session[TM_ACTIVE];
3485 struct key_state *ks = &session->key[KS_PRIMARY];
3487 if (!is_hard_reset (op, multi->opt.key_method))
3489 msg (D_TLS_ERRORS, "TLS ERROR: initial packet local/remote key_method mismatch, local key_method=%d, op=%s",
3490 multi->opt.key_method,
3491 packet_opcode_name (op));
3492 goto error;
3496 * If we have no session currently in progress, the initial packet will
3497 * open a new session in TM_ACTIVE rather than TM_UNTRUSTED.
3499 if (!session_id_defined (&ks->session_id_remote))
3501 if (multi->opt.single_session && multi->n_sessions)
3503 msg (D_TLS_ERRORS,
3504 "TLS Error: Cannot accept new session request from %s due to session context expire or --single-session [1]",
3505 print_sockaddr (from, &gc));
3506 goto error;
3509 #ifdef ENABLE_MANAGEMENT
3510 if (management)
3512 management_set_state (management,
3513 OPENVPN_STATE_AUTH,
3514 NULL,
3517 #endif
3519 msg (D_TLS_DEBUG_LOW,
3520 "TLS: Initial packet from %s, sid=%s",
3521 print_sockaddr (from, &gc),
3522 session_id_print (&sid, &gc));
3524 do_burst = true;
3525 new_link = true;
3526 i = TM_ACTIVE;
3527 session->untrusted_sockaddr = *from;
3531 if (i == TM_SIZE && is_hard_reset (op, 0))
3534 * No match with existing sessions,
3535 * probably a new session.
3537 struct tls_session *session = &multi->session[TM_UNTRUSTED];
3540 * If --single-session, don't allow any hard-reset connection request
3541 * unless it the the first packet of the session.
3543 if (multi->opt.single_session)
3545 msg (D_TLS_ERRORS,
3546 "TLS Error: Cannot accept new session request from %s due to session context expire or --single-session [2]",
3547 print_sockaddr (from, &gc));
3548 goto error;
3551 if (!is_hard_reset (op, multi->opt.key_method))
3553 msg (D_TLS_ERRORS, "TLS ERROR: new session local/remote key_method mismatch, local key_method=%d, op=%s",
3554 multi->opt.key_method,
3555 packet_opcode_name (op));
3556 goto error;
3559 if (!read_control_auth (buf, &session->tls_auth, from))
3560 goto error;
3563 * New session-initiating control packet is authenticated at this point,
3564 * assuming that the --tls-auth command line option was used.
3566 * Without --tls-auth, we leave authentication entirely up to TLS.
3568 msg (D_TLS_DEBUG_LOW,
3569 "TLS: new session incoming connection from %s",
3570 print_sockaddr (from, &gc));
3572 new_link = true;
3573 i = TM_UNTRUSTED;
3574 session->untrusted_sockaddr = *from;
3576 else
3578 struct tls_session *session = &multi->session[i];
3579 struct key_state *ks = &session->key[KS_PRIMARY];
3582 * Packet must belong to an existing session.
3584 if (i != TM_ACTIVE && i != TM_UNTRUSTED)
3586 msg (D_TLS_ERRORS,
3587 "TLS Error: Unroutable control packet received from %s (si=%d op=%s)",
3588 print_sockaddr (from, &gc),
3590 packet_opcode_name (op));
3591 goto error;
3595 * Verify remote IP address
3597 if (!new_link && !addr_port_match (&ks->remote_addr, from))
3599 msg (D_TLS_ERRORS, "TLS Error: Received control packet from unexpected IP addr: %s",
3600 print_sockaddr (from, &gc));
3601 goto error;
3605 * Remote is requesting a key renegotiation
3607 if (op == P_CONTROL_SOFT_RESET_V1
3608 && DECRYPT_KEY_ENABLED (multi, ks))
3610 if (!read_control_auth (buf, &session->tls_auth, from))
3611 goto error;
3613 key_state_soft_reset (session);
3615 dmsg (D_TLS_DEBUG,
3616 "TLS: received P_CONTROL_SOFT_RESET_V1 s=%d sid=%s",
3617 i, session_id_print (&sid, &gc));
3619 else
3622 * Remote responding to our key renegotiation request?
3624 if (op == P_CONTROL_SOFT_RESET_V1)
3625 do_burst = true;
3627 if (!read_control_auth (buf, &session->tls_auth, from))
3628 goto error;
3630 dmsg (D_TLS_DEBUG,
3631 "TLS: received control channel packet s#=%d sid=%s",
3632 i, session_id_print (&sid, &gc));
3637 * We have an authenticated packet (if --tls-auth was set).
3638 * Now pass to our reliability level which deals with
3639 * packet acknowledgements, retransmits, sequencing, etc.
3642 struct tls_session *session = &multi->session[i];
3643 struct key_state *ks = &session->key[KS_PRIMARY];
3645 /* Make sure we were initialized and that we're not in an error state */
3646 ASSERT (ks->state != S_UNDEF);
3647 ASSERT (ks->state != S_ERROR);
3648 ASSERT (session_id_defined (&session->session_id));
3650 /* Let our caller know we processed a control channel packet */
3651 ret = true;
3654 * Set our remote address and remote session_id
3656 if (new_link)
3658 ks->session_id_remote = sid;
3659 ks->remote_addr = *from;
3660 ++multi->n_sessions;
3662 else if (!addr_port_match (&ks->remote_addr, from))
3664 msg (D_TLS_ERRORS,
3665 "TLS Error: Existing session control channel packet from unknown IP address: %s",
3666 print_sockaddr (from, &gc));
3667 goto error;
3671 * Should we do a retransmit of all unacknowledged packets in
3672 * the send buffer? This improves the start-up efficiency of the
3673 * initial key negotiation after the 2nd peer comes online.
3675 if (do_burst && !session->burst)
3677 reliable_schedule_now (ks->send_reliable);
3678 session->burst = true;
3681 /* Check key_id */
3682 if (ks->key_id != key_id)
3684 msg (D_TLS_ERRORS,
3685 "TLS ERROR: local/remote key IDs out of sync (%d/%d) ID: %s",
3686 ks->key_id, key_id, print_key_id (multi, &gc));
3687 goto error;
3691 * Process incoming ACKs for packets we can now
3692 * delete from reliable send buffer
3695 /* buffers all packet IDs to delete from send_reliable */
3696 struct reliable_ack send_ack;
3698 send_ack.len = 0;
3699 if (!reliable_ack_read (&send_ack, buf, &session->session_id))
3701 msg (D_TLS_ERRORS,
3702 "TLS Error: reading acknowledgement record from packet");
3703 goto error;
3705 reliable_send_purge (ks->send_reliable, &send_ack);
3708 if (op != P_ACK_V1 && reliable_can_get (ks->rec_reliable))
3710 packet_id_type id;
3712 /* Extract the packet ID from the packet */
3713 if (reliable_ack_read_packet_id (buf, &id))
3715 /* Avoid deadlock by rejecting packet that would de-sequentialize receive buffer */
3716 if (reliable_wont_break_sequentiality (ks->rec_reliable, id))
3718 if (reliable_not_replay (ks->rec_reliable, id))
3720 /* Save incoming ciphertext packet to reliable buffer */
3721 struct buffer *in = reliable_get_buf (ks->rec_reliable);
3722 ASSERT (in);
3723 ASSERT (buf_copy (in, buf));
3724 reliable_mark_active_incoming (ks->rec_reliable, in, id, op);
3727 /* Process outgoing acknowledgment for packet just received, even if it's a replay */
3728 reliable_ack_acknowledge_packet_id (ks->rec_ack, id);
3736 done:
3737 buf->len = 0;
3738 opt->key_ctx_bi = NULL;
3739 opt->packet_id = NULL;
3740 opt->pid_persist = NULL;
3741 opt->flags &= multi->opt.crypto_flags_and;
3742 gc_free (&gc);
3743 return ret;
3745 error:
3746 ERR_clear_error ();
3747 ++multi->n_soft_errors;
3748 goto done;
3752 * This function is similar to tls_pre_decrypt, except it is called
3753 * when we are in server mode and receive an initial incoming
3754 * packet. Note that we don't modify
3755 * any state in our parameter objects. The purpose is solely to
3756 * determine whether we should generate a client instance
3757 * object, in which case true is returned.
3759 * This function is essentially the first-line HMAC firewall
3760 * on the UDP port listener in --mode server mode.
3762 bool
3763 tls_pre_decrypt_lite (const struct tls_auth_standalone *tas,
3764 const struct sockaddr_in *from,
3765 const struct buffer *buf)
3767 struct gc_arena gc = gc_new ();
3768 bool ret = false;
3770 if (buf->len > 0)
3772 int op;
3773 int key_id;
3775 /* get opcode and key ID */
3777 uint8_t c = *BPTR (buf);
3778 op = c >> P_OPCODE_SHIFT;
3779 key_id = c & P_KEY_ID_MASK;
3782 /* this packet is from an as-yet untrusted source, so
3783 scrutinize carefully */
3785 if (op != P_CONTROL_HARD_RESET_CLIENT_V2)
3788 * This can occur due to bogus data or DoS packets.
3790 dmsg (D_TLS_STATE_ERRORS,
3791 "TLS State Error: No TLS state for client %s, opcode=%d",
3792 print_sockaddr (from, &gc),
3793 op);
3794 goto error;
3797 if (key_id != 0)
3799 dmsg (D_TLS_STATE_ERRORS,
3800 "TLS State Error: Unknown key ID (%d) received from %s -- 0 was expected",
3801 key_id,
3802 print_sockaddr (from, &gc));
3803 goto error;
3806 if (buf->len > EXPANDED_SIZE_DYNAMIC (&tas->frame))
3808 dmsg (D_TLS_STATE_ERRORS,
3809 "TLS State Error: Large packet (size %d) received from %s -- a packet no larger than %d bytes was expected",
3810 buf->len,
3811 print_sockaddr (from, &gc),
3812 EXPANDED_SIZE_DYNAMIC (&tas->frame));
3813 goto error;
3817 struct buffer newbuf = clone_buf (buf);
3818 struct crypto_options co = tas->tls_auth_options;
3819 bool status;
3822 * We are in read-only mode at this point with respect to TLS
3823 * control channel state. After we build a new client instance
3824 * object, we will process this session-initiating packet for real.
3826 co.flags |= CO_IGNORE_PACKET_ID;
3828 /* HMAC test, if --tls-auth was specified */
3829 status = read_control_auth (&newbuf, &co, from);
3830 free_buf (&newbuf);
3831 if (!status)
3832 goto error;
3835 * At this point, if --tls-auth is being used, we know that
3836 * the packet has passed the HMAC test, but we don't know if
3837 * it is a replay yet. We will attempt to defeat replays
3838 * by not advancing to the S_START state until we
3839 * receive an ACK from our first reply to the client
3840 * that includes an HMAC of our randomly generated 64 bit
3841 * session ID.
3843 * On the other hand if --tls-auth is not being used, we
3844 * will proceed to begin the TLS authentication
3845 * handshake with only cursory integrity checks having
3846 * been performed, since we will be leaving the task
3847 * of authentication solely up to TLS.
3850 ret = true;
3853 gc_free (&gc);
3854 return ret;
3856 error:
3857 ERR_clear_error ();
3858 gc_free (&gc);
3859 return ret;
3862 /* Choose the key with which to encrypt a data packet */
3863 void
3864 tls_pre_encrypt (struct tls_multi *multi,
3865 struct buffer *buf, struct crypto_options *opt)
3867 multi->save_ks = NULL;
3868 if (buf->len > 0)
3870 int i;
3871 for (i = 0; i < KEY_SCAN_SIZE; ++i)
3873 struct key_state *ks = multi->key_scan[i];
3874 if (ks->state >= S_ACTIVE && ks->authenticated)
3876 opt->key_ctx_bi = &ks->key;
3877 opt->packet_id = multi->opt.replay ? &ks->packet_id : NULL;
3878 opt->pid_persist = NULL;
3879 opt->flags &= multi->opt.crypto_flags_and;
3880 opt->flags |= multi->opt.crypto_flags_or;
3881 multi->save_ks = ks;
3882 dmsg (D_TLS_DEBUG, "TLS: tls_pre_encrypt: key_id=%d", ks->key_id);
3883 return;
3888 struct gc_arena gc = gc_new ();
3889 dmsg (D_TLS_NO_SEND_KEY, "TLS Warning: no data channel send key available: %s",
3890 print_key_id (multi, &gc));
3891 gc_free (&gc);
3895 buf->len = 0;
3896 opt->key_ctx_bi = NULL;
3897 opt->packet_id = NULL;
3898 opt->pid_persist = NULL;
3899 opt->flags &= multi->opt.crypto_flags_and;
3902 /* Prepend the appropriate opcode to encrypted buffer prior to TCP/UDP send */
3903 void
3904 tls_post_encrypt (struct tls_multi *multi, struct buffer *buf)
3906 struct key_state *ks;
3907 uint8_t *op;
3909 ks = multi->save_ks;
3910 multi->save_ks = NULL;
3911 if (buf->len > 0)
3913 ASSERT (ks);
3914 ASSERT (op = buf_prepend (buf, 1));
3915 *op = (P_DATA_V1 << P_OPCODE_SHIFT) | ks->key_id;
3916 ++ks->n_packets;
3917 ks->n_bytes += buf->len;
3922 * Send a payload over the TLS control channel.
3923 * Called externally.
3926 bool
3927 tls_send_payload (struct tls_multi *multi,
3928 const uint8_t *data,
3929 int size)
3931 struct tls_session *session;
3932 struct key_state *ks;
3933 bool ret = false;
3935 ERR_clear_error ();
3937 ASSERT (multi);
3939 session = &multi->session[TM_ACTIVE];
3940 ks = &session->key[KS_PRIMARY];
3942 if (ks->state >= S_ACTIVE)
3944 if (key_state_write_plaintext_const (multi, ks, data, size) == 1)
3945 ret = true;
3948 ERR_clear_error ();
3950 return ret;
3953 bool
3954 tls_rec_payload (struct tls_multi *multi,
3955 struct buffer *buf)
3957 struct tls_session *session;
3958 struct key_state *ks;
3959 bool ret = false;
3961 ERR_clear_error ();
3963 ASSERT (multi);
3965 session = &multi->session[TM_ACTIVE];
3966 ks = &session->key[KS_PRIMARY];
3968 if (ks->state >= S_ACTIVE && BLEN (&ks->plaintext_read_buf))
3970 if (buf_copy (buf, &ks->plaintext_read_buf))
3971 ret = true;
3972 ks->plaintext_read_buf.len = 0;
3975 ERR_clear_error ();
3977 return ret;
3981 * Dump a human-readable rendition of an openvpn packet
3982 * into a garbage collectable string which is returned.
3984 const char *
3985 protocol_dump (struct buffer *buffer, unsigned int flags, struct gc_arena *gc)
3987 struct buffer out = alloc_buf_gc (256, gc);
3988 struct buffer buf = *buffer;
3990 uint8_t c;
3991 int op;
3992 int key_id;
3994 int tls_auth_hmac_size = (flags & PD_TLS_AUTH_HMAC_SIZE_MASK);
3996 if (buf.len <= 0)
3998 buf_printf (&out, "DATA UNDEF len=%d", buf.len);
3999 goto done;
4002 if (!(flags & PD_TLS))
4003 goto print_data;
4006 * Initial byte (opcode)
4008 if (!buf_read (&buf, &c, sizeof (c)))
4009 goto done;
4010 op = (c >> P_OPCODE_SHIFT);
4011 key_id = c & P_KEY_ID_MASK;
4012 buf_printf (&out, "%s kid=%d", packet_opcode_name (op), key_id);
4014 if (op == P_DATA_V1)
4015 goto print_data;
4018 * Session ID
4021 struct session_id sid;
4023 if (!session_id_read (&sid, &buf))
4024 goto done;
4025 if (flags & PD_VERBOSE)
4026 buf_printf (&out, " sid=%s", session_id_print (&sid, gc));
4030 * tls-auth hmac + packet_id
4032 if (tls_auth_hmac_size)
4034 struct packet_id_net pin;
4035 uint8_t tls_auth_hmac[MAX_HMAC_KEY_LENGTH];
4037 ASSERT (tls_auth_hmac_size <= MAX_HMAC_KEY_LENGTH);
4039 if (!buf_read (&buf, tls_auth_hmac, tls_auth_hmac_size))
4040 goto done;
4041 if (flags & PD_VERBOSE)
4042 buf_printf (&out, " tls_hmac=%s", format_hex (tls_auth_hmac, tls_auth_hmac_size, 0, gc));
4044 if (!packet_id_read (&pin, &buf, true))
4045 goto done;
4046 buf_printf(&out, " pid=%s", packet_id_net_print (&pin, (flags & PD_VERBOSE), gc));
4050 * ACK list
4052 buf_printf (&out, " %s", reliable_ack_print(&buf, (flags & PD_VERBOSE), gc));
4054 if (op == P_ACK_V1)
4055 goto done;
4058 * Packet ID
4061 packet_id_type l;
4062 if (!buf_read (&buf, &l, sizeof (l)))
4063 goto done;
4064 l = ntohpid (l);
4065 buf_printf (&out, " pid=" packet_id_format, (packet_id_print_type)l);
4068 print_data:
4069 if (flags & PD_SHOW_DATA)
4070 buf_printf (&out, " DATA %s", format_hex (BPTR (&buf), BLEN (&buf), 80, gc));
4071 else
4072 buf_printf (&out, " DATA len=%d", buf.len);
4074 done:
4075 return BSTR (&out);
4078 #ifdef EXTRACT_X509_FIELD_TEST
4080 void
4081 extract_x509_field_test (void)
4083 char line[8];
4084 char field[4];
4085 static const char field_name[] = "CN";
4087 while (fgets (line, sizeof (line), stdin))
4089 chomp (line);
4090 extract_x509_field (line, field_name, field, sizeof (field));
4091 printf ("CN: '%s'\n", field);
4095 #endif
4097 #else
4098 static void dummy(void) {}
4099 #endif /* USE_CRYPTO && USE_SSL*/