cosmetics
[tomato.git] / release / src / router / openvpn / ssl.c
blobe6953db42a9b9af74004187c743452d06510bc2f
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-2009 OpenVPN Technologies, Inc. <sales@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 #include "syshead.h"
35 #if defined(USE_CRYPTO) && defined(USE_SSL)
37 #include "ssl.h"
38 #include "error.h"
39 #include "common.h"
40 #include "integer.h"
41 #include "socket.h"
42 #include "thread.h"
43 #include "misc.h"
44 #include "fdmisc.h"
45 #include "interval.h"
46 #include "perf.h"
47 #include "status.h"
48 #include "gremlin.h"
49 #include "pkcs11.h"
50 #include "list.h"
52 #ifdef WIN32
53 #include "cryptoapi.h"
54 #endif
56 #include "memdbg.h"
58 #ifndef ENABLE_OCC
59 static const char ssl_default_options_string[] = "V0 UNDEF";
60 #endif
62 static inline const char *
63 local_options_string (const struct tls_session *session)
65 #ifdef ENABLE_OCC
66 return session->opt->local_options;
67 #else
68 return ssl_default_options_string;
69 #endif
72 #ifdef MEASURE_TLS_HANDSHAKE_STATS
74 static int tls_handshake_success; /* GLOBAL */
75 static int tls_handshake_error; /* GLOBAL */
76 static int tls_packets_generated; /* GLOBAL */
77 static int tls_packets_sent; /* GLOBAL */
79 #define INCR_SENT ++tls_packets_sent
80 #define INCR_GENERATED ++tls_packets_generated
81 #define INCR_SUCCESS ++tls_handshake_success
82 #define INCR_ERROR ++tls_handshake_error
84 void
85 show_tls_performance_stats(void)
87 msg (D_TLS_DEBUG_LOW, "TLS Handshakes, success=%f%% (good=%d, bad=%d), retransmits=%f%%",
88 (double) tls_handshake_success / (tls_handshake_success + tls_handshake_error) * 100.0,
89 tls_handshake_success, tls_handshake_error,
90 (double) (tls_packets_sent - tls_packets_generated) / tls_packets_generated * 100.0);
92 #else
94 #define INCR_SENT
95 #define INCR_GENERATED
96 #define INCR_SUCCESS
97 #define INCR_ERROR
99 #endif
101 #ifdef BIO_DEBUG
103 #warning BIO_DEBUG defined
105 static FILE *biofp; /* GLOBAL */
106 static bool biofp_toggle; /* GLOBAL */
107 static time_t biofp_last_open; /* GLOBAL */
108 static const int biofp_reopen_interval = 600; /* GLOBAL */
110 static void
111 close_biofp()
113 if (biofp)
115 ASSERT (!fclose (biofp));
116 biofp = NULL;
120 static void
121 open_biofp()
123 const time_t current = time (NULL);
124 const pid_t pid = getpid ();
126 if (biofp_last_open + biofp_reopen_interval < current)
127 close_biofp();
128 if (!biofp)
130 char fn[256];
131 openvpn_snprintf(fn, sizeof(fn), "bio/%d-%d.log", pid, biofp_toggle);
132 biofp = fopen (fn, "w");
133 ASSERT (biofp);
134 biofp_last_open = time (NULL);
135 biofp_toggle ^= 1;
139 static void
140 bio_debug_data (const char *mode, BIO *bio, const uint8_t *buf, int len, const char *desc)
142 struct gc_arena gc = gc_new ();
143 if (len > 0)
145 open_biofp();
146 fprintf(biofp, "BIO_%s %s time=" time_format " bio=" ptr_format " len=%d data=%s\n",
147 mode, desc, time (NULL), (ptr_type)bio, len, format_hex (buf, len, 0, &gc));
148 fflush (biofp);
150 gc_free (&gc);
153 static void
154 bio_debug_oc (const char *mode, BIO *bio)
156 open_biofp();
157 fprintf(biofp, "BIO %s time=" time_format " bio=" ptr_format "\n",
158 mode, time (NULL), (ptr_type)bio);
159 fflush (biofp);
162 #endif
165 * Max number of bytes we will add
166 * for data structures common to both
167 * data and control channel packets.
168 * (opcode only).
170 void
171 tls_adjust_frame_parameters(struct frame *frame)
173 frame_add_to_extra_frame (frame, 1); /* space for opcode */
177 * Max number of bytes we will add
178 * to control channel packet.
180 static void
181 tls_init_control_channel_frame_parameters(const struct frame *data_channel_frame,
182 struct frame *frame)
185 * frame->extra_frame is already initialized with tls_auth buffer requirements,
186 * if --tls-auth is enabled.
189 /* inherit link MTU and extra_link from data channel */
190 frame->link_mtu = data_channel_frame->link_mtu;
191 frame->extra_link = data_channel_frame->extra_link;
193 /* set extra_frame */
194 tls_adjust_frame_parameters (frame);
195 reliable_ack_adjust_frame_parameters (frame, CONTROL_SEND_ACK_MAX);
196 frame_add_to_extra_frame (frame, SID_SIZE + sizeof (packet_id_type));
198 /* set dynamic link MTU to minimum value */
199 frame_set_mtu_dynamic (frame, 0, SET_MTU_TUN);
203 * Allocate space in SSL objects
204 * in which to store a struct tls_session
205 * pointer back to parent.
208 static int mydata_index; /* GLOBAL */
210 static void
211 ssl_set_mydata_index ()
213 mydata_index = SSL_get_ex_new_index (0, "struct session *", NULL, NULL, NULL);
214 ASSERT (mydata_index >= 0);
217 void
218 init_ssl_lib ()
220 SSL_library_init ();
221 SSL_load_error_strings ();
222 OpenSSL_add_all_algorithms ();
224 init_crypto_lib();
227 * If you build the OpenSSL library and OpenVPN with
228 * CRYPTO_MDEBUG, you will get a listing of OpenSSL
229 * memory leaks on program termination.
231 #ifdef CRYPTO_MDEBUG
232 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
233 #endif
235 ssl_set_mydata_index ();
238 void
239 free_ssl_lib ()
241 #ifdef CRYPTO_MDEBUG
242 FILE* fp = fopen ("sdlog", "w");
243 ASSERT (fp);
244 CRYPTO_mem_leaks_fp (fp);
245 fclose (fp);
246 #endif
248 uninit_crypto_lib ();
249 EVP_cleanup ();
250 ERR_free_strings ();
254 * OpenSSL library calls pem_password_callback if the
255 * private key is protected by a password.
258 static struct user_pass passbuf; /* GLOBAL */
260 void
261 pem_password_setup (const char *auth_file)
263 if (!strlen (passbuf.password))
264 get_user_pass (&passbuf, auth_file, UP_TYPE_PRIVATE_KEY, GET_USER_PASS_MANAGEMENT|GET_USER_PASS_SENSITIVE|GET_USER_PASS_PASSWORD_ONLY);
268 pem_password_callback (char *buf, int size, int rwflag, void *u)
270 if (buf)
272 /* prompt for password even if --askpass wasn't specified */
273 pem_password_setup (NULL);
274 strncpynt (buf, passbuf.password, size);
275 purge_user_pass (&passbuf, false);
277 return strlen (buf);
279 return 0;
283 * Auth username/password handling
286 static bool auth_user_pass_enabled; /* GLOBAL */
287 static struct user_pass auth_user_pass; /* GLOBAL */
289 void
290 auth_user_pass_setup (const char *auth_file)
292 auth_user_pass_enabled = true;
293 if (!auth_user_pass.defined)
295 #if AUTO_USERID
296 get_user_pass_auto_userid (&auth_user_pass, auth_file);
297 #else
298 get_user_pass (&auth_user_pass, auth_file, UP_TYPE_AUTH, GET_USER_PASS_MANAGEMENT|GET_USER_PASS_SENSITIVE);
299 #endif
304 * Disable password caching
306 void
307 ssl_set_auth_nocache (void)
309 passbuf.nocache = true;
310 auth_user_pass.nocache = true;
314 * Forget private key password AND auth-user-pass username/password.
316 void
317 ssl_purge_auth (void)
319 #ifdef USE_PKCS11
320 pkcs11_logout ();
321 #endif
322 purge_user_pass (&passbuf, true);
323 purge_user_pass (&auth_user_pass, true);
327 * OpenSSL callback to get a temporary RSA key, mostly
328 * used for export ciphers.
330 static RSA *
331 tmp_rsa_cb (SSL * s, int is_export, int keylength)
333 static RSA *rsa_tmp = NULL;
334 if (rsa_tmp == NULL)
336 msg (D_HANDSHAKE, "Generating temp (%d bit) RSA key", keylength);
337 rsa_tmp = RSA_generate_key (keylength, RSA_F4, NULL, NULL);
339 return (rsa_tmp);
343 * Cert hash functions
345 static void
346 cert_hash_remember (struct tls_session *session, const int error_depth, const unsigned char *sha1_hash)
348 if (error_depth >= 0 && error_depth < MAX_CERT_DEPTH)
350 if (!session->cert_hash_set)
351 ALLOC_OBJ_CLEAR (session->cert_hash_set, struct cert_hash_set);
352 if (!session->cert_hash_set->ch[error_depth])
353 ALLOC_OBJ (session->cert_hash_set->ch[error_depth], struct cert_hash);
355 struct cert_hash *ch = session->cert_hash_set->ch[error_depth];
356 memcpy (ch->sha1_hash, sha1_hash, SHA_DIGEST_LENGTH);
361 #if 0
362 static void
363 cert_hash_print (const struct cert_hash_set *chs, int msglevel)
365 struct gc_arena gc = gc_new ();
366 msg (msglevel, "CERT_HASH");
367 if (chs)
369 int i;
370 for (i = 0; i < MAX_CERT_DEPTH; ++i)
372 const struct cert_hash *ch = chs->ch[i];
373 if (ch)
374 msg (msglevel, "%d:%s", i, format_hex(ch->sha1_hash, SHA_DIGEST_LENGTH, 0, &gc));
377 gc_free (&gc);
379 #endif
381 static void
382 cert_hash_free (struct cert_hash_set *chs)
384 if (chs)
386 int i;
387 for (i = 0; i < MAX_CERT_DEPTH; ++i)
388 free (chs->ch[i]);
389 free (chs);
393 static bool
394 cert_hash_compare (const struct cert_hash_set *chs1, const struct cert_hash_set *chs2)
396 if (chs1 && chs2)
398 int i;
399 for (i = 0; i < MAX_CERT_DEPTH; ++i)
401 const struct cert_hash *ch1 = chs1->ch[i];
402 const struct cert_hash *ch2 = chs2->ch[i];
404 if (!ch1 && !ch2)
405 continue;
406 else if (ch1 && ch2 && !memcmp (ch1->sha1_hash, ch2->sha1_hash, SHA_DIGEST_LENGTH))
407 continue;
408 else
409 return false;
411 return true;
413 else if (!chs1 && !chs2)
414 return true;
415 else
416 return false;
419 static struct cert_hash_set *
420 cert_hash_copy (const struct cert_hash_set *chs)
422 struct cert_hash_set *dest = NULL;
423 if (chs)
425 int i;
426 ALLOC_OBJ_CLEAR (dest, struct cert_hash_set);
427 for (i = 0; i < MAX_CERT_DEPTH; ++i)
429 const struct cert_hash *ch = chs->ch[i];
430 if (ch)
432 ALLOC_OBJ (dest->ch[i], struct cert_hash);
433 memcpy (dest->ch[i]->sha1_hash, ch->sha1_hash, SHA_DIGEST_LENGTH);
437 return dest;
441 * Extract a field from an X509 subject name.
443 * Example:
445 * /C=US/ST=CO/L=Denver/O=ORG/CN=First-CN/CN=Test-CA/Email=jim@yonan.net
447 * The common name is 'Test-CA'
449 * Return true on success, false on error (insufficient buffer size in 'out'
450 * to contain result is grounds for error).
452 static bool
453 extract_x509_field_ssl (X509_NAME *x509, const char *field_name, char *out, int size)
455 int lastpos = -1;
456 int tmp = -1;
457 X509_NAME_ENTRY *x509ne = 0;
458 ASN1_STRING *asn1 = 0;
459 unsigned char *buf = (unsigned char *)1; /* bug in OpenSSL 0.9.6b ASN1_STRING_to_UTF8 requires this workaround */
460 int nid = OBJ_txt2nid((char *)field_name);
462 ASSERT (size > 0);
463 *out = '\0';
464 do {
465 lastpos = tmp;
466 tmp = X509_NAME_get_index_by_NID(x509, nid, lastpos);
467 } while (tmp > -1);
469 /* Nothing found */
470 if (lastpos == -1)
471 return false;
473 x509ne = X509_NAME_get_entry(x509, lastpos);
474 if (!x509ne)
475 return false;
477 asn1 = X509_NAME_ENTRY_get_data(x509ne);
478 if (!asn1)
479 return false;
480 tmp = ASN1_STRING_to_UTF8(&buf, asn1);
481 if (tmp <= 0)
482 return false;
484 strncpynt(out, (char *)buf, size);
487 const bool ret = (strlen ((char *)buf) < size);
488 OPENSSL_free (buf);
489 return ret;
494 * Save X509 fields to environment, using the naming convention:
496 * X509_{cert_depth}_{name}={value}
498 static void
499 setenv_x509 (struct env_set *es, const int error_depth, X509_NAME *x509)
501 int i, n;
502 int fn_nid;
503 ASN1_OBJECT *fn;
504 ASN1_STRING *val;
505 X509_NAME_ENTRY *ent;
506 const char *objbuf;
507 unsigned char *buf;
508 char *name_expand;
509 size_t name_expand_size;
511 n = X509_NAME_entry_count (x509);
512 for (i = 0; i < n; ++i)
514 ent = X509_NAME_get_entry (x509, i);
515 if (!ent)
516 continue;
517 fn = X509_NAME_ENTRY_get_object (ent);
518 if (!fn)
519 continue;
520 val = X509_NAME_ENTRY_get_data (ent);
521 if (!val)
522 continue;
523 fn_nid = OBJ_obj2nid (fn);
524 if (fn_nid == NID_undef)
525 continue;
526 objbuf = OBJ_nid2sn (fn_nid);
527 if (!objbuf)
528 continue;
529 buf = (unsigned char *)1; /* bug in OpenSSL 0.9.6b ASN1_STRING_to_UTF8 requires this workaround */
530 if (ASN1_STRING_to_UTF8 (&buf, val) <= 0)
531 continue;
532 name_expand_size = 64 + strlen (objbuf);
533 name_expand = (char *) malloc (name_expand_size);
534 check_malloc_return (name_expand);
535 openvpn_snprintf (name_expand, name_expand_size, "X509_%d_%s", error_depth, objbuf);
536 string_mod (name_expand, CC_PRINT, CC_CRLF, '_');
537 string_mod ((char*)buf, CC_PRINT, CC_CRLF, '_');
538 setenv_str (es, name_expand, (char*)buf);
539 free (name_expand);
540 OPENSSL_free (buf);
544 static void
545 setenv_untrusted (struct tls_session *session)
547 setenv_link_socket_actual (session->opt->es, "untrusted", &session->untrusted_addr, SA_IP_PORT);
550 static void
551 set_common_name (struct tls_session *session, const char *common_name)
553 if (session->common_name)
555 free (session->common_name);
556 session->common_name = NULL;
557 #ifdef ENABLE_PF
558 session->common_name_hashval = 0;
559 #endif
561 if (common_name)
563 session->common_name = string_alloc (common_name, NULL);
564 #ifdef ENABLE_PF
566 const uint32_t len = (uint32_t) strlen (common_name);
567 if (len)
568 session->common_name_hashval = hash_func ((const uint8_t*)common_name, len+1, 0);
569 else
570 session->common_name_hashval = 0;
572 #endif
576 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
578 bool verify_cert_eku (X509 *x509, const char * const expected_oid) {
580 EXTENDED_KEY_USAGE *eku = NULL;
581 bool fFound = false;
583 if ((eku = (EXTENDED_KEY_USAGE *)X509_get_ext_d2i (x509, NID_ext_key_usage, NULL, NULL)) == NULL) {
584 msg (D_HANDSHAKE, "Certificate does not have extended key usage extension");
586 else {
587 int i;
589 msg (D_HANDSHAKE, "Validating certificate extended key usage");
590 for(i = 0; !fFound && i < sk_ASN1_OBJECT_num (eku); i++) {
591 ASN1_OBJECT *oid = sk_ASN1_OBJECT_value (eku, i);
592 char szOid[1024];
594 if (!fFound && OBJ_obj2txt (szOid, sizeof (szOid), oid, 0) != -1) {
595 msg (D_HANDSHAKE, "++ Certificate has EKU (str) %s, expects %s", szOid, expected_oid);
596 if (!strcmp (expected_oid, szOid)) {
597 fFound = true;
600 if (!fFound && OBJ_obj2txt (szOid, sizeof (szOid), oid, 1) != -1) {
601 msg (D_HANDSHAKE, "++ Certificate has EKU (oid) %s, expects %s", szOid, expected_oid);
602 if (!strcmp (expected_oid, szOid)) {
603 fFound = true;
609 if (eku != NULL) {
610 sk_ASN1_OBJECT_pop_free (eku, ASN1_OBJECT_free);
613 return fFound;
616 bool verify_cert_ku (X509 *x509, const unsigned * const expected_ku, int expected_len) {
618 ASN1_BIT_STRING *ku = NULL;
619 bool fFound = false;
621 if ((ku = (ASN1_BIT_STRING *)X509_get_ext_d2i (x509, NID_key_usage, NULL, NULL)) == NULL) {
622 msg (D_HANDSHAKE, "Certificate does not have key usage extension");
624 else {
625 unsigned nku = 0;
626 int i;
627 for (i=0;i<8;i++) {
628 if (ASN1_BIT_STRING_get_bit (ku, i)) {
629 nku |= 1<<(7-i);
634 * Fixup if no LSB bits
636 if ((nku & 0xff) == 0) {
637 nku >>= 8;
640 msg (D_HANDSHAKE, "Validating certificate key usage");
641 for (i=0;!fFound && i<expected_len;i++) {
642 if (expected_ku[i] != 0) {
643 msg (D_HANDSHAKE, "++ Certificate has key usage %04x, expects %04x", nku, expected_ku[i]);
645 if (nku == expected_ku[i]) {
646 fFound = true;
652 if (ku != NULL) {
653 ASN1_BIT_STRING_free (ku);
656 return fFound;
659 #endif /* OPENSSL_VERSION_NUMBER */
662 * nsCertType checking
665 #define verify_nsCertType(x, usage) (((x)->ex_flags & EXFLAG_NSCERT) && ((x)->ex_nscert & (usage)))
667 static const char *
668 print_nsCertType (int type)
670 switch (type)
672 case NS_SSL_SERVER:
673 return "SERVER";
674 case NS_SSL_CLIENT:
675 return "CLIENT";
676 default:
677 return "?";
681 static void
682 string_mod_sslname (char *str, const unsigned int restrictive_flags, const unsigned int ssl_flags)
684 if (ssl_flags & SSLF_NO_NAME_REMAPPING)
685 string_mod (str, CC_PRINT, CC_CRLF, '_');
686 else
687 string_mod (str, restrictive_flags, 0, '_');
691 * Our verify callback function -- check
692 * that an incoming peer certificate is good.
695 static int
696 verify_callback (int preverify_ok, X509_STORE_CTX * ctx)
698 char *subject = NULL;
699 char envname[64];
700 char common_name[TLS_CN_LEN];
701 SSL *ssl;
702 struct tls_session *session;
703 const struct tls_options *opt;
704 const int max_depth = MAX_CERT_DEPTH;
705 struct argv argv = argv_new ();
707 /* get the tls_session pointer */
708 ssl = X509_STORE_CTX_get_ex_data (ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
709 ASSERT (ssl);
710 session = (struct tls_session *) SSL_get_ex_data (ssl, mydata_index);
711 ASSERT (session);
712 opt = session->opt;
713 ASSERT (opt);
715 session->verified = false;
717 /* get the X509 name */
718 subject = X509_NAME_oneline (X509_get_subject_name (ctx->current_cert), NULL, 0);
719 if (!subject)
721 msg (D_TLS_ERRORS, "VERIFY ERROR: depth=%d, could not extract X509 subject string from certificate", ctx->error_depth);
722 goto err;
725 /* Save X509 fields in environment */
726 setenv_x509 (opt->es, ctx->error_depth, X509_get_subject_name (ctx->current_cert));
728 /* enforce character class restrictions in X509 name */
729 string_mod_sslname (subject, X509_NAME_CHAR_CLASS, opt->ssl_flags);
730 string_replace_leading (subject, '-', '_');
732 /* extract the common name */
733 if (!extract_x509_field_ssl (X509_get_subject_name (ctx->current_cert), "CN", common_name, TLS_CN_LEN))
735 if (!ctx->error_depth)
737 msg (D_TLS_ERRORS, "VERIFY ERROR: could not extract Common Name from X509 subject string ('%s') -- note that the Common Name length is limited to %d characters",
738 subject,
739 TLS_CN_LEN);
740 goto err;
744 string_mod_sslname (common_name, COMMON_NAME_CHAR_CLASS, opt->ssl_flags);
746 cert_hash_remember (session, ctx->error_depth, ctx->current_cert->sha1_hash);
748 #if 0 /* print some debugging info */
750 struct gc_arena gc = gc_new ();
751 msg (M_INFO, "LOCAL OPT[%d]: %s", ctx->error_depth, opt->local_options);
752 msg (M_INFO, "X509[%d]: %s", ctx->error_depth, subject);
753 msg (M_INFO, "SHA1[%d]: %s", ctx->error_depth, format_hex(ctx->current_cert->sha1_hash, SHA_DIGEST_LENGTH, 0, &gc));
754 gc_free (&gc);
756 #endif
758 /* did peer present cert which was signed our root cert? */
759 if (!preverify_ok)
761 /* Remote site specified a certificate, but it's not correct */
762 msg (D_TLS_ERRORS, "VERIFY ERROR: depth=%d, error=%s: %s",
763 ctx->error_depth, X509_verify_cert_error_string (ctx->error), subject);
764 goto err; /* Reject connection */
767 /* warn if cert chain is too deep */
768 if (ctx->error_depth >= max_depth)
770 msg (D_TLS_ERRORS, "TLS Error: Convoluted certificate chain detected with depth [%d] greater than %d", ctx->error_depth, max_depth);
771 goto err; /* Reject connection */
774 /* save common name in session object */
775 if (ctx->error_depth == 0)
776 set_common_name (session, common_name);
778 /* export subject name string as environmental variable */
779 session->verify_maxlevel = max_int (session->verify_maxlevel, ctx->error_depth);
780 openvpn_snprintf (envname, sizeof(envname), "tls_id_%d", ctx->error_depth);
781 setenv_str (opt->es, envname, subject);
783 #if 0
784 /* export common name string as environmental variable */
785 openvpn_snprintf (envname, sizeof(envname), "tls_common_name_%d", ctx->error_depth);
786 setenv_str (opt->es, envname, common_name);
787 #endif
789 /* export serial number as environmental variable */
791 const int serial = (int) ASN1_INTEGER_get (X509_get_serialNumber (ctx->current_cert));
792 openvpn_snprintf (envname, sizeof(envname), "tls_serial_%d", ctx->error_depth);
793 setenv_int (opt->es, envname, serial);
796 /* export current untrusted IP */
797 setenv_untrusted (session);
799 /* verify certificate nsCertType */
800 if (opt->ns_cert_type && ctx->error_depth == 0)
802 if (verify_nsCertType (ctx->current_cert, opt->ns_cert_type))
804 msg (D_HANDSHAKE, "VERIFY OK: nsCertType=%s",
805 print_nsCertType (opt->ns_cert_type));
807 else
809 msg (D_HANDSHAKE, "VERIFY nsCertType ERROR: %s, require nsCertType=%s",
810 subject, print_nsCertType (opt->ns_cert_type));
811 goto err; /* Reject connection */
815 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
817 /* verify certificate ku */
818 if (opt->remote_cert_ku[0] != 0 && ctx->error_depth == 0)
820 if (verify_cert_ku (ctx->current_cert, opt->remote_cert_ku, MAX_PARMS))
822 msg (D_HANDSHAKE, "VERIFY KU OK");
824 else
826 msg (D_HANDSHAKE, "VERIFY KU ERROR");
827 goto err; /* Reject connection */
831 /* verify certificate eku */
832 if (opt->remote_cert_eku != NULL && ctx->error_depth == 0)
834 if (verify_cert_eku (ctx->current_cert, opt->remote_cert_eku))
836 msg (D_HANDSHAKE, "VERIFY EKU OK");
838 else
840 msg (D_HANDSHAKE, "VERIFY EKU ERROR");
841 goto err; /* Reject connection */
845 #endif /* OPENSSL_VERSION_NUMBER */
847 /* verify X509 name or common name against --tls-remote */
848 if (opt->verify_x509name && strlen (opt->verify_x509name) > 0 && ctx->error_depth == 0)
850 if (strcmp (opt->verify_x509name, subject) == 0
851 || strncmp (opt->verify_x509name, common_name, strlen (opt->verify_x509name)) == 0)
852 msg (D_HANDSHAKE, "VERIFY X509NAME OK: %s", subject);
853 else
855 msg (D_HANDSHAKE, "VERIFY X509NAME ERROR: %s, must be %s",
856 subject, opt->verify_x509name);
857 goto err; /* Reject connection */
861 /* call --tls-verify plug-in(s) */
862 if (plugin_defined (opt->plugins, OPENVPN_PLUGIN_TLS_VERIFY))
864 int ret;
866 argv_printf (&argv, "%d %s",
867 ctx->error_depth,
868 subject);
870 ret = plugin_call (opt->plugins, OPENVPN_PLUGIN_TLS_VERIFY, &argv, NULL, opt->es);
872 if (ret == OPENVPN_PLUGIN_FUNC_SUCCESS)
874 msg (D_HANDSHAKE, "VERIFY PLUGIN OK: depth=%d, %s",
875 ctx->error_depth, subject);
877 else
879 msg (D_HANDSHAKE, "VERIFY PLUGIN ERROR: depth=%d, %s",
880 ctx->error_depth, subject);
881 goto err; /* Reject connection */
885 /* run --tls-verify script */
886 if (opt->verify_command)
888 int ret;
890 setenv_str (opt->es, "script_type", "tls-verify");
892 argv_printf (&argv, "%sc %d %s",
893 opt->verify_command,
894 ctx->error_depth,
895 subject);
896 argv_msg_prefix (D_TLS_DEBUG, &argv, "TLS: executing verify command");
897 ret = openvpn_execve (&argv, opt->es, S_SCRIPT);
899 if (system_ok (ret))
901 msg (D_HANDSHAKE, "VERIFY SCRIPT OK: depth=%d, %s",
902 ctx->error_depth, subject);
904 else
906 if (!system_executed (ret))
907 argv_msg_prefix (M_ERR, &argv, "Verify command failed to execute");
908 msg (D_HANDSHAKE, "VERIFY SCRIPT ERROR: depth=%d, %s",
909 ctx->error_depth, subject);
910 goto err; /* Reject connection */
914 /* check peer cert against CRL */
915 if (opt->crl_file)
917 X509_CRL *crl=NULL;
918 X509_REVOKED *revoked;
919 BIO *in=NULL;
920 int n,i,retval = 0;
922 in=BIO_new(BIO_s_file());
924 if (in == NULL) {
925 msg (M_ERR, "CRL: BIO err");
926 goto end;
928 if (BIO_read_filename(in, opt->crl_file) <= 0) {
929 msg (M_ERR, "CRL: cannot read: %s", opt->crl_file);
930 goto end;
932 crl=PEM_read_bio_X509_CRL(in,NULL,NULL,NULL);
933 if (crl == NULL) {
934 msg (M_ERR, "CRL: cannot read CRL from file %s", opt->crl_file);
935 goto end;
938 if (X509_NAME_cmp(X509_CRL_get_issuer(crl), X509_get_issuer_name(ctx->current_cert)) != 0) {
939 msg (M_WARN, "CRL: CRL %s is from a different issuer than the issuer of certificate %s", opt->crl_file, subject);
940 retval = 1;
941 goto end;
944 n = sk_num(X509_CRL_get_REVOKED(crl));
946 for (i = 0; i < n; i++) {
947 revoked = (X509_REVOKED *)sk_value(X509_CRL_get_REVOKED(crl), i);
948 if (ASN1_INTEGER_cmp(revoked->serialNumber, X509_get_serialNumber(ctx->current_cert)) == 0) {
949 msg (D_HANDSHAKE, "CRL CHECK FAILED: %s is REVOKED",subject);
950 goto end;
954 retval = 1;
955 msg (D_HANDSHAKE, "CRL CHECK OK: %s",subject);
957 end:
959 BIO_free(in);
960 if (crl)
961 X509_CRL_free (crl);
962 if (!retval)
963 goto err;
966 msg (D_HANDSHAKE, "VERIFY OK: depth=%d, %s", ctx->error_depth, subject);
968 session->verified = true;
969 free (subject);
970 argv_reset (&argv);
971 return 1; /* Accept connection */
973 err:
974 ERR_clear_error ();
975 free (subject);
976 argv_reset (&argv);
977 return 0; /* Reject connection */
980 void
981 tls_set_common_name (struct tls_multi *multi, const char *common_name)
983 if (multi)
984 set_common_name (&multi->session[TM_ACTIVE], common_name);
987 const char *
988 tls_common_name (const struct tls_multi *multi, const bool null)
990 const char *ret = NULL;
991 if (multi)
992 ret = multi->session[TM_ACTIVE].common_name;
993 if (ret && strlen (ret))
994 return ret;
995 else if (null)
996 return NULL;
997 else
998 return "UNDEF";
1001 void
1002 tls_lock_common_name (struct tls_multi *multi)
1004 const char *cn = multi->session[TM_ACTIVE].common_name;
1005 if (cn && !multi->locked_cn)
1006 multi->locked_cn = string_alloc (cn, NULL);
1009 void
1010 tls_lock_cert_hash_set (struct tls_multi *multi)
1012 const struct cert_hash_set *chs = multi->session[TM_ACTIVE].cert_hash_set;
1013 if (chs && !multi->locked_cert_hash_set)
1014 multi->locked_cert_hash_set = cert_hash_copy (chs);
1017 static bool
1018 tls_lock_username (struct tls_multi *multi, const char *username)
1020 if (multi->locked_username)
1022 if (!username || strcmp (username, multi->locked_username))
1024 msg (D_TLS_ERRORS, "TLS Auth Error: username attempted to change from '%s' to '%s' -- tunnel disabled",
1025 multi->locked_username,
1026 np(username));
1028 /* disable the tunnel */
1029 tls_deauthenticate (multi);
1030 return false;
1033 else
1035 if (username)
1036 multi->locked_username = string_alloc (username, NULL);
1038 return true;
1041 #ifdef ENABLE_DEF_AUTH
1042 /* key_state_test_auth_control_file return values,
1043 NOTE: acf_merge indexing depends on these values */
1044 #define ACF_UNDEFINED 0
1045 #define ACF_SUCCEEDED 1
1046 #define ACF_DISABLED 2
1047 #define ACF_FAILED 3
1048 #endif
1050 #ifdef MANAGEMENT_DEF_AUTH
1051 static void
1052 man_def_auth_set_client_reason (struct tls_multi *multi, const char *client_reason)
1054 if (multi->client_reason)
1056 free (multi->client_reason);
1057 multi->client_reason = NULL;
1059 if (client_reason && strlen (client_reason))
1060 multi->client_reason = string_alloc (client_reason, NULL);
1063 static inline unsigned int
1064 man_def_auth_test (const struct key_state *ks)
1066 if (management_enable_def_auth (management))
1067 return ks->mda_status;
1068 else
1069 return ACF_DISABLED;
1071 #endif
1073 #ifdef PLUGIN_DEF_AUTH
1076 * auth_control_file functions
1079 static void
1080 key_state_rm_auth_control_file (struct key_state *ks)
1082 if (ks && ks->auth_control_file)
1084 delete_file (ks->auth_control_file);
1085 free (ks->auth_control_file);
1086 ks->auth_control_file = NULL;
1090 static void
1091 key_state_gen_auth_control_file (struct key_state *ks, const struct tls_options *opt)
1093 struct gc_arena gc = gc_new ();
1094 const char *acf;
1096 key_state_rm_auth_control_file (ks);
1097 acf = create_temp_filename (opt->tmp_dir, "acf", &gc);
1098 ks->auth_control_file = string_alloc (acf, NULL);
1099 setenv_str (opt->es, "auth_control_file", ks->auth_control_file);
1101 gc_free (&gc);
1104 static unsigned int
1105 key_state_test_auth_control_file (struct key_state *ks)
1107 if (ks && ks->auth_control_file)
1109 unsigned int ret = ks->auth_control_status;
1110 if (ret == ACF_UNDEFINED)
1112 FILE *fp = fopen (ks->auth_control_file, "r");
1113 if (fp)
1115 const int c = fgetc (fp);
1116 if (c == '1')
1117 ret = ACF_SUCCEEDED;
1118 else if (c == '0')
1119 ret = ACF_FAILED;
1120 fclose (fp);
1121 ks->auth_control_status = ret;
1124 return ret;
1126 return ACF_DISABLED;
1129 #endif
1132 * Return current session authentication state. Return
1133 * value is TLS_AUTHENTICATION_x.
1137 tls_authentication_status (struct tls_multi *multi, const int latency)
1139 bool deferred = false;
1140 bool success = false;
1141 bool active = false;
1143 #ifdef ENABLE_DEF_AUTH
1144 static const unsigned char acf_merge[] =
1146 ACF_UNDEFINED, /* s1=ACF_UNDEFINED s2=ACF_UNDEFINED */
1147 ACF_UNDEFINED, /* s1=ACF_UNDEFINED s2=ACF_SUCCEEDED */
1148 ACF_UNDEFINED, /* s1=ACF_UNDEFINED s2=ACF_DISABLED */
1149 ACF_FAILED, /* s1=ACF_UNDEFINED s2=ACF_FAILED */
1150 ACF_UNDEFINED, /* s1=ACF_SUCCEEDED s2=ACF_UNDEFINED */
1151 ACF_SUCCEEDED, /* s1=ACF_SUCCEEDED s2=ACF_SUCCEEDED */
1152 ACF_SUCCEEDED, /* s1=ACF_SUCCEEDED s2=ACF_DISABLED */
1153 ACF_FAILED, /* s1=ACF_SUCCEEDED s2=ACF_FAILED */
1154 ACF_UNDEFINED, /* s1=ACF_DISABLED s2=ACF_UNDEFINED */
1155 ACF_SUCCEEDED, /* s1=ACF_DISABLED s2=ACF_SUCCEEDED */
1156 ACF_DISABLED, /* s1=ACF_DISABLED s2=ACF_DISABLED */
1157 ACF_FAILED, /* s1=ACF_DISABLED s2=ACF_FAILED */
1158 ACF_FAILED, /* s1=ACF_FAILED s2=ACF_UNDEFINED */
1159 ACF_FAILED, /* s1=ACF_FAILED s2=ACF_SUCCEEDED */
1160 ACF_FAILED, /* s1=ACF_FAILED s2=ACF_DISABLED */
1161 ACF_FAILED /* s1=ACF_FAILED s2=ACF_FAILED */
1163 #endif
1165 if (multi)
1167 int i;
1169 #ifdef ENABLE_DEF_AUTH
1170 if (latency && multi->tas_last && multi->tas_last + latency >= now)
1171 return TLS_AUTHENTICATION_UNDEFINED;
1172 multi->tas_last = now;
1173 #endif
1175 for (i = 0; i < KEY_SCAN_SIZE; ++i)
1177 struct key_state *ks = multi->key_scan[i];
1178 if (DECRYPT_KEY_ENABLED (multi, ks))
1180 active = true;
1181 if (ks->authenticated)
1183 #ifdef ENABLE_DEF_AUTH
1184 unsigned int s1 = ACF_DISABLED;
1185 unsigned int s2 = ACF_DISABLED;
1186 #ifdef PLUGIN_DEF_AUTH
1187 s1 = key_state_test_auth_control_file (ks);
1188 #endif
1189 #ifdef MANAGEMENT_DEF_AUTH
1190 s2 = man_def_auth_test (ks);
1191 #endif
1192 ASSERT (s1 < 4 && s2 < 4);
1193 switch (acf_merge[(s1<<2) + s2])
1195 case ACF_SUCCEEDED:
1196 case ACF_DISABLED:
1197 success = true;
1198 ks->auth_deferred = false;
1199 break;
1200 case ACF_UNDEFINED:
1201 if (now < ks->auth_deferred_expire)
1202 deferred = true;
1203 break;
1204 case ACF_FAILED:
1205 ks->authenticated = false;
1206 break;
1207 default:
1208 ASSERT (0);
1210 #else
1211 success = true;
1212 #endif
1218 #if 0
1219 dmsg (D_TLS_ERRORS, "TAS: a=%d s=%d d=%d", active, success, deferred);
1220 #endif
1222 if (success)
1223 return TLS_AUTHENTICATION_SUCCEEDED;
1224 else if (!active || deferred)
1225 return TLS_AUTHENTICATION_DEFERRED;
1226 else
1227 return TLS_AUTHENTICATION_FAILED;
1230 #ifdef MANAGEMENT_DEF_AUTH
1231 bool
1232 tls_authenticate_key (struct tls_multi *multi, const unsigned int mda_key_id, const bool auth, const char *client_reason)
1234 bool ret = false;
1235 if (multi)
1237 int i;
1238 man_def_auth_set_client_reason (multi, client_reason);
1239 for (i = 0; i < KEY_SCAN_SIZE; ++i)
1241 struct key_state *ks = multi->key_scan[i];
1242 if (ks->mda_key_id == mda_key_id)
1244 ks->mda_status = auth ? ACF_SUCCEEDED : ACF_FAILED;
1245 ret = true;
1249 return ret;
1251 #endif
1253 void
1254 tls_deauthenticate (struct tls_multi *multi)
1256 if (multi)
1258 int i, j;
1259 for (i = 0; i < TM_SIZE; ++i)
1260 for (j = 0; j < KS_SIZE; ++j)
1261 multi->session[i].key[j].authenticated = false;
1266 * Print debugging information on SSL/TLS session negotiation.
1268 static void
1269 info_callback (INFO_CALLBACK_SSL_CONST SSL * s, int where, int ret)
1271 if (where & SSL_CB_LOOP)
1273 dmsg (D_HANDSHAKE_VERBOSE, "SSL state (%s): %s",
1274 where & SSL_ST_CONNECT ? "connect" :
1275 where & SSL_ST_ACCEPT ? "accept" :
1276 "undefined", SSL_state_string_long (s));
1278 else if (where & SSL_CB_ALERT)
1280 dmsg (D_HANDSHAKE_VERBOSE, "SSL alert (%s): %s: %s",
1281 where & SSL_CB_READ ? "read" : "write",
1282 SSL_alert_type_string_long (ret),
1283 SSL_alert_desc_string_long (ret));
1287 #if ENABLE_INLINE_FILES
1289 static int
1290 use_inline_load_verify_locations (SSL_CTX *ctx, const char *ca_string)
1292 X509_STORE *store = NULL;
1293 X509* cert = NULL;
1294 BIO *in = NULL;
1295 int ret = 0;
1297 in = BIO_new_mem_buf ((char *)ca_string, -1);
1298 if (!in)
1299 goto err;
1301 for (;;)
1303 if (!PEM_read_bio_X509 (in, &cert, 0, NULL))
1305 ret = 1;
1306 break;
1308 if (!cert)
1309 break;
1311 store = SSL_CTX_get_cert_store (ctx);
1312 if (!store)
1313 break;
1315 if (!X509_STORE_add_cert (store, cert))
1316 break;
1318 if (cert)
1320 X509_free (cert);
1321 cert = NULL;
1325 err:
1326 if (cert)
1327 X509_free (cert);
1328 if (in)
1329 BIO_free (in);
1330 return ret;
1333 static int
1334 xname_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1336 return(X509_NAME_cmp(*a,*b));
1339 static STACK_OF(X509_NAME) *
1340 use_inline_load_client_CA_file (SSL_CTX *ctx, const char *ca_string)
1342 BIO *in = NULL;
1343 X509 *x = NULL;
1344 X509_NAME *xn = NULL;
1345 STACK_OF(X509_NAME) *ret = NULL, *sk;
1347 sk=sk_X509_NAME_new(xname_cmp);
1349 in = BIO_new_mem_buf ((char *)ca_string, -1);
1350 if (!in)
1351 goto err;
1353 if ((sk == NULL) || (in == NULL))
1354 goto err;
1356 for (;;)
1358 if (PEM_read_bio_X509(in,&x,NULL,NULL) == NULL)
1359 break;
1360 if (ret == NULL)
1362 ret = sk_X509_NAME_new_null();
1363 if (ret == NULL)
1364 goto err;
1366 if ((xn=X509_get_subject_name(x)) == NULL) goto err;
1367 /* check for duplicates */
1368 xn=X509_NAME_dup(xn);
1369 if (xn == NULL) goto err;
1370 if (sk_X509_NAME_find(sk,xn) >= 0)
1371 X509_NAME_free(xn);
1372 else
1374 sk_X509_NAME_push(sk,xn);
1375 sk_X509_NAME_push(ret,xn);
1379 if (0)
1381 err:
1382 if (ret != NULL) sk_X509_NAME_pop_free(ret,X509_NAME_free);
1383 ret=NULL;
1385 if (sk != NULL) sk_X509_NAME_free(sk);
1386 if (in != NULL) BIO_free(in);
1387 if (x != NULL) X509_free(x);
1388 if (ret != NULL)
1389 ERR_clear_error();
1390 return(ret);
1393 static int
1394 use_inline_certificate_file (SSL_CTX *ctx, const char *cert_string)
1396 BIO *in = NULL;
1397 X509 *x = NULL;
1398 int ret = 0;
1400 in = BIO_new_mem_buf ((char *)cert_string, -1);
1401 if (!in)
1402 goto end;
1404 x = PEM_read_bio_X509 (in,
1405 NULL,
1406 ctx->default_passwd_callback,
1407 ctx->default_passwd_callback_userdata);
1408 if (!x)
1409 goto end;
1411 ret = SSL_CTX_use_certificate(ctx, x);
1413 end:
1414 if (x)
1415 X509_free (x);
1416 if (in)
1417 BIO_free (in);
1418 return ret;
1421 static int
1422 use_inline_PrivateKey_file (SSL_CTX *ctx, const char *key_string)
1424 BIO *in = NULL;
1425 EVP_PKEY *pkey = NULL;
1426 int ret = 0;
1428 in = BIO_new_mem_buf ((char *)key_string, -1);
1429 if (!in)
1430 goto end;
1432 pkey = PEM_read_bio_PrivateKey (in,
1433 NULL,
1434 ctx->default_passwd_callback,
1435 ctx->default_passwd_callback_userdata);
1436 if (!pkey)
1437 goto end;
1439 ret = SSL_CTX_use_PrivateKey (ctx, pkey);
1441 end:
1442 if (pkey)
1443 EVP_PKEY_free (pkey);
1444 if (in)
1445 BIO_free (in);
1446 return ret;
1449 #endif
1452 * Initialize SSL context.
1453 * All files are in PEM format.
1455 SSL_CTX *
1456 init_ssl (const struct options *options)
1458 SSL_CTX *ctx = NULL;
1459 DH *dh;
1460 BIO *bio;
1461 bool using_cert_file = false;
1463 ERR_clear_error ();
1465 if (options->tls_server)
1467 ctx = SSL_CTX_new (TLSv1_server_method ());
1468 if (ctx == NULL)
1469 msg (M_SSLERR, "SSL_CTX_new TLSv1_server_method");
1471 SSL_CTX_set_tmp_rsa_callback (ctx, tmp_rsa_cb);
1473 #if ENABLE_INLINE_FILES
1474 if (!strcmp (options->dh_file, INLINE_FILE_TAG) && options->dh_file_inline)
1476 if (!(bio = BIO_new_mem_buf ((char *)options->dh_file_inline, -1)))
1477 msg (M_SSLERR, "Cannot open memory BIO for inline DH parameters");
1479 else
1480 #endif
1482 /* Get Diffie Hellman Parameters */
1483 if (!(bio = BIO_new_file (options->dh_file, "r")))
1484 msg (M_SSLERR, "Cannot open %s for DH parameters", options->dh_file);
1487 dh = PEM_read_bio_DHparams (bio, NULL, NULL, NULL);
1488 BIO_free (bio);
1489 if (!dh)
1490 msg (M_SSLERR, "Cannot load DH parameters from %s", options->dh_file);
1491 if (!SSL_CTX_set_tmp_dh (ctx, dh))
1492 msg (M_SSLERR, "SSL_CTX_set_tmp_dh");
1493 msg (D_TLS_DEBUG_LOW, "Diffie-Hellman initialized with %d bit key",
1494 8 * DH_size (dh));
1495 DH_free (dh);
1497 else /* if client */
1499 ctx = SSL_CTX_new (TLSv1_client_method ());
1500 if (ctx == NULL)
1501 msg (M_SSLERR, "SSL_CTX_new TLSv1_client_method");
1504 /* Set SSL options */
1505 SSL_CTX_set_session_cache_mode (ctx, SSL_SESS_CACHE_OFF);
1506 SSL_CTX_set_options (ctx, SSL_OP_SINGLE_DH_USE);
1508 /* Set callback for getting password from user to decrypt private key */
1509 SSL_CTX_set_default_passwd_cb (ctx, pem_password_callback);
1511 if (options->pkcs12_file)
1513 /* Use PKCS #12 file for key, cert and CA certs */
1515 FILE *fp;
1516 EVP_PKEY *pkey;
1517 X509 *cert;
1518 STACK_OF(X509) *ca = NULL;
1519 PKCS12 *p12;
1520 int i;
1521 char password[256];
1523 /* Load the PKCS #12 file */
1524 if (!(fp = fopen(options->pkcs12_file, "rb")))
1525 msg (M_SSLERR, "Error opening file %s", options->pkcs12_file);
1526 p12 = d2i_PKCS12_fp(fp, NULL);
1527 fclose (fp);
1528 if (!p12) msg (M_SSLERR, "Error reading PKCS#12 file %s", options->pkcs12_file);
1530 /* Parse the PKCS #12 file */
1531 if (!PKCS12_parse(p12, "", &pkey, &cert, &ca))
1533 pem_password_callback (password, sizeof(password) - 1, 0, NULL);
1534 /* Reparse the PKCS #12 file with password */
1535 ca = NULL;
1536 if (!PKCS12_parse(p12, password, &pkey, &cert, &ca))
1538 PKCS12_free(p12);
1539 msg (M_WARN|M_SSL, "Error parsing PKCS#12 file %s", options->pkcs12_file);
1540 goto err;
1543 PKCS12_free(p12);
1545 /* Load Certificate */
1546 if (!SSL_CTX_use_certificate (ctx, cert))
1547 msg (M_SSLERR, "Cannot use certificate");
1549 /* Load Private Key */
1550 if (!SSL_CTX_use_PrivateKey (ctx, pkey))
1551 msg (M_SSLERR, "Cannot use private key");
1552 warn_if_group_others_accessible (options->pkcs12_file);
1554 /* Check Private Key */
1555 if (!SSL_CTX_check_private_key (ctx))
1556 msg (M_SSLERR, "Private key does not match the certificate");
1558 /* Set Certificate Verification chain */
1559 if (!options->ca_file)
1561 if (ca && sk_num(ca))
1563 for (i = 0; i < sk_X509_num(ca); i++)
1565 if (!X509_STORE_add_cert(ctx->cert_store,sk_X509_value(ca, i)))
1566 msg (M_SSLERR, "Cannot add certificate to certificate chain (X509_STORE_add_cert)");
1567 if (!SSL_CTX_add_client_CA(ctx, sk_X509_value(ca, i)))
1568 msg (M_SSLERR, "Cannot add certificate to client CA list (SSL_CTX_add_client_CA)");
1573 else
1575 /* Use seperate PEM files for key, cert and CA certs */
1577 #ifdef ENABLE_PKCS11
1578 if (options->pkcs11_providers[0])
1580 /* Load Certificate and Private Key */
1581 if (!SSL_CTX_use_pkcs11 (ctx, options->pkcs11_id_management, options->pkcs11_id))
1583 msg (M_WARN, "Cannot load certificate \"%s\" using PKCS#11 interface", options->pkcs11_id);
1584 goto err;
1587 else
1588 #endif
1590 #ifdef WIN32
1591 if (options->cryptoapi_cert)
1593 /* Load Certificate and Private Key */
1594 if (!SSL_CTX_use_CryptoAPI_certificate (ctx, options->cryptoapi_cert))
1595 msg (M_SSLERR, "Cannot load certificate \"%s\" from Microsoft Certificate Store",
1596 options->cryptoapi_cert);
1598 else
1599 #endif
1601 /* Load Certificate */
1602 if (options->cert_file)
1604 #if ENABLE_INLINE_FILES
1605 if (!strcmp (options->cert_file, INLINE_FILE_TAG) && options->cert_file_inline)
1607 if (!use_inline_certificate_file (ctx, options->cert_file_inline))
1608 msg (M_SSLERR, "Cannot load inline certificate file");
1610 else
1611 #endif
1613 if (!SSL_CTX_use_certificate_file (ctx, options->cert_file, SSL_FILETYPE_PEM))
1614 msg (M_SSLERR, "Cannot load certificate file %s", options->cert_file);
1615 using_cert_file = true;
1619 /* Load Private Key */
1620 if (options->priv_key_file)
1622 int status;
1624 #if ENABLE_INLINE_FILES
1625 if (!strcmp (options->priv_key_file, INLINE_FILE_TAG) && options->priv_key_file_inline)
1627 status = use_inline_PrivateKey_file (ctx, options->priv_key_file_inline);
1629 else
1630 #endif
1632 status = SSL_CTX_use_PrivateKey_file (ctx, options->priv_key_file, SSL_FILETYPE_PEM);
1634 if (!status)
1636 #ifdef ENABLE_MANAGEMENT
1637 if (management && (ERR_GET_REASON (ERR_peek_error()) == EVP_R_BAD_DECRYPT))
1638 management_auth_failure (management, UP_TYPE_PRIVATE_KEY);
1639 #endif
1640 msg (M_WARN|M_SSL, "Cannot load private key file %s", options->priv_key_file);
1641 goto err;
1643 warn_if_group_others_accessible (options->priv_key_file);
1645 /* Check Private Key */
1646 if (!SSL_CTX_check_private_key (ctx))
1647 msg (M_SSLERR, "Private key does not match the certificate");
1652 if (options->ca_file || options->ca_path)
1654 int status;
1656 #if ENABLE_INLINE_FILES
1657 if (options->ca_file && !strcmp (options->ca_file, INLINE_FILE_TAG) && options->ca_file_inline)
1659 status = use_inline_load_verify_locations (ctx, options->ca_file_inline);
1661 else
1662 #endif
1664 /* Load CA file for verifying peer supplied certificate */
1665 status = SSL_CTX_load_verify_locations (ctx, options->ca_file, options->ca_path);
1668 if (!status)
1669 msg (M_SSLERR, "Cannot load CA certificate file %s path %s (SSL_CTX_load_verify_locations)", options->ca_file, options->ca_path);
1671 /* Set a store for certs (CA & CRL) with a lookup on the "capath" hash directory */
1672 if (options->ca_path) {
1673 X509_STORE *store = SSL_CTX_get_cert_store(ctx);
1675 if (store)
1677 X509_LOOKUP *lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
1678 if (!X509_LOOKUP_add_dir(lookup, options->ca_path, X509_FILETYPE_PEM))
1679 X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
1680 else
1681 msg(M_WARN, "WARNING: experimental option --capath %s", options->ca_path);
1682 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
1683 X509_STORE_set_flags(store, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1684 #else
1685 msg(M_WARN, "WARNING: this version of OpenSSL cannot handle CRL files in capath");
1686 #endif
1688 else
1689 msg(M_SSLERR, "Cannot get certificate store (SSL_CTX_get_cert_store)");
1692 /* Load names of CAs from file and use it as a client CA list */
1693 if (options->ca_file) {
1694 STACK_OF(X509_NAME) *cert_names = NULL;
1695 #if ENABLE_INLINE_FILES
1696 if (!strcmp (options->ca_file, INLINE_FILE_TAG) && options->ca_file_inline)
1698 cert_names = use_inline_load_client_CA_file (ctx, options->ca_file_inline);
1700 else
1701 #endif
1703 cert_names = SSL_load_client_CA_file (options->ca_file);
1705 if (!cert_names)
1706 msg (M_SSLERR, "Cannot load CA certificate file %s (SSL_load_client_CA_file)", options->ca_file);
1707 SSL_CTX_set_client_CA_list (ctx, cert_names);
1711 /* Enable the use of certificate chains */
1712 if (using_cert_file)
1714 if (!SSL_CTX_use_certificate_chain_file (ctx, options->cert_file))
1715 msg (M_SSLERR, "Cannot load certificate chain file %s (SSL_use_certificate_chain_file)", options->cert_file);
1718 /* Require peer certificate verification */
1719 #if P2MP_SERVER
1720 if (options->ssl_flags & SSLF_CLIENT_CERT_NOT_REQUIRED)
1722 msg (M_WARN, "WARNING: POTENTIALLY DANGEROUS OPTION --client-cert-not-required may accept clients which do not present a certificate");
1724 else
1725 #endif
1726 SSL_CTX_set_verify (ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
1727 verify_callback);
1729 /* Connection information callback */
1730 SSL_CTX_set_info_callback (ctx, info_callback);
1732 /* Allowable ciphers */
1733 if (options->cipher_list)
1735 if (!SSL_CTX_set_cipher_list (ctx, options->cipher_list))
1736 msg (M_SSLERR, "Problem with cipher list: %s", options->cipher_list);
1739 ERR_clear_error ();
1741 return ctx;
1743 err:
1744 ERR_clear_error ();
1745 if (ctx)
1746 SSL_CTX_free (ctx);
1747 return NULL;
1751 * Print a one line summary of SSL/TLS session handshake.
1753 static void
1754 print_details (SSL * c_ssl, const char *prefix)
1756 SSL_CIPHER *ciph;
1757 X509 *cert;
1758 char s1[256];
1759 char s2[256];
1761 s1[0] = s2[0] = 0;
1762 ciph = SSL_get_current_cipher (c_ssl);
1763 openvpn_snprintf (s1, sizeof (s1), "%s %s, cipher %s %s",
1764 prefix,
1765 SSL_get_version (c_ssl),
1766 SSL_CIPHER_get_version (ciph),
1767 SSL_CIPHER_get_name (ciph));
1768 cert = SSL_get_peer_certificate (c_ssl);
1769 if (cert != NULL)
1771 EVP_PKEY *pkey = X509_get_pubkey (cert);
1772 if (pkey != NULL)
1774 if (pkey->type == EVP_PKEY_RSA && pkey->pkey.rsa != NULL
1775 && pkey->pkey.rsa->n != NULL)
1777 openvpn_snprintf (s2, sizeof (s2), ", %d bit RSA",
1778 BN_num_bits (pkey->pkey.rsa->n));
1780 else if (pkey->type == EVP_PKEY_DSA && pkey->pkey.dsa != NULL
1781 && pkey->pkey.dsa->p != NULL)
1783 openvpn_snprintf (s2, sizeof (s2), ", %d bit DSA",
1784 BN_num_bits (pkey->pkey.dsa->p));
1786 EVP_PKEY_free (pkey);
1788 X509_free (cert);
1790 /* The SSL API does not allow us to look at temporary RSA/DH keys,
1791 * otherwise we should print their lengths too */
1792 msg (D_HANDSHAKE, "%s%s", s1, s2);
1796 * Show the TLS ciphers that are available for us to use
1797 * in the OpenSSL library.
1799 void
1800 show_available_tls_ciphers ()
1802 SSL_CTX *ctx;
1803 SSL *ssl;
1804 const char *cipher_name;
1805 int priority = 0;
1807 ctx = SSL_CTX_new (TLSv1_method ());
1808 if (!ctx)
1809 msg (M_SSLERR, "Cannot create SSL_CTX object");
1810 ssl = SSL_new (ctx);
1811 if (!ssl)
1812 msg (M_SSLERR, "Cannot create SSL object");
1814 printf ("Available TLS Ciphers,\n");
1815 printf ("listed in order of preference:\n\n");
1816 while ((cipher_name = SSL_get_cipher_list (ssl, priority++)))
1817 printf ("%s\n", cipher_name);
1818 printf ("\n");
1820 SSL_free (ssl);
1821 SSL_CTX_free (ctx);
1825 * The OpenSSL library has a notion of preference in TLS
1826 * ciphers. Higher preference == more secure.
1827 * Return the highest preference cipher.
1829 void
1830 get_highest_preference_tls_cipher (char *buf, int size)
1832 SSL_CTX *ctx;
1833 SSL *ssl;
1834 const char *cipher_name;
1836 ctx = SSL_CTX_new (TLSv1_method ());
1837 if (!ctx)
1838 msg (M_SSLERR, "Cannot create SSL_CTX object");
1839 ssl = SSL_new (ctx);
1840 if (!ssl)
1841 msg (M_SSLERR, "Cannot create SSL object");
1843 cipher_name = SSL_get_cipher_list (ssl, 0);
1844 strncpynt (buf, cipher_name, size);
1846 SSL_free (ssl);
1847 SSL_CTX_free (ctx);
1851 * Map internal constants to ascii names.
1853 static const char *
1854 state_name (int state)
1856 switch (state)
1858 case S_UNDEF:
1859 return "S_UNDEF";
1860 case S_INITIAL:
1861 return "S_INITIAL";
1862 case S_PRE_START:
1863 return "S_PRE_START";
1864 case S_START:
1865 return "S_START";
1866 case S_SENT_KEY:
1867 return "S_SENT_KEY";
1868 case S_GOT_KEY:
1869 return "S_GOT_KEY";
1870 case S_ACTIVE:
1871 return "S_ACTIVE";
1872 case S_NORMAL_OP:
1873 return "S_NORMAL_OP";
1874 case S_ERROR:
1875 return "S_ERROR";
1876 default:
1877 return "S_???";
1881 static const char *
1882 packet_opcode_name (int op)
1884 switch (op)
1886 case P_CONTROL_HARD_RESET_CLIENT_V1:
1887 return "P_CONTROL_HARD_RESET_CLIENT_V1";
1888 case P_CONTROL_HARD_RESET_SERVER_V1:
1889 return "P_CONTROL_HARD_RESET_SERVER_V1";
1890 case P_CONTROL_HARD_RESET_CLIENT_V2:
1891 return "P_CONTROL_HARD_RESET_CLIENT_V2";
1892 case P_CONTROL_HARD_RESET_SERVER_V2:
1893 return "P_CONTROL_HARD_RESET_SERVER_V2";
1894 case P_CONTROL_SOFT_RESET_V1:
1895 return "P_CONTROL_SOFT_RESET_V1";
1896 case P_CONTROL_V1:
1897 return "P_CONTROL_V1";
1898 case P_ACK_V1:
1899 return "P_ACK_V1";
1900 case P_DATA_V1:
1901 return "P_DATA_V1";
1902 default:
1903 return "P_???";
1907 static const char *
1908 session_index_name (int index)
1910 switch (index)
1912 case TM_ACTIVE:
1913 return "TM_ACTIVE";
1914 case TM_UNTRUSTED:
1915 return "TM_UNTRUSTED";
1916 case TM_LAME_DUCK:
1917 return "TM_LAME_DUCK";
1918 default:
1919 return "TM_???";
1924 * For debugging.
1926 static const char *
1927 print_key_id (struct tls_multi *multi, struct gc_arena *gc)
1929 int i;
1930 struct buffer out = alloc_buf_gc (256, gc);
1932 for (i = 0; i < KEY_SCAN_SIZE; ++i)
1934 struct key_state *ks = multi->key_scan[i];
1935 buf_printf (&out, " [key#%d state=%s id=%d sid=%s]", i,
1936 state_name (ks->state), ks->key_id,
1937 session_id_print (&ks->session_id_remote, gc));
1940 return BSTR (&out);
1944 * Given a key_method, return true if op
1945 * represents the required form of hard_reset.
1947 * If key_method = 0, return true if any
1948 * form of hard reset is used.
1950 static bool
1951 is_hard_reset (int op, int key_method)
1953 if (!key_method || key_method == 1)
1954 if (op == P_CONTROL_HARD_RESET_CLIENT_V1 || op == P_CONTROL_HARD_RESET_SERVER_V1)
1955 return true;
1957 if (!key_method || key_method >= 2)
1958 if (op == P_CONTROL_HARD_RESET_CLIENT_V2 || op == P_CONTROL_HARD_RESET_SERVER_V2)
1959 return true;
1961 return false;
1965 * OpenVPN's interface to SSL/TLS authentication,
1966 * encryption, and decryption is exclusively
1967 * through "memory BIOs".
1969 static BIO *
1970 getbio (BIO_METHOD * type, const char *desc)
1972 BIO *ret;
1973 ret = BIO_new (type);
1974 if (!ret)
1975 msg (M_SSLERR, "Error creating %s BIO", desc);
1976 return ret;
1980 * Write to an OpenSSL BIO in non-blocking mode.
1982 static int
1983 bio_write (struct tls_multi* multi, BIO *bio, const uint8_t *data, int size, const char *desc)
1985 int i;
1986 int ret = 0;
1987 ASSERT (size >= 0);
1988 if (size)
1991 * Free the L_TLS lock prior to calling BIO routines
1992 * so that foreground thread can still call
1993 * tls_pre_decrypt or tls_pre_encrypt,
1994 * allowing tunnel packet forwarding to continue.
1996 #ifdef BIO_DEBUG
1997 bio_debug_data ("write", bio, data, size, desc);
1998 #endif
1999 i = BIO_write (bio, data, size);
2001 if (i < 0)
2003 if (BIO_should_retry (bio))
2007 else
2009 msg (D_TLS_ERRORS | M_SSL, "TLS ERROR: BIO write %s error",
2010 desc);
2011 ret = -1;
2012 ERR_clear_error ();
2015 else if (i != size)
2017 msg (D_TLS_ERRORS | M_SSL,
2018 "TLS ERROR: BIO write %s incomplete %d/%d", desc, i, size);
2019 ret = -1;
2020 ERR_clear_error ();
2022 else
2023 { /* successful write */
2024 dmsg (D_HANDSHAKE_VERBOSE, "BIO write %s %d bytes", desc, i);
2025 ret = 1;
2028 return ret;
2032 * Read from an OpenSSL BIO in non-blocking mode.
2034 static int
2035 bio_read (struct tls_multi* multi, BIO *bio, struct buffer *buf, int maxlen, const char *desc)
2037 int i;
2038 int ret = 0;
2039 ASSERT (buf->len >= 0);
2040 if (buf->len)
2044 else
2046 int len = buf_forward_capacity (buf);
2047 if (maxlen < len)
2048 len = maxlen;
2051 * BIO_read brackets most of the serious RSA
2052 * key negotiation number crunching.
2054 i = BIO_read (bio, BPTR (buf), len);
2056 VALGRIND_MAKE_READABLE ((void *) &i, sizeof (i));
2058 #ifdef BIO_DEBUG
2059 bio_debug_data ("read", bio, BPTR (buf), i, desc);
2060 #endif
2061 if (i < 0)
2063 if (BIO_should_retry (bio))
2067 else
2069 msg (D_TLS_ERRORS | M_SSL, "TLS_ERROR: BIO read %s error",
2070 desc);
2071 buf->len = 0;
2072 ret = -1;
2073 ERR_clear_error ();
2076 else if (!i)
2078 buf->len = 0;
2080 else
2081 { /* successful read */
2082 dmsg (D_HANDSHAKE_VERBOSE, "BIO read %s %d bytes", desc, i);
2083 buf->len = i;
2084 ret = 1;
2085 VALGRIND_MAKE_READABLE ((void *) BPTR (buf), BLEN (buf));
2088 return ret;
2092 * Inline functions for reading from and writing
2093 * to BIOs.
2096 static void
2097 bio_write_post (const int status, struct buffer *buf)
2099 if (status == 1) /* success status return from bio_write? */
2101 memset (BPTR (buf), 0, BLEN (buf)); /* erase data just written */
2102 buf->len = 0;
2106 static int
2107 key_state_write_plaintext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf)
2109 int ret;
2110 perf_push (PERF_BIO_WRITE_PLAINTEXT);
2111 ret = bio_write (multi, ks->ssl_bio, BPTR(buf), BLEN(buf), "tls_write_plaintext");
2112 bio_write_post (ret, buf);
2113 perf_pop ();
2114 return ret;
2117 static int
2118 key_state_write_plaintext_const (struct tls_multi *multi, struct key_state *ks, const uint8_t *data, int len)
2120 int ret;
2121 perf_push (PERF_BIO_WRITE_PLAINTEXT);
2122 ret = bio_write (multi, ks->ssl_bio, data, len, "tls_write_plaintext_const");
2123 perf_pop ();
2124 return ret;
2127 static int
2128 key_state_write_ciphertext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf)
2130 int ret;
2131 perf_push (PERF_BIO_WRITE_CIPHERTEXT);
2132 ret = bio_write (multi, ks->ct_in, BPTR(buf), BLEN(buf), "tls_write_ciphertext");
2133 bio_write_post (ret, buf);
2134 perf_pop ();
2135 return ret;
2138 static int
2139 key_state_read_plaintext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf,
2140 int maxlen)
2142 int ret;
2143 perf_push (PERF_BIO_READ_PLAINTEXT);
2144 ret = bio_read (multi, ks->ssl_bio, buf, maxlen, "tls_read_plaintext");
2145 perf_pop ();
2146 return ret;
2149 static int
2150 key_state_read_ciphertext (struct tls_multi *multi, struct key_state *ks, struct buffer *buf,
2151 int maxlen)
2153 int ret;
2154 perf_push (PERF_BIO_READ_CIPHERTEXT);
2155 ret = bio_read (multi, ks->ct_out, buf, maxlen, "tls_read_ciphertext");
2156 perf_pop ();
2157 return ret;
2161 * Initialize a key_state. Each key_state corresponds to
2162 * a specific SSL/TLS session.
2164 static void
2165 key_state_init (struct tls_session *session, struct key_state *ks)
2167 update_time ();
2170 * Build TLS object that reads/writes ciphertext
2171 * to/from memory BIOs.
2173 CLEAR (*ks);
2175 ks->ssl = SSL_new (session->opt->ssl_ctx);
2176 if (!ks->ssl)
2177 msg (M_SSLERR, "SSL_new failed");
2179 /* put session * in ssl object so we can access it
2180 from verify callback*/
2181 SSL_set_ex_data (ks->ssl, mydata_index, session);
2183 ks->ssl_bio = getbio (BIO_f_ssl (), "ssl_bio");
2184 ks->ct_in = getbio (BIO_s_mem (), "ct_in");
2185 ks->ct_out = getbio (BIO_s_mem (), "ct_out");
2187 #ifdef BIO_DEBUG
2188 bio_debug_oc ("open ssl_bio", ks->ssl_bio);
2189 bio_debug_oc ("open ct_in", ks->ct_in);
2190 bio_debug_oc ("open ct_out", ks->ct_out);
2191 #endif
2193 if (session->opt->server)
2194 SSL_set_accept_state (ks->ssl);
2195 else
2196 SSL_set_connect_state (ks->ssl);
2198 SSL_set_bio (ks->ssl, ks->ct_in, ks->ct_out);
2199 BIO_set_ssl (ks->ssl_bio, ks->ssl, BIO_NOCLOSE);
2201 /* Set control-channel initiation mode */
2202 ks->initial_opcode = session->initial_opcode;
2203 session->initial_opcode = P_CONTROL_SOFT_RESET_V1;
2204 ks->state = S_INITIAL;
2205 ks->key_id = session->key_id;
2208 * key_id increments to KEY_ID_MASK then recycles back to 1.
2209 * This way you know that if key_id is 0, it is the first key.
2211 ++session->key_id;
2212 session->key_id &= P_KEY_ID_MASK;
2213 if (!session->key_id)
2214 session->key_id = 1;
2216 /* allocate key source material object */
2217 ALLOC_OBJ_CLEAR (ks->key_src, struct key_source2);
2219 /* allocate reliability objects */
2220 ALLOC_OBJ_CLEAR (ks->send_reliable, struct reliable);
2221 ALLOC_OBJ_CLEAR (ks->rec_reliable, struct reliable);
2222 ALLOC_OBJ_CLEAR (ks->rec_ack, struct reliable_ack);
2224 /* allocate buffers */
2225 ks->plaintext_read_buf = alloc_buf (TLS_CHANNEL_BUF_SIZE);
2226 ks->plaintext_write_buf = alloc_buf (TLS_CHANNEL_BUF_SIZE);
2227 ks->ack_write_buf = alloc_buf (BUF_SIZE (&session->opt->frame));
2228 reliable_init (ks->send_reliable, BUF_SIZE (&session->opt->frame),
2229 FRAME_HEADROOM (&session->opt->frame), TLS_RELIABLE_N_SEND_BUFFERS,
2230 ks->key_id ? false : session->opt->xmit_hold);
2231 reliable_init (ks->rec_reliable, BUF_SIZE (&session->opt->frame),
2232 FRAME_HEADROOM (&session->opt->frame), TLS_RELIABLE_N_REC_BUFFERS,
2233 false);
2234 reliable_set_timeout (ks->send_reliable, session->opt->packet_timeout);
2236 /* init packet ID tracker */
2237 packet_id_init (&ks->packet_id,
2238 session->opt->replay_window,
2239 session->opt->replay_time);
2241 #ifdef MANAGEMENT_DEF_AUTH
2242 ks->mda_key_id = session->opt->mda_context->mda_key_id_counter++;
2243 #endif
2246 static void
2247 key_state_free (struct key_state *ks, bool clear)
2249 ks->state = S_UNDEF;
2251 if (ks->ssl) {
2252 #ifdef BIO_DEBUG
2253 bio_debug_oc ("close ssl_bio", ks->ssl_bio);
2254 bio_debug_oc ("close ct_in", ks->ct_in);
2255 bio_debug_oc ("close ct_out", ks->ct_out);
2256 #endif
2257 BIO_free_all(ks->ssl_bio);
2258 SSL_free (ks->ssl);
2261 free_key_ctx_bi (&ks->key);
2262 free_buf (&ks->plaintext_read_buf);
2263 free_buf (&ks->plaintext_write_buf);
2264 free_buf (&ks->ack_write_buf);
2266 if (ks->send_reliable)
2268 reliable_free (ks->send_reliable);
2269 free (ks->send_reliable);
2272 if (ks->rec_reliable)
2274 reliable_free (ks->rec_reliable);
2275 free (ks->rec_reliable);
2278 if (ks->rec_ack)
2279 free (ks->rec_ack);
2281 if (ks->key_src)
2282 free (ks->key_src);
2284 packet_id_free (&ks->packet_id);
2286 #ifdef PLUGIN_DEF_AUTH
2287 key_state_rm_auth_control_file (ks);
2288 #endif
2290 if (clear)
2291 CLEAR (*ks);
2295 * Must be called if we move a tls_session in memory.
2297 static inline void tls_session_set_self_referential_pointers (struct tls_session* session) {
2298 session->tls_auth.packet_id = &session->tls_auth_pid;
2302 * Initialize a TLS session. A TLS session normally has 2 key_state objects,
2303 * one for the current key, and one for the lame duck (i.e. retiring) key.
2305 static void
2306 tls_session_init (struct tls_multi *multi, struct tls_session *session)
2308 struct gc_arena gc = gc_new ();
2310 dmsg (D_TLS_DEBUG, "TLS: tls_session_init: entry");
2312 CLEAR (*session);
2314 /* Set options data to point to parent's option structure */
2315 session->opt = &multi->opt;
2317 /* Randomize session # if it is 0 */
2318 while (!session_id_defined(&session->session_id))
2319 session_id_random (&session->session_id);
2321 /* Are we a TLS server or client? */
2322 ASSERT (session->opt->key_method >= 1);
2323 if (session->opt->key_method == 1)
2325 session->initial_opcode = session->opt->server ?
2326 P_CONTROL_HARD_RESET_SERVER_V1 : P_CONTROL_HARD_RESET_CLIENT_V1;
2328 else /* session->opt->key_method >= 2 */
2330 session->initial_opcode = session->opt->server ?
2331 P_CONTROL_HARD_RESET_SERVER_V2 : P_CONTROL_HARD_RESET_CLIENT_V2;
2334 /* Initialize control channel authentication parameters */
2335 session->tls_auth = session->opt->tls_auth;
2337 /* Set session internal pointers (also called if session object is moved in memory) */
2338 tls_session_set_self_referential_pointers (session);
2340 /* initialize packet ID replay window for --tls-auth */
2341 packet_id_init (session->tls_auth.packet_id,
2342 session->opt->replay_window,
2343 session->opt->replay_time);
2345 /* load most recent packet-id to replay protect on --tls-auth */
2346 packet_id_persist_load_obj (session->tls_auth.pid_persist, session->tls_auth.packet_id);
2348 key_state_init (session, &session->key[KS_PRIMARY]);
2350 dmsg (D_TLS_DEBUG, "TLS: tls_session_init: new session object, sid=%s",
2351 session_id_print (&session->session_id, &gc));
2353 gc_free (&gc);
2356 static void
2357 tls_session_free (struct tls_session *session, bool clear)
2359 int i;
2361 if (session->tls_auth.packet_id)
2362 packet_id_free (session->tls_auth.packet_id);
2364 for (i = 0; i < KS_SIZE; ++i)
2365 key_state_free (&session->key[i], false);
2367 if (session->common_name)
2368 free (session->common_name);
2370 cert_hash_free (session->cert_hash_set);
2372 if (clear)
2373 CLEAR (*session);
2376 static void
2377 move_session (struct tls_multi* multi, int dest, int src, bool reinit_src)
2379 msg (D_TLS_DEBUG_LOW, "TLS: move_session: dest=%s src=%s reinit_src=%d",
2380 session_index_name(dest),
2381 session_index_name(src),
2382 reinit_src);
2383 ASSERT (src != dest);
2384 ASSERT (src >= 0 && src < TM_SIZE);
2385 ASSERT (dest >= 0 && dest < TM_SIZE);
2386 tls_session_free (&multi->session[dest], false);
2387 multi->session[dest] = multi->session[src];
2388 tls_session_set_self_referential_pointers (&multi->session[dest]);
2390 if (reinit_src)
2391 tls_session_init (multi, &multi->session[src]);
2392 else
2393 CLEAR (multi->session[src]);
2395 dmsg (D_TLS_DEBUG, "TLS: move_session: exit");
2398 static void
2399 reset_session (struct tls_multi *multi, struct tls_session *session)
2401 tls_session_free (session, false);
2402 tls_session_init (multi, session);
2405 #if 0
2407 * Transmit a TLS reset on our untrusted channel.
2409 static void
2410 initiate_untrusted_session (struct tls_multi *multi, struct sockaddr_in *to)
2412 struct tls_session *session = &multi->session[TM_UNTRUSTED];
2413 struct key_state *ks = &session->key[KS_PRIMARY];
2415 reset_session (multi, session);
2416 ks->remote_addr = *to;
2417 msg (D_TLS_DEBUG_LOW, "TLS: initiate_untrusted_session: addr=%s", print_sockaddr (to));
2419 #endif
2422 * Used to determine in how many seconds we should be
2423 * called again.
2425 static inline void
2426 compute_earliest_wakeup (interval_t *earliest, interval_t seconds_from_now) {
2427 if (seconds_from_now < *earliest)
2428 *earliest = seconds_from_now;
2429 if (*earliest < 0)
2430 *earliest = 0;
2434 * Return true if "lame duck" or retiring key has expired and can
2435 * no longer be used.
2437 static inline bool
2438 lame_duck_must_die (const struct tls_session* session, interval_t *wakeup)
2440 const struct key_state* lame = &session->key[KS_LAME_DUCK];
2441 if (lame->state >= S_INITIAL)
2443 const time_t local_now = now;
2444 ASSERT (lame->must_die); /* a lame duck key must always have an expiration */
2445 if (local_now < lame->must_die)
2447 compute_earliest_wakeup (wakeup, lame->must_die - local_now);
2448 return false;
2450 else
2451 return true;
2453 else if (lame->state == S_ERROR)
2454 return true;
2455 else
2456 return false;
2460 * A tls_multi object fully encapsulates OpenVPN's TLS state.
2461 * See ssl.h for more comments.
2463 struct tls_multi *
2464 tls_multi_init (struct tls_options *tls_options)
2466 struct tls_multi *ret;
2468 ALLOC_OBJ_CLEAR (ret, struct tls_multi);
2470 /* get command line derived options */
2471 ret->opt = *tls_options;
2473 /* set up pointer to HMAC object for TLS packet authentication */
2474 ret->opt.tls_auth.key_ctx_bi = &ret->opt.tls_auth_key;
2476 /* set up list of keys to be scanned by data channel encrypt and decrypt routines */
2477 ASSERT (SIZE (ret->key_scan) == 3);
2478 ret->key_scan[0] = &ret->session[TM_ACTIVE].key[KS_PRIMARY];
2479 ret->key_scan[1] = &ret->session[TM_ACTIVE].key[KS_LAME_DUCK];
2480 ret->key_scan[2] = &ret->session[TM_LAME_DUCK].key[KS_LAME_DUCK];
2482 return ret;
2486 * Finalize our computation of frame sizes.
2488 void
2489 tls_multi_init_finalize (struct tls_multi* multi, const struct frame* frame)
2491 tls_init_control_channel_frame_parameters (frame, &multi->opt.frame);
2493 /* initialize the active and untrusted sessions */
2495 tls_session_init (multi, &multi->session[TM_ACTIVE]);
2497 if (!multi->opt.single_session)
2498 tls_session_init (multi, &multi->session[TM_UNTRUSTED]);
2502 * Initialize and finalize a standalone tls-auth verification object.
2505 struct tls_auth_standalone *
2506 tls_auth_standalone_init (struct tls_options *tls_options,
2507 struct gc_arena *gc)
2509 struct tls_auth_standalone *tas;
2511 ALLOC_OBJ_CLEAR_GC (tas, struct tls_auth_standalone, gc);
2513 /* set up pointer to HMAC object for TLS packet authentication */
2514 tas->tls_auth_key = tls_options->tls_auth_key;
2515 tas->tls_auth_options.key_ctx_bi = &tas->tls_auth_key;
2516 tas->tls_auth_options.flags |= CO_PACKET_ID_LONG_FORM;
2518 /* get initial frame parms, still need to finalize */
2519 tas->frame = tls_options->frame;
2521 return tas;
2524 void
2525 tls_auth_standalone_finalize (struct tls_auth_standalone *tas,
2526 const struct frame *frame)
2528 tls_init_control_channel_frame_parameters (frame, &tas->frame);
2532 * Set local and remote option compatibility strings.
2533 * Used to verify compatibility of local and remote option
2534 * sets.
2536 void
2537 tls_multi_init_set_options (struct tls_multi* multi,
2538 const char *local,
2539 const char *remote)
2541 #ifdef ENABLE_OCC
2542 /* initialize options string */
2543 multi->opt.local_options = local;
2544 multi->opt.remote_options = remote;
2545 #endif
2548 void
2549 tls_multi_free (struct tls_multi *multi, bool clear)
2551 int i;
2553 ASSERT (multi);
2555 #ifdef MANAGEMENT_DEF_AUTH
2556 man_def_auth_set_client_reason(multi, NULL);
2557 #endif
2559 if (multi->locked_cn)
2560 free (multi->locked_cn);
2562 if (multi->locked_username)
2563 free (multi->locked_username);
2565 cert_hash_free (multi->locked_cert_hash_set);
2567 for (i = 0; i < TM_SIZE; ++i)
2568 tls_session_free (&multi->session[i], false);
2570 if (clear)
2571 CLEAR (*multi);
2573 free(multi);
2577 * Move a packet authentication HMAC + related fields to or from the front
2578 * of the buffer so it can be processed by encrypt/decrypt.
2582 * Dependent on hmac size, opcode size, and session_id size.
2583 * Will assert if too small.
2585 #define SWAP_BUF_SIZE 256
2587 static bool
2588 swap_hmac (struct buffer *buf, const struct crypto_options *co, bool incoming)
2590 struct key_ctx *ctx;
2592 ASSERT (co);
2594 ctx = (incoming ? &co->key_ctx_bi->decrypt : &co->key_ctx_bi->encrypt);
2595 ASSERT (ctx->hmac);
2598 /* hmac + packet_id (8 bytes) */
2599 const int hmac_size = HMAC_size (ctx->hmac) + packet_id_size (true);
2601 /* opcode + session_id */
2602 const int osid_size = 1 + SID_SIZE;
2604 int e1, e2;
2605 uint8_t *b = BPTR (buf);
2606 uint8_t buf1[SWAP_BUF_SIZE];
2607 uint8_t buf2[SWAP_BUF_SIZE];
2609 if (incoming)
2611 e1 = osid_size;
2612 e2 = hmac_size;
2614 else
2616 e1 = hmac_size;
2617 e2 = osid_size;
2620 ASSERT (e1 <= SWAP_BUF_SIZE && e2 <= SWAP_BUF_SIZE);
2622 if (buf->len >= e1 + e2)
2624 memcpy (buf1, b, e1);
2625 memcpy (buf2, b + e1, e2);
2626 memcpy (b, buf2, e2);
2627 memcpy (b + e2, buf1, e1);
2628 return true;
2630 else
2631 return false;
2635 #undef SWAP_BUF_SIZE
2638 * Write a control channel authentication record.
2640 static void
2641 write_control_auth (struct tls_session *session,
2642 struct key_state *ks,
2643 struct buffer *buf,
2644 struct link_socket_actual **to_link_addr,
2645 int opcode,
2646 int max_ack,
2647 bool prepend_ack)
2649 uint8_t *header;
2650 struct buffer null = clear_buf ();
2652 ASSERT (link_socket_actual_defined (&ks->remote_addr));
2653 ASSERT (reliable_ack_write
2654 (ks->rec_ack, buf, &ks->session_id_remote, max_ack, prepend_ack));
2655 ASSERT (session_id_write_prepend (&session->session_id, buf));
2656 ASSERT (header = buf_prepend (buf, 1));
2657 *header = ks->key_id | (opcode << P_OPCODE_SHIFT);
2658 if (session->tls_auth.key_ctx_bi->encrypt.hmac)
2660 /* no encryption, only write hmac */
2661 openvpn_encrypt (buf, null, &session->tls_auth, NULL);
2662 ASSERT (swap_hmac (buf, &session->tls_auth, false));
2664 *to_link_addr = &ks->remote_addr;
2668 * Read a control channel authentication record.
2670 static bool
2671 read_control_auth (struct buffer *buf,
2672 const struct crypto_options *co,
2673 const struct link_socket_actual *from)
2675 struct gc_arena gc = gc_new ();
2677 if (co->key_ctx_bi->decrypt.hmac)
2679 struct buffer null = clear_buf ();
2681 /* move the hmac record to the front of the packet */
2682 if (!swap_hmac (buf, co, true))
2684 msg (D_TLS_ERRORS,
2685 "TLS Error: cannot locate HMAC in incoming packet from %s",
2686 print_link_socket_actual (from, &gc));
2687 gc_free (&gc);
2688 return false;
2691 /* authenticate only (no decrypt) and remove the hmac record
2692 from the head of the buffer */
2693 openvpn_decrypt (buf, null, co, NULL);
2694 if (!buf->len)
2696 msg (D_TLS_ERRORS,
2697 "TLS Error: incoming packet authentication failed from %s",
2698 print_link_socket_actual (from, &gc));
2699 gc_free (&gc);
2700 return false;
2705 /* advance buffer pointer past opcode & session_id since our caller
2706 already read it */
2707 buf_advance (buf, SID_SIZE + 1);
2709 gc_free (&gc);
2710 return true;
2714 * For debugging, print contents of key_source2 structure.
2717 static void
2718 key_source_print (const struct key_source *k,
2719 const char *prefix)
2721 struct gc_arena gc = gc_new ();
2723 VALGRIND_MAKE_READABLE ((void *)k->pre_master, sizeof (k->pre_master));
2724 VALGRIND_MAKE_READABLE ((void *)k->random1, sizeof (k->random1));
2725 VALGRIND_MAKE_READABLE ((void *)k->random2, sizeof (k->random2));
2727 dmsg (D_SHOW_KEY_SOURCE,
2728 "%s pre_master: %s",
2729 prefix,
2730 format_hex (k->pre_master, sizeof (k->pre_master), 0, &gc));
2731 dmsg (D_SHOW_KEY_SOURCE,
2732 "%s random1: %s",
2733 prefix,
2734 format_hex (k->random1, sizeof (k->random1), 0, &gc));
2735 dmsg (D_SHOW_KEY_SOURCE,
2736 "%s random2: %s",
2737 prefix,
2738 format_hex (k->random2, sizeof (k->random2), 0, &gc));
2740 gc_free (&gc);
2743 static void
2744 key_source2_print (const struct key_source2 *k)
2746 key_source_print (&k->client, "Client");
2747 key_source_print (&k->server, "Server");
2751 * Use the TLS PRF function for generating data channel keys.
2752 * This code is taken from the OpenSSL library.
2754 * TLS generates keys as such:
2756 * master_secret[48] = PRF(pre_master_secret[48], "master secret",
2757 * ClientHello.random[32] + ServerHello.random[32])
2759 * key_block[] = PRF(SecurityParameters.master_secret[48],
2760 * "key expansion",
2761 * SecurityParameters.server_random[32] +
2762 * SecurityParameters.client_random[32]);
2764 * Notes:
2766 * (1) key_block contains a full set of 4 keys.
2767 * (2) The pre-master secret is generated by the client.
2770 static void
2771 tls1_P_hash(const EVP_MD *md,
2772 const uint8_t *sec,
2773 int sec_len,
2774 const uint8_t *seed,
2775 int seed_len,
2776 uint8_t *out,
2777 int olen)
2779 struct gc_arena gc = gc_new ();
2780 int chunk,n;
2781 unsigned int j;
2782 HMAC_CTX ctx;
2783 HMAC_CTX ctx_tmp;
2784 uint8_t A1[EVP_MAX_MD_SIZE];
2785 unsigned int A1_len;
2787 #ifdef ENABLE_DEBUG
2788 const int olen_orig = olen;
2789 const uint8_t *out_orig = out;
2790 #endif
2792 dmsg (D_SHOW_KEY_SOURCE, "tls1_P_hash sec: %s", format_hex (sec, sec_len, 0, &gc));
2793 dmsg (D_SHOW_KEY_SOURCE, "tls1_P_hash seed: %s", format_hex (seed, seed_len, 0, &gc));
2795 chunk=EVP_MD_size(md);
2797 HMAC_CTX_init(&ctx);
2798 HMAC_CTX_init(&ctx_tmp);
2799 HMAC_Init_ex(&ctx,sec,sec_len,md, NULL);
2800 HMAC_Init_ex(&ctx_tmp,sec,sec_len,md, NULL);
2801 HMAC_Update(&ctx,seed,seed_len);
2802 HMAC_Final(&ctx,A1,&A1_len);
2804 n=0;
2805 for (;;)
2807 HMAC_Init_ex(&ctx,NULL,0,NULL,NULL); /* re-init */
2808 HMAC_Init_ex(&ctx_tmp,NULL,0,NULL,NULL); /* re-init */
2809 HMAC_Update(&ctx,A1,A1_len);
2810 HMAC_Update(&ctx_tmp,A1,A1_len);
2811 HMAC_Update(&ctx,seed,seed_len);
2813 if (olen > chunk)
2815 HMAC_Final(&ctx,out,&j);
2816 out+=j;
2817 olen-=j;
2818 HMAC_Final(&ctx_tmp,A1,&A1_len); /* calc the next A1 value */
2820 else /* last one */
2822 HMAC_Final(&ctx,A1,&A1_len);
2823 memcpy(out,A1,olen);
2824 break;
2827 HMAC_CTX_cleanup(&ctx);
2828 HMAC_CTX_cleanup(&ctx_tmp);
2829 CLEAR (A1);
2831 dmsg (D_SHOW_KEY_SOURCE, "tls1_P_hash out: %s", format_hex (out_orig, olen_orig, 0, &gc));
2832 gc_free (&gc);
2835 static void
2836 tls1_PRF(uint8_t *label,
2837 int label_len,
2838 const uint8_t *sec,
2839 int slen,
2840 uint8_t *out1,
2841 int olen)
2843 struct gc_arena gc = gc_new ();
2844 const EVP_MD *md5 = EVP_md5();
2845 const EVP_MD *sha1 = EVP_sha1();
2846 int len,i;
2847 const uint8_t *S1,*S2;
2848 uint8_t *out2;
2850 out2 = (uint8_t *) gc_malloc (olen, false, &gc);
2852 len=slen/2;
2853 S1=sec;
2854 S2= &(sec[len]);
2855 len+=(slen&1); /* add for odd, make longer */
2858 tls1_P_hash(md5 ,S1,len,label,label_len,out1,olen);
2859 tls1_P_hash(sha1,S2,len,label,label_len,out2,olen);
2861 for (i=0; i<olen; i++)
2862 out1[i]^=out2[i];
2864 memset (out2, 0, olen);
2866 dmsg (D_SHOW_KEY_SOURCE, "tls1_PRF out[%d]: %s", olen, format_hex (out1, olen, 0, &gc));
2868 gc_free (&gc);
2871 static void
2872 openvpn_PRF (const uint8_t *secret,
2873 int secret_len,
2874 const char *label,
2875 const uint8_t *client_seed,
2876 int client_seed_len,
2877 const uint8_t *server_seed,
2878 int server_seed_len,
2879 const struct session_id *client_sid,
2880 const struct session_id *server_sid,
2881 uint8_t *output,
2882 int output_len)
2884 /* concatenate seed components */
2886 struct buffer seed = alloc_buf (strlen (label)
2887 + client_seed_len
2888 + server_seed_len
2889 + SID_SIZE * 2);
2891 ASSERT (buf_write (&seed, label, strlen (label)));
2892 ASSERT (buf_write (&seed, client_seed, client_seed_len));
2893 ASSERT (buf_write (&seed, server_seed, server_seed_len));
2895 if (client_sid)
2896 ASSERT (buf_write (&seed, client_sid->id, SID_SIZE));
2897 if (server_sid)
2898 ASSERT (buf_write (&seed, server_sid->id, SID_SIZE));
2900 /* compute PRF */
2901 tls1_PRF (BPTR(&seed), BLEN(&seed), secret, secret_len, output, output_len);
2903 buf_clear (&seed);
2904 free_buf (&seed);
2906 VALGRIND_MAKE_READABLE ((void *)output, output_len);
2910 * Using source entropy from local and remote hosts, mix into
2911 * master key.
2913 static bool
2914 generate_key_expansion (struct key_ctx_bi *key,
2915 const struct key_type *key_type,
2916 const struct key_source2 *key_src,
2917 const struct session_id *client_sid,
2918 const struct session_id *server_sid,
2919 bool server)
2921 uint8_t master[48];
2922 struct key2 key2;
2923 bool ret = false;
2924 int i;
2926 CLEAR (master);
2927 CLEAR (key2);
2929 /* debugging print of source key material */
2930 key_source2_print (key_src);
2932 /* compute master secret */
2933 openvpn_PRF (key_src->client.pre_master,
2934 sizeof(key_src->client.pre_master),
2935 KEY_EXPANSION_ID " master secret",
2936 key_src->client.random1,
2937 sizeof(key_src->client.random1),
2938 key_src->server.random1,
2939 sizeof(key_src->server.random1),
2940 NULL,
2941 NULL,
2942 master,
2943 sizeof(master));
2945 /* compute key expansion */
2946 openvpn_PRF (master,
2947 sizeof(master),
2948 KEY_EXPANSION_ID " key expansion",
2949 key_src->client.random2,
2950 sizeof(key_src->client.random2),
2951 key_src->server.random2,
2952 sizeof(key_src->server.random2),
2953 client_sid,
2954 server_sid,
2955 (uint8_t*)key2.keys,
2956 sizeof(key2.keys));
2958 key2.n = 2;
2960 key2_print (&key2, key_type, "Master Encrypt", "Master Decrypt");
2962 /* check for weak keys */
2963 for (i = 0; i < 2; ++i)
2965 fixup_key (&key2.keys[i], key_type);
2966 if (!check_key (&key2.keys[i], key_type))
2968 msg (D_TLS_ERRORS, "TLS Error: Bad dynamic key generated");
2969 goto exit;
2973 /* Initialize OpenSSL key contexts */
2975 ASSERT (server == true || server == false);
2977 init_key_ctx (&key->encrypt,
2978 &key2.keys[(int)server],
2979 key_type,
2980 DO_ENCRYPT,
2981 "Data Channel Encrypt");
2983 init_key_ctx (&key->decrypt,
2984 &key2.keys[1-(int)server],
2985 key_type,
2986 DO_DECRYPT,
2987 "Data Channel Decrypt");
2989 ret = true;
2991 exit:
2992 CLEAR (master);
2993 CLEAR (key2);
2995 return ret;
2998 static bool
2999 random_bytes_to_buf (struct buffer *buf,
3000 uint8_t *out,
3001 int outlen)
3003 if (!RAND_bytes (out, outlen))
3004 msg (M_FATAL, "ERROR: Random number generator cannot obtain entropy for key generation [SSL]");
3005 if (!buf_write (buf, out, outlen))
3006 return false;
3007 return true;
3010 static bool
3011 key_source2_randomize_write (struct key_source2 *k2,
3012 struct buffer *buf,
3013 bool server)
3015 struct key_source *k = &k2->client;
3016 if (server)
3017 k = &k2->server;
3019 CLEAR (*k);
3021 if (!server)
3023 if (!random_bytes_to_buf (buf, k->pre_master, sizeof (k->pre_master)))
3024 return false;
3027 if (!random_bytes_to_buf (buf, k->random1, sizeof (k->random1)))
3028 return false;
3029 if (!random_bytes_to_buf (buf, k->random2, sizeof (k->random2)))
3030 return false;
3032 return true;
3035 static int
3036 key_source2_read (struct key_source2 *k2,
3037 struct buffer *buf,
3038 bool server)
3040 struct key_source *k = &k2->client;
3042 if (!server)
3043 k = &k2->server;
3045 CLEAR (*k);
3047 if (server)
3049 if (!buf_read (buf, k->pre_master, sizeof (k->pre_master)))
3050 return 0;
3053 if (!buf_read (buf, k->random1, sizeof (k->random1)))
3054 return 0;
3055 if (!buf_read (buf, k->random2, sizeof (k->random2)))
3056 return 0;
3058 return 1;
3062 * Macros for key_state_soft_reset & tls_process
3064 #define ks (&session->key[KS_PRIMARY]) /* primary key */
3065 #define ks_lame (&session->key[KS_LAME_DUCK]) /* retiring key */
3067 /* true if no in/out acknowledgements pending */
3068 #define FULL_SYNC \
3069 (reliable_empty(ks->send_reliable) && reliable_ack_empty (ks->rec_ack))
3072 * Move the active key to the lame duck key and reinitialize the
3073 * active key.
3075 static void
3076 key_state_soft_reset (struct tls_session *session)
3078 ks->must_die = now + session->opt->transition_window; /* remaining lifetime of old key */
3079 key_state_free (ks_lame, false);
3080 *ks_lame = *ks;
3082 key_state_init (session, ks);
3083 ks->session_id_remote = ks_lame->session_id_remote;
3084 ks->remote_addr = ks_lame->remote_addr;
3088 * Read/write strings from/to a struct buffer with a u16 length prefix.
3091 static bool
3092 write_string (struct buffer *buf, const char *str, const int maxlen)
3094 const int len = strlen (str) + 1;
3095 if (len < 1 || (maxlen >= 0 && len > maxlen))
3096 return false;
3097 if (!buf_write_u16 (buf, len))
3098 return false;
3099 if (!buf_write (buf, str, len))
3100 return false;
3101 return true;
3104 static bool
3105 read_string (struct buffer *buf, char *str, const unsigned int capacity)
3107 const int len = buf_read_u16 (buf);
3108 if (len < 1 || len > (int)capacity)
3109 return false;
3110 if (!buf_read (buf, str, len))
3111 return false;
3112 str[len-1] = '\0';
3113 return true;
3117 * Authenticate a client using username/password.
3118 * Runs on server.
3120 * If you want to add new authentication methods,
3121 * this is the place to start.
3124 static bool
3125 verify_user_pass_script (struct tls_session *session, const struct user_pass *up)
3127 struct gc_arena gc = gc_new ();
3128 struct argv argv = argv_new ();
3129 const char *tmp_file = "";
3130 int retval;
3131 bool ret = false;
3133 /* Is username defined? */
3134 if ((session->opt->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL) || strlen (up->username))
3136 /* Set environmental variables prior to calling script */
3137 setenv_str (session->opt->es, "script_type", "user-pass-verify");
3139 if (session->opt->auth_user_pass_verify_script_via_file)
3141 struct status_output *so;
3143 tmp_file = create_temp_filename (session->opt->tmp_dir, "up", &gc);
3144 so = status_open (tmp_file, 0, -1, NULL, STATUS_OUTPUT_WRITE);
3145 status_printf (so, "%s", up->username);
3146 status_printf (so, "%s", up->password);
3147 if (!status_close (so))
3149 msg (D_TLS_ERRORS, "TLS Auth Error: could not write username/password to file: %s",
3150 tmp_file);
3151 goto done;
3154 else
3156 setenv_str (session->opt->es, "username", up->username);
3157 setenv_str (session->opt->es, "password", up->password);
3160 /* setenv incoming cert common name for script */
3161 setenv_str (session->opt->es, "common_name", session->common_name);
3163 /* setenv client real IP address */
3164 setenv_untrusted (session);
3166 /* format command line */
3167 argv_printf (&argv, "%sc %s", session->opt->auth_user_pass_verify_script, tmp_file);
3169 /* call command */
3170 retval = openvpn_execve (&argv, session->opt->es, S_SCRIPT);
3172 /* test return status of command */
3173 if (system_ok (retval))
3174 ret = true;
3175 else if (!system_executed (retval))
3176 argv_msg_prefix (D_TLS_ERRORS, &argv, "TLS Auth Error: user-pass-verify script failed to execute");
3178 if (!session->opt->auth_user_pass_verify_script_via_file)
3179 setenv_del (session->opt->es, "password");
3181 else
3183 msg (D_TLS_ERRORS, "TLS Auth Error: peer provided a blank username");
3186 done:
3187 if (strlen (tmp_file) > 0)
3188 delete_file (tmp_file);
3190 argv_reset (&argv);
3191 gc_free (&gc);
3192 return ret;
3195 static int
3196 verify_user_pass_plugin (struct tls_session *session, const struct user_pass *up, const char *raw_username)
3198 int retval = OPENVPN_PLUGIN_FUNC_ERROR;
3200 /* Is username defined? */
3201 if ((session->opt->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL) || strlen (up->username))
3203 /* set username/password in private env space */
3204 setenv_str (session->opt->es, "username", raw_username);
3205 setenv_str (session->opt->es, "password", up->password);
3207 /* setenv incoming cert common name for script */
3208 setenv_str (session->opt->es, "common_name", session->common_name);
3210 /* setenv client real IP address */
3211 setenv_untrusted (session);
3213 #ifdef PLUGIN_DEF_AUTH
3214 /* generate filename for deferred auth control file */
3215 key_state_gen_auth_control_file (ks, session->opt);
3216 #endif
3218 /* call command */
3219 retval = plugin_call (session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY, NULL, NULL, session->opt->es);
3221 #ifdef PLUGIN_DEF_AUTH
3222 /* purge auth control filename (and file itself) for non-deferred returns */
3223 if (retval != OPENVPN_PLUGIN_FUNC_DEFERRED)
3224 key_state_rm_auth_control_file (ks);
3225 #endif
3227 setenv_del (session->opt->es, "password");
3228 setenv_str (session->opt->es, "username", up->username);
3230 else
3232 msg (D_TLS_ERRORS, "TLS Auth Error (verify_user_pass_plugin): peer provided a blank username");
3235 return retval;
3239 * MANAGEMENT_DEF_AUTH internal ssl.c status codes
3241 #define KMDA_ERROR 0
3242 #define KMDA_SUCCESS 1
3243 #define KMDA_UNDEF 2
3244 #define KMDA_DEF 3
3246 #ifdef MANAGEMENT_DEF_AUTH
3247 static int
3248 verify_user_pass_management (struct tls_session *session, const struct user_pass *up, const char *raw_username)
3250 int retval = KMDA_ERROR;
3252 /* Is username defined? */
3253 if ((session->opt->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL) || strlen (up->username))
3255 /* set username/password in private env space */
3256 setenv_str (session->opt->es, "username", raw_username);
3257 setenv_str (session->opt->es, "password", up->password);
3259 /* setenv incoming cert common name for script */
3260 setenv_str (session->opt->es, "common_name", session->common_name);
3262 /* setenv client real IP address */
3263 setenv_untrusted (session);
3265 if (management)
3266 management_notify_client_needing_auth (management, ks->mda_key_id, session->opt->mda_context, session->opt->es);
3268 setenv_del (session->opt->es, "password");
3269 setenv_str (session->opt->es, "username", up->username);
3271 retval = KMDA_SUCCESS;
3273 else
3275 msg (D_TLS_ERRORS, "TLS Auth Error (verify_user_pass_management): peer provided a blank username");
3278 return retval;
3280 #endif
3283 * Handle the reading and writing of key data to and from
3284 * the TLS control channel (cleartext).
3287 static bool
3288 key_method_1_write (struct buffer *buf, struct tls_session *session)
3290 struct key key;
3292 ASSERT (session->opt->key_method == 1);
3293 ASSERT (buf_init (buf, 0));
3295 generate_key_random (&key, &session->opt->key_type);
3296 if (!check_key (&key, &session->opt->key_type))
3298 msg (D_TLS_ERRORS, "TLS Error: Bad encrypting key generated");
3299 return false;
3302 if (!write_key (&key, &session->opt->key_type, buf))
3304 msg (D_TLS_ERRORS, "TLS Error: write_key failed");
3305 return false;
3308 init_key_ctx (&ks->key.encrypt, &key, &session->opt->key_type,
3309 DO_ENCRYPT, "Data Channel Encrypt");
3310 CLEAR (key);
3312 /* send local options string */
3314 const char *local_options = local_options_string (session);
3315 const int optlen = strlen (local_options) + 1;
3316 if (!buf_write (buf, local_options, optlen))
3318 msg (D_TLS_ERRORS, "TLS Error: KM1 write options failed");
3319 return false;
3323 return true;
3326 static bool
3327 key_method_2_write (struct buffer *buf, struct tls_session *session)
3329 ASSERT (session->opt->key_method == 2);
3330 ASSERT (buf_init (buf, 0));
3332 /* write a uint32 0 */
3333 if (!buf_write_u32 (buf, 0))
3334 goto error;
3336 /* write key_method + flags */
3337 if (!buf_write_u8 (buf, (session->opt->key_method & KEY_METHOD_MASK)))
3338 goto error;
3340 /* write key source material */
3341 if (!key_source2_randomize_write (ks->key_src, buf, session->opt->server))
3342 goto error;
3344 /* write options string */
3346 if (!write_string (buf, local_options_string (session), TLS_OPTIONS_LEN))
3347 goto error;
3350 /* write username/password if specified */
3351 if (auth_user_pass_enabled)
3353 auth_user_pass_setup (NULL);
3354 if (!write_string (buf, auth_user_pass.username, -1))
3355 goto error;
3356 if (!write_string (buf, auth_user_pass.password, -1))
3357 goto error;
3358 purge_user_pass (&auth_user_pass, false);
3362 * generate tunnel keys if server
3364 if (session->opt->server)
3366 if (ks->authenticated)
3368 if (!generate_key_expansion (&ks->key,
3369 &session->opt->key_type,
3370 ks->key_src,
3371 &ks->session_id_remote,
3372 &session->session_id,
3373 true))
3375 msg (D_TLS_ERRORS, "TLS Error: server generate_key_expansion failed");
3376 goto error;
3380 CLEAR (*ks->key_src);
3383 return true;
3385 error:
3386 msg (D_TLS_ERRORS, "TLS Error: Key Method #2 write failed");
3387 CLEAR (*ks->key_src);
3388 return false;
3391 static bool
3392 key_method_1_read (struct buffer *buf, struct tls_session *session)
3394 int status;
3395 struct key key;
3397 ASSERT (session->opt->key_method == 1);
3399 if (!session->verified)
3401 msg (D_TLS_ERRORS,
3402 "TLS Error: Certificate verification failed (key-method 1)");
3403 goto error;
3406 status = read_key (&key, &session->opt->key_type, buf);
3407 if (status != 1)
3409 msg (D_TLS_ERRORS,
3410 "TLS Error: Error reading data channel key from plaintext buffer");
3411 goto error;
3414 if (!check_key (&key, &session->opt->key_type))
3416 msg (D_TLS_ERRORS, "TLS Error: Bad decrypting key received from peer");
3417 goto error;
3420 if (buf->len < 1)
3422 msg (D_TLS_ERRORS, "TLS Error: Missing options string");
3423 goto error;
3426 #ifdef ENABLE_OCC
3427 /* compare received remote options string
3428 with our locally computed options string */
3429 if (!session->opt->disable_occ &&
3430 !options_cmp_equal_safe ((char *) BPTR (buf), session->opt->remote_options, buf->len))
3432 options_warning_safe ((char *) BPTR (buf), session->opt->remote_options, buf->len);
3434 #endif
3436 buf_clear (buf);
3438 init_key_ctx (&ks->key.decrypt, &key, &session->opt->key_type,
3439 DO_DECRYPT, "Data Channel Decrypt");
3440 CLEAR (key);
3441 ks->authenticated = true;
3442 return true;
3444 error:
3445 buf_clear (buf);
3446 CLEAR (key);
3447 return false;
3450 static bool
3451 key_method_2_read (struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
3453 struct gc_arena gc = gc_new ();
3454 int key_method_flags;
3455 char *options;
3456 struct user_pass *up;
3458 bool man_def_auth = KMDA_UNDEF;
3460 #ifdef MANAGEMENT_DEF_AUTH
3461 if (management_enable_def_auth (management))
3462 man_def_auth = KMDA_DEF;
3463 #endif
3465 ASSERT (session->opt->key_method == 2);
3467 /* allocate temporary objects */
3468 ALLOC_ARRAY_CLEAR_GC (options, char, TLS_OPTIONS_LEN, &gc);
3470 /* discard leading uint32 */
3471 ASSERT (buf_advance (buf, 4));
3473 /* get key method */
3474 key_method_flags = buf_read_u8 (buf);
3475 if ((key_method_flags & KEY_METHOD_MASK) != 2)
3477 msg (D_TLS_ERRORS,
3478 "TLS ERROR: Unknown key_method/flags=%d received from remote host",
3479 key_method_flags);
3480 goto error;
3483 /* get key source material (not actual keys yet) */
3484 if (!key_source2_read (ks->key_src, buf, session->opt->server))
3486 msg (D_TLS_ERRORS, "TLS Error: Error reading remote data channel key source entropy from plaintext buffer");
3487 goto error;
3490 /* get options */
3491 if (!read_string (buf, options, TLS_OPTIONS_LEN))
3493 msg (D_TLS_ERRORS, "TLS Error: Failed to read required OCC options string");
3494 goto error;
3497 /* should we check username/password? */
3498 ks->authenticated = false;
3499 if (session->opt->auth_user_pass_verify_script
3500 || plugin_defined (session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY)
3501 || man_def_auth == KMDA_DEF)
3503 int s1 = OPENVPN_PLUGIN_FUNC_SUCCESS;
3504 bool s2 = true;
3505 char *raw_username;
3507 /* get username/password from plaintext buffer */
3508 ALLOC_OBJ_CLEAR_GC (up, struct user_pass, &gc);
3509 if (!read_string (buf, up->username, USER_PASS_LEN)
3510 || !read_string (buf, up->password, USER_PASS_LEN))
3512 CLEAR (*up);
3513 if (!(session->opt->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL))
3515 msg (D_TLS_ERRORS, "TLS Error: Auth Username/Password was not provided by peer");
3516 goto error;
3520 /* preserve raw username before string_mod remapping, for plugins */
3521 ALLOC_ARRAY_CLEAR_GC (raw_username, char, USER_PASS_LEN, &gc);
3522 strcpy (raw_username, up->username);
3523 string_mod (raw_username, CC_PRINT, CC_CRLF, '_');
3525 /* enforce character class restrictions in username/password */
3526 string_mod_sslname (up->username, COMMON_NAME_CHAR_CLASS, session->opt->ssl_flags);
3527 string_mod (up->password, CC_PRINT, CC_CRLF, '_');
3529 /* call plugin(s) and/or script */
3530 #ifdef MANAGEMENT_DEF_AUTH
3531 if (man_def_auth == KMDA_DEF)
3532 man_def_auth = verify_user_pass_management (session, up, raw_username);
3533 #endif
3534 if (plugin_defined (session->opt->plugins, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY))
3535 s1 = verify_user_pass_plugin (session, up, raw_username);
3536 if (session->opt->auth_user_pass_verify_script)
3537 s2 = verify_user_pass_script (session, up);
3539 /* check sizing of username if it will become our common name */
3540 if ((session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME) && strlen (up->username) >= TLS_CN_LEN)
3542 msg (D_TLS_ERRORS, "TLS Auth Error: --username-as-common name specified and username is longer than the maximum permitted Common Name length of %d characters", TLS_CN_LEN);
3543 s1 = OPENVPN_PLUGIN_FUNC_ERROR;
3546 /* auth succeeded? */
3547 if ((s1 == OPENVPN_PLUGIN_FUNC_SUCCESS
3548 #ifdef PLUGIN_DEF_AUTH
3549 || s1 == OPENVPN_PLUGIN_FUNC_DEFERRED
3550 #endif
3551 ) && s2 && man_def_auth != KMDA_ERROR
3552 && tls_lock_username (multi, up->username))
3554 ks->authenticated = true;
3555 #ifdef PLUGIN_DEF_AUTH
3556 if (s1 == OPENVPN_PLUGIN_FUNC_DEFERRED)
3557 ks->auth_deferred = true;
3558 #endif
3559 #ifdef MANAGEMENT_DEF_AUTH
3560 if (man_def_auth != KMDA_UNDEF)
3561 ks->auth_deferred = true;
3562 #endif
3563 if ((session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME))
3564 set_common_name (session, up->username);
3565 #ifdef ENABLE_DEF_AUTH
3566 msg (D_HANDSHAKE, "TLS: Username/Password authentication %s for username '%s' %s",
3567 ks->auth_deferred ? "deferred" : "succeeded",
3568 up->username,
3569 (session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME) ? "[CN SET]" : "");
3570 #else
3571 msg (D_HANDSHAKE, "TLS: Username/Password authentication %s for username '%s' %s",
3572 "succeeded",
3573 up->username,
3574 (session->opt->ssl_flags & SSLF_USERNAME_AS_COMMON_NAME) ? "[CN SET]" : "");
3575 #endif
3577 else
3579 msg (D_TLS_ERRORS, "TLS Auth Error: Auth Username/Password verification failed for peer");
3582 CLEAR (*up);
3584 else
3586 if (!session->verified)
3588 msg (D_TLS_ERRORS,
3589 "TLS Error: Certificate verification failed (key-method 2)");
3590 goto error;
3592 ks->authenticated = true;
3595 /* While it shouldn't really happen, don't allow the common name to be NULL */
3596 if (!session->common_name)
3597 set_common_name (session, "");
3599 /* Don't allow the CN to change once it's been locked */
3600 if (ks->authenticated && multi->locked_cn)
3602 const char *cn = session->common_name;
3603 if (cn && strcmp (cn, multi->locked_cn))
3605 msg (D_TLS_ERRORS, "TLS Auth Error: TLS object CN attempted to change from '%s' to '%s' -- tunnel disabled",
3606 multi->locked_cn,
3607 cn);
3609 /* change the common name back to its original value and disable the tunnel */
3610 set_common_name (session, multi->locked_cn);
3611 tls_deauthenticate (multi);
3615 /* Don't allow the cert hashes to change once they have been locked */
3616 if (ks->authenticated && multi->locked_cert_hash_set)
3618 const struct cert_hash_set *chs = session->cert_hash_set;
3619 if (chs && !cert_hash_compare (chs, multi->locked_cert_hash_set))
3621 msg (D_TLS_ERRORS, "TLS Auth Error: TLS object CN=%s client-provided SSL certs unexpectedly changed during mid-session reauth",
3622 session->common_name);
3624 /* disable the tunnel */
3625 tls_deauthenticate (multi);
3629 /* verify --client-config-dir based authentication */
3630 if (ks->authenticated && session->opt->client_config_dir_exclusive)
3632 const char *cn = session->common_name;
3633 const char *path = gen_path (session->opt->client_config_dir_exclusive, cn, &gc);
3634 if (!cn || !strcmp (cn, CCD_DEFAULT) || !test_file (path))
3636 ks->authenticated = false;
3637 msg (D_TLS_ERRORS, "TLS Auth Error: --client-config-dir authentication failed for common name '%s' file='%s'",
3638 session->common_name,
3639 path ? path : "UNDEF");
3643 #ifdef ENABLE_OCC
3644 /* check options consistency */
3645 if (!session->opt->disable_occ &&
3646 !options_cmp_equal (options, session->opt->remote_options))
3648 options_warning (options, session->opt->remote_options);
3649 if (session->opt->ssl_flags & SSLF_OPT_VERIFY)
3651 msg (D_TLS_ERRORS, "Option inconsistency warnings triggering disconnect due to --opt-verify");
3652 ks->authenticated = false;
3655 #endif
3657 buf_clear (buf);
3660 * Call OPENVPN_PLUGIN_TLS_FINAL plugin if defined, for final
3661 * veto opportunity over authentication decision.
3663 if (ks->authenticated && plugin_defined (session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL))
3665 if (plugin_call (session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL, NULL, NULL, session->opt->es) != OPENVPN_PLUGIN_FUNC_SUCCESS)
3666 ks->authenticated = false;
3670 * Generate tunnel keys if client
3672 if (!session->opt->server)
3674 if (!generate_key_expansion (&ks->key,
3675 &session->opt->key_type,
3676 ks->key_src,
3677 &session->session_id,
3678 &ks->session_id_remote,
3679 false))
3681 msg (D_TLS_ERRORS, "TLS Error: client generate_key_expansion failed");
3682 goto error;
3685 CLEAR (*ks->key_src);
3688 gc_free (&gc);
3689 return true;
3691 error:
3692 CLEAR (*ks->key_src);
3693 buf_clear (buf);
3694 gc_free (&gc);
3695 return false;
3698 static int
3699 auth_deferred_expire_window (const struct tls_options *o)
3701 const int hw = o->handshake_window;
3702 const int r2 = o->renegotiate_seconds / 2;
3703 return min_int (hw, r2);
3707 * This is the primary routine for processing TLS stuff inside the
3708 * the main event loop. When this routine exits
3709 * with non-error status, it will set *wakeup to the number of seconds
3710 * when it wants to be called again.
3712 * Return value is true if we have placed a packet in *to_link which we
3713 * want to send to our peer.
3715 static bool
3716 tls_process (struct tls_multi *multi,
3717 struct tls_session *session,
3718 struct buffer *to_link,
3719 struct link_socket_actual **to_link_addr,
3720 struct link_socket_info *to_link_socket_info,
3721 interval_t *wakeup)
3723 struct gc_arena gc = gc_new ();
3724 struct buffer *buf;
3725 bool state_change = false;
3726 bool active = false;
3728 /* Make sure we were initialized and that we're not in an error state */
3729 ASSERT (ks->state != S_UNDEF);
3730 ASSERT (ks->state != S_ERROR);
3731 ASSERT (session_id_defined (&session->session_id));
3733 /* Should we trigger a soft reset? -- new key, keeps old key for a while */
3734 if (ks->state >= S_ACTIVE &&
3735 ((session->opt->renegotiate_seconds
3736 && now >= ks->established + session->opt->renegotiate_seconds)
3737 || (session->opt->renegotiate_bytes
3738 && ks->n_bytes >= session->opt->renegotiate_bytes)
3739 || (session->opt->renegotiate_packets
3740 && ks->n_packets >= session->opt->renegotiate_packets)
3741 || (packet_id_close_to_wrapping (&ks->packet_id.send))))
3743 msg (D_TLS_DEBUG_LOW, "TLS: soft reset sec=%d bytes=%d/%d pkts=%d/%d",
3744 (int)(ks->established + session->opt->renegotiate_seconds - now),
3745 ks->n_bytes, session->opt->renegotiate_bytes,
3746 ks->n_packets, session->opt->renegotiate_packets);
3747 key_state_soft_reset (session);
3750 /* Kill lame duck key transition_window seconds after primary key negotiation */
3751 if (lame_duck_must_die (session, wakeup)) {
3752 key_state_free (ks_lame, true);
3753 msg (D_TLS_DEBUG_LOW, "TLS: tls_process: killed expiring key");
3756 /*mutex_cycle (multi->mutex);*/
3760 update_time ();
3762 dmsg (D_TLS_DEBUG, "TLS: tls_process: chg=%d ks=%s lame=%s to_link->len=%d wakeup=%d",
3763 state_change,
3764 state_name (ks->state),
3765 state_name (ks_lame->state),
3766 to_link->len,
3767 *wakeup);
3769 state_change = false;
3772 * TLS activity is finished once we get to S_ACTIVE,
3773 * though we will still process acknowledgements.
3775 * CHANGED with 2.0 -> now we may send tunnel configuration
3776 * info over the control channel.
3778 if (true)
3780 /* Initial handshake */
3781 if (ks->state == S_INITIAL)
3783 buf = reliable_get_buf_output_sequenced (ks->send_reliable);
3784 if (buf)
3786 ks->must_negotiate = now + session->opt->handshake_window;
3787 ks->auth_deferred_expire = now + auth_deferred_expire_window (session->opt);
3789 /* null buffer */
3790 reliable_mark_active_outgoing (ks->send_reliable, buf, ks->initial_opcode);
3791 INCR_GENERATED;
3793 ks->state = S_PRE_START;
3794 state_change = true;
3795 dmsg (D_TLS_DEBUG, "TLS: Initial Handshake, sid=%s",
3796 session_id_print (&session->session_id, &gc));
3798 #ifdef ENABLE_MANAGEMENT
3799 if (management && ks->initial_opcode != P_CONTROL_SOFT_RESET_V1)
3801 management_set_state (management,
3802 OPENVPN_STATE_WAIT,
3803 NULL,
3807 #endif
3811 /* Are we timed out on receive? */
3812 if (now >= ks->must_negotiate)
3814 if (ks->state < S_ACTIVE)
3816 msg (D_TLS_ERRORS,
3817 "TLS Error: TLS key negotiation failed to occur within %d seconds (check your network connectivity)",
3818 session->opt->handshake_window);
3819 goto error;
3821 else /* assume that ks->state == S_ACTIVE */
3823 dmsg (D_TLS_DEBUG_MED, "STATE S_NORMAL_OP");
3824 ks->state = S_NORMAL_OP;
3825 ks->must_negotiate = 0;
3829 /* Wait for Initial Handshake ACK */
3830 if (ks->state == S_PRE_START && FULL_SYNC)
3832 ks->state = S_START;
3833 state_change = true;
3834 dmsg (D_TLS_DEBUG_MED, "STATE S_START");
3837 /* Wait for ACK */
3838 if (((ks->state == S_GOT_KEY && !session->opt->server) ||
3839 (ks->state == S_SENT_KEY && session->opt->server)))
3841 if (FULL_SYNC)
3843 ks->established = now;
3844 dmsg (D_TLS_DEBUG_MED, "STATE S_ACTIVE");
3845 if (check_debug_level (D_HANDSHAKE))
3846 print_details (ks->ssl, "Control Channel:");
3847 state_change = true;
3848 ks->state = S_ACTIVE;
3849 INCR_SUCCESS;
3851 /* Set outgoing address for data channel packets */
3852 link_socket_set_outgoing_addr (NULL, to_link_socket_info, &ks->remote_addr, session->common_name, session->opt->es);
3854 #ifdef MEASURE_TLS_HANDSHAKE_STATS
3855 show_tls_performance_stats();
3856 #endif
3860 /* Reliable buffer to outgoing TCP/UDP (send up to CONTROL_SEND_ACK_MAX ACKs
3861 for previously received packets) */
3862 if (!to_link->len && reliable_can_send (ks->send_reliable))
3864 int opcode;
3865 struct buffer b;
3867 buf = reliable_send (ks->send_reliable, &opcode);
3868 ASSERT (buf);
3869 b = *buf;
3870 INCR_SENT;
3872 write_control_auth (session, ks, &b, to_link_addr, opcode,
3873 CONTROL_SEND_ACK_MAX, true);
3874 *to_link = b;
3875 active = true;
3876 state_change = true;
3877 dmsg (D_TLS_DEBUG, "Reliable -> TCP/UDP");
3878 break;
3881 #ifndef TLS_AGGREGATE_ACK
3882 /* Send 1 or more ACKs (each received control packet gets one ACK) */
3883 if (!to_link->len && !reliable_ack_empty (ks->rec_ack))
3885 buf = &ks->ack_write_buf;
3886 ASSERT (buf_init (buf, FRAME_HEADROOM (&multi->opt.frame)));
3887 write_control_auth (session, ks, buf, to_link_addr, P_ACK_V1,
3888 RELIABLE_ACK_SIZE, false);
3889 *to_link = *buf;
3890 active = true;
3891 state_change = true;
3892 dmsg (D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP");
3893 break;
3895 #endif
3897 /* Write incoming ciphertext to TLS object */
3898 buf = reliable_get_buf_sequenced (ks->rec_reliable);
3899 if (buf)
3901 int status = 0;
3902 if (buf->len)
3904 status = key_state_write_ciphertext (multi, ks, buf);
3905 if (status == -1)
3907 msg (D_TLS_ERRORS,
3908 "TLS Error: Incoming Ciphertext -> TLS object write error");
3909 goto error;
3912 else
3914 status = 1;
3916 if (status == 1)
3918 reliable_mark_deleted (ks->rec_reliable, buf, true);
3919 state_change = true;
3920 dmsg (D_TLS_DEBUG, "Incoming Ciphertext -> TLS");
3924 /* Read incoming plaintext from TLS object */
3925 buf = &ks->plaintext_read_buf;
3926 if (!buf->len)
3928 int status;
3930 ASSERT (buf_init (buf, 0));
3931 status = key_state_read_plaintext (multi, ks, buf, TLS_CHANNEL_BUF_SIZE);
3932 update_time ();
3933 if (status == -1)
3935 msg (D_TLS_ERRORS, "TLS Error: TLS object -> incoming plaintext read error");
3936 goto error;
3938 if (status == 1)
3940 state_change = true;
3941 dmsg (D_TLS_DEBUG, "TLS -> Incoming Plaintext");
3943 #if 0 /* show null plaintext reads */
3944 if (!status)
3945 msg (M_INFO, "TLS plaintext read -> NULL return");
3946 #endif
3949 /* Send Key */
3950 buf = &ks->plaintext_write_buf;
3951 if (!buf->len && ((ks->state == S_START && !session->opt->server) ||
3952 (ks->state == S_GOT_KEY && session->opt->server)))
3954 if (session->opt->key_method == 1)
3956 if (!key_method_1_write (buf, session))
3957 goto error;
3959 else if (session->opt->key_method == 2)
3961 if (!key_method_2_write (buf, session))
3962 goto error;
3964 else
3966 ASSERT (0);
3969 state_change = true;
3970 dmsg (D_TLS_DEBUG_MED, "STATE S_SENT_KEY");
3971 ks->state = S_SENT_KEY;
3974 /* Receive Key */
3975 buf = &ks->plaintext_read_buf;
3976 if (buf->len
3977 && ((ks->state == S_SENT_KEY && !session->opt->server)
3978 || (ks->state == S_START && session->opt->server)))
3980 if (session->opt->key_method == 1)
3982 if (!key_method_1_read (buf, session))
3983 goto error;
3985 else if (session->opt->key_method == 2)
3987 if (!key_method_2_read (buf, multi, session))
3988 goto error;
3990 else
3992 ASSERT (0);
3995 state_change = true;
3996 dmsg (D_TLS_DEBUG_MED, "STATE S_GOT_KEY");
3997 ks->state = S_GOT_KEY;
4000 /* Write outgoing plaintext to TLS object */
4001 buf = &ks->plaintext_write_buf;
4002 if (buf->len)
4004 int status = key_state_write_plaintext (multi, ks, buf);
4005 if (status == -1)
4007 msg (D_TLS_ERRORS,
4008 "TLS ERROR: Outgoing Plaintext -> TLS object write error");
4009 goto error;
4011 if (status == 1)
4013 state_change = true;
4014 dmsg (D_TLS_DEBUG, "Outgoing Plaintext -> TLS");
4018 /* Outgoing Ciphertext to reliable buffer */
4019 if (ks->state >= S_START)
4021 buf = reliable_get_buf_output_sequenced (ks->send_reliable);
4022 if (buf)
4024 int status = key_state_read_ciphertext (multi, ks, buf, PAYLOAD_SIZE_DYNAMIC (&multi->opt.frame));
4025 if (status == -1)
4027 msg (D_TLS_ERRORS,
4028 "TLS Error: Ciphertext -> reliable TCP/UDP transport read error");
4029 goto error;
4031 if (status == 1)
4033 reliable_mark_active_outgoing (ks->send_reliable, buf, P_CONTROL_V1);
4034 INCR_GENERATED;
4035 state_change = true;
4036 dmsg (D_TLS_DEBUG, "Outgoing Ciphertext -> Reliable");
4041 /*mutex_cycle (multi->mutex);*/
4043 while (state_change);
4045 update_time ();
4047 #ifdef TLS_AGGREGATE_ACK
4048 /* Send 1 or more ACKs (each received control packet gets one ACK) */
4049 if (!to_link->len && !reliable_ack_empty (ks->rec_ack))
4051 buf = &ks->ack_write_buf;
4052 ASSERT (buf_init (buf, FRAME_HEADROOM (&multi->opt.frame)));
4053 write_control_auth (session, ks, buf, to_link_addr, P_ACK_V1,
4054 RELIABLE_ACK_SIZE, false);
4055 *to_link = *buf;
4056 active = true;
4057 state_change = true;
4058 dmsg (D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP");
4060 #endif
4062 /* When should we wake up again? */
4064 if (ks->state >= S_INITIAL)
4066 compute_earliest_wakeup (wakeup,
4067 reliable_send_timeout (ks->send_reliable));
4069 if (ks->must_negotiate)
4070 compute_earliest_wakeup (wakeup, ks->must_negotiate - now);
4073 if (ks->established && session->opt->renegotiate_seconds)
4074 compute_earliest_wakeup (wakeup,
4075 ks->established + session->opt->renegotiate_seconds - now);
4077 /* prevent event-loop spinning by setting minimum wakeup of 1 second */
4078 if (*wakeup <= 0)
4080 *wakeup = 1;
4082 /* if we had something to send to remote, but to_link was busy,
4083 let caller know we need to be called again soon */
4084 active = true;
4087 dmsg (D_TLS_DEBUG, "TLS: tls_process: timeout set to %d", *wakeup);
4089 gc_free (&gc);
4090 return active;
4093 error:
4094 ERR_clear_error ();
4095 ks->state = S_ERROR;
4096 msg (D_TLS_ERRORS, "TLS Error: TLS handshake failed");
4097 INCR_ERROR;
4098 gc_free (&gc);
4099 return false;
4102 #undef ks
4103 #undef ks_lame
4106 * Called by the top-level event loop.
4108 * Basically decides if we should call tls_process for
4109 * the active or untrusted sessions.
4113 tls_multi_process (struct tls_multi *multi,
4114 struct buffer *to_link,
4115 struct link_socket_actual **to_link_addr,
4116 struct link_socket_info *to_link_socket_info,
4117 interval_t *wakeup)
4119 struct gc_arena gc = gc_new ();
4120 int i;
4121 int active = TLSMP_INACTIVE;
4122 bool error = false;
4123 int tas;
4125 perf_push (PERF_TLS_MULTI_PROCESS);
4127 ERR_clear_error ();
4130 * Process each session object having state of S_INITIAL or greater,
4131 * and which has a defined remote IP addr.
4134 for (i = 0; i < TM_SIZE; ++i)
4136 struct tls_session *session = &multi->session[i];
4137 struct key_state *ks = &session->key[KS_PRIMARY];
4138 struct key_state *ks_lame = &session->key[KS_LAME_DUCK];
4140 /* set initial remote address */
4141 if (i == TM_ACTIVE && ks->state == S_INITIAL &&
4142 link_socket_actual_defined (&to_link_socket_info->lsa->actual))
4143 ks->remote_addr = to_link_socket_info->lsa->actual;
4145 dmsg (D_TLS_DEBUG,
4146 "TLS: tls_multi_process: i=%d state=%s, mysid=%s, stored-sid=%s, stored-ip=%s",
4148 state_name (ks->state),
4149 session_id_print (&session->session_id, &gc),
4150 session_id_print (&ks->session_id_remote, &gc),
4151 print_link_socket_actual (&ks->remote_addr, &gc));
4153 if (ks->state >= S_INITIAL && link_socket_actual_defined (&ks->remote_addr))
4155 struct link_socket_actual *tla = NULL;
4157 update_time ();
4159 if (tls_process (multi, session, to_link, &tla,
4160 to_link_socket_info, wakeup))
4161 active = TLSMP_ACTIVE;
4164 * If tls_process produced an outgoing packet,
4165 * return the link_socket_actual object (which
4166 * contains the outgoing address).
4168 if (tla)
4170 multi->to_link_addr = *tla;
4171 *to_link_addr = &multi->to_link_addr;
4175 * If tls_process hits an error:
4176 * (1) If the session has an unexpired lame duck key, preserve it.
4177 * (2) Reinitialize the session.
4178 * (3) Increment soft error count
4180 if (ks->state == S_ERROR)
4182 ++multi->n_soft_errors;
4184 if (i == TM_ACTIVE)
4185 error = true;
4187 if (i == TM_ACTIVE
4188 && ks_lame->state >= S_ACTIVE
4189 && !multi->opt.single_session)
4190 move_session (multi, TM_LAME_DUCK, TM_ACTIVE, true);
4191 else
4192 reset_session (multi, session);
4195 /*mutex_cycle (multi->mutex);*/
4198 update_time ();
4200 tas = tls_authentication_status (multi, TLS_MULTI_AUTH_STATUS_INTERVAL);
4203 * If lame duck session expires, kill it.
4205 if (lame_duck_must_die (&multi->session[TM_LAME_DUCK], wakeup)) {
4206 tls_session_free (&multi->session[TM_LAME_DUCK], true);
4207 msg (D_TLS_DEBUG_LOW, "TLS: tls_multi_process: killed expiring key");
4211 * If untrusted session achieves TLS authentication,
4212 * move it to active session, usurping any prior session.
4214 * A semi-trusted session is one in which the certificate authentication
4215 * succeeded (if cert verification is enabled) but the username/password
4216 * verification failed. A semi-trusted session can forward data on the
4217 * TLS control channel but not on the tunnel channel.
4219 if (DECRYPT_KEY_ENABLED (multi, &multi->session[TM_UNTRUSTED].key[KS_PRIMARY])) {
4220 move_session (multi, TM_ACTIVE, TM_UNTRUSTED, true);
4221 msg (D_TLS_DEBUG_LOW, "TLS: tls_multi_process: untrusted session promoted to %strusted",
4222 tas == TLS_AUTHENTICATION_SUCCEEDED ? "" : "semi-");
4226 * A hard error means that TM_ACTIVE hit an S_ERROR state and that no
4227 * other key state objects are S_ACTIVE or higher.
4229 if (error)
4231 for (i = 0; i < (int) SIZE (multi->key_scan); ++i)
4233 if (multi->key_scan[i]->state >= S_ACTIVE)
4234 goto nohard;
4236 ++multi->n_hard_errors;
4238 nohard:
4240 #ifdef ENABLE_DEBUG
4241 /* DEBUGGING -- flood peer with repeating connection attempts */
4243 const int throw_level = GREMLIN_CONNECTION_FLOOD_LEVEL (multi->opt.gremlin);
4244 if (throw_level)
4246 for (i = 0; i < (int) SIZE (multi->key_scan); ++i)
4248 if (multi->key_scan[i]->state >= throw_level)
4250 ++multi->n_hard_errors;
4251 ++multi->n_soft_errors;
4256 #endif
4258 perf_pop ();
4259 gc_free (&gc);
4261 return (tas == TLS_AUTHENTICATION_FAILED) ? TLSMP_KILL : active;
4265 * Pre and post-process the encryption & decryption buffers in order
4266 * to implement a multiplexed TLS channel over the TCP/UDP port.
4271 * When we are in TLS mode, this is the first routine which sees
4272 * an incoming packet.
4274 * If it's a data packet, we set opt so that our caller can
4275 * decrypt it. We also give our caller the appropriate decryption key.
4277 * If it's a control packet, we authenticate it and process it,
4278 * possibly creating a new tls_session if it represents the
4279 * first packet of a new session. For control packets, we will
4280 * also zero the size of *buf so that our caller ignores the
4281 * packet on our return.
4283 * Note that openvpn only allows one active session at a time,
4284 * so a new session (once authenticated) will always usurp
4285 * an old session.
4287 * Return true if input was an authenticated control channel
4288 * packet.
4290 * If we are running in TLS thread mode, all public routines
4291 * below this point must be called with the L_TLS lock held.
4294 bool
4295 tls_pre_decrypt (struct tls_multi *multi,
4296 const struct link_socket_actual *from,
4297 struct buffer *buf,
4298 struct crypto_options *opt)
4300 struct gc_arena gc = gc_new ();
4301 bool ret = false;
4303 if (buf->len > 0)
4305 int i;
4306 int op;
4307 int key_id;
4309 /* get opcode and key ID */
4311 uint8_t c = *BPTR (buf);
4312 op = c >> P_OPCODE_SHIFT;
4313 key_id = c & P_KEY_ID_MASK;
4316 if (op == P_DATA_V1)
4317 { /* data channel packet */
4318 for (i = 0; i < KEY_SCAN_SIZE; ++i)
4320 struct key_state *ks = multi->key_scan[i];
4323 * This is the basic test of TLS state compatibility between a local OpenVPN
4324 * instance and its remote peer.
4326 * If the test fails, it tells us that we are getting a packet from a source
4327 * which claims reference to a prior negotiated TLS session, but the local
4328 * OpenVPN instance has no memory of such a negotiation.
4330 * It almost always occurs on UDP sessions when the passive side of the
4331 * connection is restarted without the active side restarting as well (the
4332 * passive side is the server which only listens for the connections, the
4333 * active side is the client which initiates connections).
4335 if (DECRYPT_KEY_ENABLED (multi, ks)
4336 && key_id == ks->key_id
4337 && ks->authenticated
4338 #ifdef ENABLE_DEF_AUTH
4339 && !ks->auth_deferred
4340 #endif
4341 && link_socket_actual_match (from, &ks->remote_addr))
4343 /* return appropriate data channel decrypt key in opt */
4344 opt->key_ctx_bi = &ks->key;
4345 opt->packet_id = multi->opt.replay ? &ks->packet_id : NULL;
4346 opt->pid_persist = NULL;
4347 opt->flags &= multi->opt.crypto_flags_and;
4348 opt->flags |= multi->opt.crypto_flags_or;
4349 ASSERT (buf_advance (buf, 1));
4350 ++ks->n_packets;
4351 ks->n_bytes += buf->len;
4352 dmsg (D_TLS_KEYSELECT,
4353 "TLS: tls_pre_decrypt, key_id=%d, IP=%s",
4354 key_id, print_link_socket_actual (from, &gc));
4355 gc_free (&gc);
4356 return ret;
4358 #if 0 /* keys out of sync? */
4359 else
4361 dmsg (D_TLS_ERRORS, "TLS_PRE_DECRYPT: [%d] dken=%d rkid=%d lkid=%d auth=%d def=%d match=%d",
4363 DECRYPT_KEY_ENABLED (multi, ks),
4364 key_id,
4365 ks->key_id,
4366 ks->authenticated,
4367 #ifdef ENABLE_DEF_AUTH
4368 ks->auth_deferred,
4369 #else
4371 #endif
4372 link_socket_actual_match (from, &ks->remote_addr));
4374 #endif
4377 msg (D_TLS_ERRORS,
4378 "TLS Error: local/remote TLS keys are out of sync: %s [%d]",
4379 print_link_socket_actual (from, &gc), key_id);
4380 goto error_lite;
4382 else /* control channel packet */
4384 bool do_burst = false;
4385 bool new_link = false;
4386 struct session_id sid; /* remote session ID */
4388 /* verify legal opcode */
4389 if (op < P_FIRST_OPCODE || op > P_LAST_OPCODE)
4391 msg (D_TLS_ERRORS,
4392 "TLS Error: unknown opcode received from %s op=%d",
4393 print_link_socket_actual (from, &gc), op);
4394 goto error;
4397 /* hard reset ? */
4398 if (is_hard_reset (op, 0))
4400 /* verify client -> server or server -> client connection */
4401 if (((op == P_CONTROL_HARD_RESET_CLIENT_V1
4402 || op == P_CONTROL_HARD_RESET_CLIENT_V2) && !multi->opt.server)
4403 || ((op == P_CONTROL_HARD_RESET_SERVER_V1
4404 || op == P_CONTROL_HARD_RESET_SERVER_V2) && multi->opt.server))
4406 msg (D_TLS_ERRORS,
4407 "TLS Error: client->client or server->server connection attempted from %s",
4408 print_link_socket_actual (from, &gc));
4409 goto error;
4414 * Authenticate Packet
4416 dmsg (D_TLS_DEBUG, "TLS: control channel, op=%s, IP=%s",
4417 packet_opcode_name (op), print_link_socket_actual (from, &gc));
4419 /* get remote session-id */
4421 struct buffer tmp = *buf;
4422 buf_advance (&tmp, 1);
4423 if (!session_id_read (&sid, &tmp) || !session_id_defined (&sid))
4425 msg (D_TLS_ERRORS,
4426 "TLS Error: session-id not found in packet from %s",
4427 print_link_socket_actual (from, &gc));
4428 goto error;
4432 /* use session ID to match up packet with appropriate tls_session object */
4433 for (i = 0; i < TM_SIZE; ++i)
4435 struct tls_session *session = &multi->session[i];
4436 struct key_state *ks = &session->key[KS_PRIMARY];
4438 dmsg (D_TLS_DEBUG,
4439 "TLS: initial packet test, i=%d state=%s, mysid=%s, rec-sid=%s, rec-ip=%s, stored-sid=%s, stored-ip=%s",
4441 state_name (ks->state),
4442 session_id_print (&session->session_id, &gc),
4443 session_id_print (&sid, &gc),
4444 print_link_socket_actual (from, &gc),
4445 session_id_print (&ks->session_id_remote, &gc),
4446 print_link_socket_actual (&ks->remote_addr, &gc));
4448 if (session_id_equal (&ks->session_id_remote, &sid))
4449 /* found a match */
4451 if (i == TM_LAME_DUCK) {
4452 msg (D_TLS_ERRORS,
4453 "TLS ERROR: received control packet with stale session-id=%s",
4454 session_id_print (&sid, &gc));
4455 goto error;
4457 dmsg (D_TLS_DEBUG,
4458 "TLS: found match, session[%d], sid=%s",
4459 i, session_id_print (&sid, &gc));
4460 break;
4465 * Initial packet received.
4468 if (i == TM_SIZE && is_hard_reset (op, 0))
4470 struct tls_session *session = &multi->session[TM_ACTIVE];
4471 struct key_state *ks = &session->key[KS_PRIMARY];
4473 if (!is_hard_reset (op, multi->opt.key_method))
4475 msg (D_TLS_ERRORS, "TLS ERROR: initial packet local/remote key_method mismatch, local key_method=%d, op=%s",
4476 multi->opt.key_method,
4477 packet_opcode_name (op));
4478 goto error;
4482 * If we have no session currently in progress, the initial packet will
4483 * open a new session in TM_ACTIVE rather than TM_UNTRUSTED.
4485 if (!session_id_defined (&ks->session_id_remote))
4487 if (multi->opt.single_session && multi->n_sessions)
4489 msg (D_TLS_ERRORS,
4490 "TLS Error: Cannot accept new session request from %s due to session context expire or --single-session [1]",
4491 print_link_socket_actual (from, &gc));
4492 goto error;
4495 #ifdef ENABLE_MANAGEMENT
4496 if (management)
4498 management_set_state (management,
4499 OPENVPN_STATE_AUTH,
4500 NULL,
4504 #endif
4506 msg (D_TLS_DEBUG_LOW,
4507 "TLS: Initial packet from %s, sid=%s",
4508 print_link_socket_actual (from, &gc),
4509 session_id_print (&sid, &gc));
4511 do_burst = true;
4512 new_link = true;
4513 i = TM_ACTIVE;
4514 session->untrusted_addr = *from;
4518 if (i == TM_SIZE && is_hard_reset (op, 0))
4521 * No match with existing sessions,
4522 * probably a new session.
4524 struct tls_session *session = &multi->session[TM_UNTRUSTED];
4527 * If --single-session, don't allow any hard-reset connection request
4528 * unless it the the first packet of the session.
4530 if (multi->opt.single_session)
4532 msg (D_TLS_ERRORS,
4533 "TLS Error: Cannot accept new session request from %s due to session context expire or --single-session [2]",
4534 print_link_socket_actual (from, &gc));
4535 goto error;
4538 if (!is_hard_reset (op, multi->opt.key_method))
4540 msg (D_TLS_ERRORS, "TLS ERROR: new session local/remote key_method mismatch, local key_method=%d, op=%s",
4541 multi->opt.key_method,
4542 packet_opcode_name (op));
4543 goto error;
4546 if (!read_control_auth (buf, &session->tls_auth, from))
4547 goto error;
4550 * New session-initiating control packet is authenticated at this point,
4551 * assuming that the --tls-auth command line option was used.
4553 * Without --tls-auth, we leave authentication entirely up to TLS.
4555 msg (D_TLS_DEBUG_LOW,
4556 "TLS: new session incoming connection from %s",
4557 print_link_socket_actual (from, &gc));
4559 new_link = true;
4560 i = TM_UNTRUSTED;
4561 session->untrusted_addr = *from;
4563 else
4565 struct tls_session *session = &multi->session[i];
4566 struct key_state *ks = &session->key[KS_PRIMARY];
4569 * Packet must belong to an existing session.
4571 if (i != TM_ACTIVE && i != TM_UNTRUSTED)
4573 msg (D_TLS_ERRORS,
4574 "TLS Error: Unroutable control packet received from %s (si=%d op=%s)",
4575 print_link_socket_actual (from, &gc),
4577 packet_opcode_name (op));
4578 goto error;
4582 * Verify remote IP address
4584 if (!new_link && !link_socket_actual_match (&ks->remote_addr, from))
4586 msg (D_TLS_ERRORS, "TLS Error: Received control packet from unexpected IP addr: %s",
4587 print_link_socket_actual (from, &gc));
4588 goto error;
4592 * Remote is requesting a key renegotiation
4594 if (op == P_CONTROL_SOFT_RESET_V1
4595 && DECRYPT_KEY_ENABLED (multi, ks))
4597 if (!read_control_auth (buf, &session->tls_auth, from))
4598 goto error;
4600 key_state_soft_reset (session);
4602 dmsg (D_TLS_DEBUG,
4603 "TLS: received P_CONTROL_SOFT_RESET_V1 s=%d sid=%s",
4604 i, session_id_print (&sid, &gc));
4606 else
4609 * Remote responding to our key renegotiation request?
4611 if (op == P_CONTROL_SOFT_RESET_V1)
4612 do_burst = true;
4614 if (!read_control_auth (buf, &session->tls_auth, from))
4615 goto error;
4617 dmsg (D_TLS_DEBUG,
4618 "TLS: received control channel packet s#=%d sid=%s",
4619 i, session_id_print (&sid, &gc));
4624 * We have an authenticated packet (if --tls-auth was set).
4625 * Now pass to our reliability level which deals with
4626 * packet acknowledgements, retransmits, sequencing, etc.
4629 struct tls_session *session = &multi->session[i];
4630 struct key_state *ks = &session->key[KS_PRIMARY];
4632 /* Make sure we were initialized and that we're not in an error state */
4633 ASSERT (ks->state != S_UNDEF);
4634 ASSERT (ks->state != S_ERROR);
4635 ASSERT (session_id_defined (&session->session_id));
4637 /* Let our caller know we processed a control channel packet */
4638 ret = true;
4641 * Set our remote address and remote session_id
4643 if (new_link)
4645 ks->session_id_remote = sid;
4646 ks->remote_addr = *from;
4647 ++multi->n_sessions;
4649 else if (!link_socket_actual_match (&ks->remote_addr, from))
4651 msg (D_TLS_ERRORS,
4652 "TLS Error: Existing session control channel packet from unknown IP address: %s",
4653 print_link_socket_actual (from, &gc));
4654 goto error;
4658 * Should we do a retransmit of all unacknowledged packets in
4659 * the send buffer? This improves the start-up efficiency of the
4660 * initial key negotiation after the 2nd peer comes online.
4662 if (do_burst && !session->burst)
4664 reliable_schedule_now (ks->send_reliable);
4665 session->burst = true;
4668 /* Check key_id */
4669 if (ks->key_id != key_id)
4671 msg (D_TLS_ERRORS,
4672 "TLS ERROR: local/remote key IDs out of sync (%d/%d) ID: %s",
4673 ks->key_id, key_id, print_key_id (multi, &gc));
4674 goto error;
4678 * Process incoming ACKs for packets we can now
4679 * delete from reliable send buffer
4682 /* buffers all packet IDs to delete from send_reliable */
4683 struct reliable_ack send_ack;
4685 send_ack.len = 0;
4686 if (!reliable_ack_read (&send_ack, buf, &session->session_id))
4688 msg (D_TLS_ERRORS,
4689 "TLS Error: reading acknowledgement record from packet");
4690 goto error;
4692 reliable_send_purge (ks->send_reliable, &send_ack);
4695 if (op != P_ACK_V1 && reliable_can_get (ks->rec_reliable))
4697 packet_id_type id;
4699 /* Extract the packet ID from the packet */
4700 if (reliable_ack_read_packet_id (buf, &id))
4702 /* Avoid deadlock by rejecting packet that would de-sequentialize receive buffer */
4703 if (reliable_wont_break_sequentiality (ks->rec_reliable, id))
4705 if (reliable_not_replay (ks->rec_reliable, id))
4707 /* Save incoming ciphertext packet to reliable buffer */
4708 struct buffer *in = reliable_get_buf (ks->rec_reliable);
4709 ASSERT (in);
4710 ASSERT (buf_copy (in, buf));
4711 reliable_mark_active_incoming (ks->rec_reliable, in, id, op);
4714 /* Process outgoing acknowledgment for packet just received, even if it's a replay */
4715 reliable_ack_acknowledge_packet_id (ks->rec_ack, id);
4723 done:
4724 buf->len = 0;
4725 opt->key_ctx_bi = NULL;
4726 opt->packet_id = NULL;
4727 opt->pid_persist = NULL;
4728 opt->flags &= multi->opt.crypto_flags_and;
4729 gc_free (&gc);
4730 return ret;
4732 error:
4733 ++multi->n_soft_errors;
4734 error_lite:
4735 ERR_clear_error ();
4736 goto done;
4740 * This function is similar to tls_pre_decrypt, except it is called
4741 * when we are in server mode and receive an initial incoming
4742 * packet. Note that we don't modify
4743 * any state in our parameter objects. The purpose is solely to
4744 * determine whether we should generate a client instance
4745 * object, in which case true is returned.
4747 * This function is essentially the first-line HMAC firewall
4748 * on the UDP port listener in --mode server mode.
4750 bool
4751 tls_pre_decrypt_lite (const struct tls_auth_standalone *tas,
4752 const struct link_socket_actual *from,
4753 const struct buffer *buf)
4756 struct gc_arena gc = gc_new ();
4757 bool ret = false;
4759 if (buf->len > 0)
4761 int op;
4762 int key_id;
4764 /* get opcode and key ID */
4766 uint8_t c = *BPTR (buf);
4767 op = c >> P_OPCODE_SHIFT;
4768 key_id = c & P_KEY_ID_MASK;
4771 /* this packet is from an as-yet untrusted source, so
4772 scrutinize carefully */
4774 if (op != P_CONTROL_HARD_RESET_CLIENT_V2)
4777 * This can occur due to bogus data or DoS packets.
4779 dmsg (D_TLS_STATE_ERRORS,
4780 "TLS State Error: No TLS state for client %s, opcode=%d",
4781 print_link_socket_actual (from, &gc),
4782 op);
4783 goto error;
4786 if (key_id != 0)
4788 dmsg (D_TLS_STATE_ERRORS,
4789 "TLS State Error: Unknown key ID (%d) received from %s -- 0 was expected",
4790 key_id,
4791 print_link_socket_actual (from, &gc));
4792 goto error;
4795 if (buf->len > EXPANDED_SIZE_DYNAMIC (&tas->frame))
4797 dmsg (D_TLS_STATE_ERRORS,
4798 "TLS State Error: Large packet (size %d) received from %s -- a packet no larger than %d bytes was expected",
4799 buf->len,
4800 print_link_socket_actual (from, &gc),
4801 EXPANDED_SIZE_DYNAMIC (&tas->frame));
4802 goto error;
4806 struct buffer newbuf = clone_buf (buf);
4807 struct crypto_options co = tas->tls_auth_options;
4808 bool status;
4811 * We are in read-only mode at this point with respect to TLS
4812 * control channel state. After we build a new client instance
4813 * object, we will process this session-initiating packet for real.
4815 co.flags |= CO_IGNORE_PACKET_ID;
4817 /* HMAC test, if --tls-auth was specified */
4818 status = read_control_auth (&newbuf, &co, from);
4819 free_buf (&newbuf);
4820 if (!status)
4821 goto error;
4824 * At this point, if --tls-auth is being used, we know that
4825 * the packet has passed the HMAC test, but we don't know if
4826 * it is a replay yet. We will attempt to defeat replays
4827 * by not advancing to the S_START state until we
4828 * receive an ACK from our first reply to the client
4829 * that includes an HMAC of our randomly generated 64 bit
4830 * session ID.
4832 * On the other hand if --tls-auth is not being used, we
4833 * will proceed to begin the TLS authentication
4834 * handshake with only cursory integrity checks having
4835 * been performed, since we will be leaving the task
4836 * of authentication solely up to TLS.
4839 ret = true;
4842 gc_free (&gc);
4843 return ret;
4845 error:
4846 ERR_clear_error ();
4847 gc_free (&gc);
4848 return ret;
4851 /* Choose the key with which to encrypt a data packet */
4852 void
4853 tls_pre_encrypt (struct tls_multi *multi,
4854 struct buffer *buf, struct crypto_options *opt)
4856 multi->save_ks = NULL;
4857 if (buf->len > 0)
4859 int i;
4860 struct key_state *ks_select = NULL;
4861 for (i = 0; i < KEY_SCAN_SIZE; ++i)
4863 struct key_state *ks = multi->key_scan[i];
4864 if (ks->state >= S_ACTIVE
4865 && ks->authenticated
4866 #ifdef ENABLE_DEF_AUTH
4867 && !ks->auth_deferred
4868 #endif
4871 if (!ks_select)
4872 ks_select = ks;
4873 if (now >= ks->auth_deferred_expire)
4875 ks_select = ks;
4876 break;
4881 if (ks_select)
4883 opt->key_ctx_bi = &ks_select->key;
4884 opt->packet_id = multi->opt.replay ? &ks_select->packet_id : NULL;
4885 opt->pid_persist = NULL;
4886 opt->flags &= multi->opt.crypto_flags_and;
4887 opt->flags |= multi->opt.crypto_flags_or;
4888 multi->save_ks = ks_select;
4889 dmsg (D_TLS_KEYSELECT, "TLS: tls_pre_encrypt: key_id=%d", ks_select->key_id);
4890 return;
4892 else
4894 struct gc_arena gc = gc_new ();
4895 dmsg (D_TLS_KEYSELECT, "TLS Warning: no data channel send key available: %s",
4896 print_key_id (multi, &gc));
4897 gc_free (&gc);
4901 buf->len = 0;
4902 opt->key_ctx_bi = NULL;
4903 opt->packet_id = NULL;
4904 opt->pid_persist = NULL;
4905 opt->flags &= multi->opt.crypto_flags_and;
4908 /* Prepend the appropriate opcode to encrypted buffer prior to TCP/UDP send */
4909 void
4910 tls_post_encrypt (struct tls_multi *multi, struct buffer *buf)
4912 struct key_state *ks;
4913 uint8_t *op;
4915 ks = multi->save_ks;
4916 multi->save_ks = NULL;
4917 if (buf->len > 0)
4919 ASSERT (ks);
4920 ASSERT (op = buf_prepend (buf, 1));
4921 *op = (P_DATA_V1 << P_OPCODE_SHIFT) | ks->key_id;
4922 ++ks->n_packets;
4923 ks->n_bytes += buf->len;
4928 * Send a payload over the TLS control channel.
4929 * Called externally.
4932 bool
4933 tls_send_payload (struct tls_multi *multi,
4934 const uint8_t *data,
4935 int size)
4937 struct tls_session *session;
4938 struct key_state *ks;
4939 bool ret = false;
4941 ERR_clear_error ();
4943 ASSERT (multi);
4945 session = &multi->session[TM_ACTIVE];
4946 ks = &session->key[KS_PRIMARY];
4948 if (ks->state >= S_ACTIVE)
4950 if (key_state_write_plaintext_const (multi, ks, data, size) == 1)
4951 ret = true;
4954 ERR_clear_error ();
4956 return ret;
4959 bool
4960 tls_rec_payload (struct tls_multi *multi,
4961 struct buffer *buf)
4963 struct tls_session *session;
4964 struct key_state *ks;
4965 bool ret = false;
4967 ERR_clear_error ();
4969 ASSERT (multi);
4971 session = &multi->session[TM_ACTIVE];
4972 ks = &session->key[KS_PRIMARY];
4974 if (ks->state >= S_ACTIVE && BLEN (&ks->plaintext_read_buf))
4976 if (buf_copy (buf, &ks->plaintext_read_buf))
4977 ret = true;
4978 ks->plaintext_read_buf.len = 0;
4981 ERR_clear_error ();
4983 return ret;
4987 * Dump a human-readable rendition of an openvpn packet
4988 * into a garbage collectable string which is returned.
4990 const char *
4991 protocol_dump (struct buffer *buffer, unsigned int flags, struct gc_arena *gc)
4993 struct buffer out = alloc_buf_gc (256, gc);
4994 struct buffer buf = *buffer;
4996 uint8_t c;
4997 int op;
4998 int key_id;
5000 int tls_auth_hmac_size = (flags & PD_TLS_AUTH_HMAC_SIZE_MASK);
5002 if (buf.len <= 0)
5004 buf_printf (&out, "DATA UNDEF len=%d", buf.len);
5005 goto done;
5008 if (!(flags & PD_TLS))
5009 goto print_data;
5012 * Initial byte (opcode)
5014 if (!buf_read (&buf, &c, sizeof (c)))
5015 goto done;
5016 op = (c >> P_OPCODE_SHIFT);
5017 key_id = c & P_KEY_ID_MASK;
5018 buf_printf (&out, "%s kid=%d", packet_opcode_name (op), key_id);
5020 if (op == P_DATA_V1)
5021 goto print_data;
5024 * Session ID
5027 struct session_id sid;
5029 if (!session_id_read (&sid, &buf))
5030 goto done;
5031 if (flags & PD_VERBOSE)
5032 buf_printf (&out, " sid=%s", session_id_print (&sid, gc));
5036 * tls-auth hmac + packet_id
5038 if (tls_auth_hmac_size)
5040 struct packet_id_net pin;
5041 uint8_t tls_auth_hmac[MAX_HMAC_KEY_LENGTH];
5043 ASSERT (tls_auth_hmac_size <= MAX_HMAC_KEY_LENGTH);
5045 if (!buf_read (&buf, tls_auth_hmac, tls_auth_hmac_size))
5046 goto done;
5047 if (flags & PD_VERBOSE)
5048 buf_printf (&out, " tls_hmac=%s", format_hex (tls_auth_hmac, tls_auth_hmac_size, 0, gc));
5050 if (!packet_id_read (&pin, &buf, true))
5051 goto done;
5052 buf_printf(&out, " pid=%s", packet_id_net_print (&pin, (flags & PD_VERBOSE), gc));
5056 * ACK list
5058 buf_printf (&out, " %s", reliable_ack_print(&buf, (flags & PD_VERBOSE), gc));
5060 if (op == P_ACK_V1)
5061 goto done;
5064 * Packet ID
5067 packet_id_type l;
5068 if (!buf_read (&buf, &l, sizeof (l)))
5069 goto done;
5070 l = ntohpid (l);
5071 buf_printf (&out, " pid=" packet_id_format, (packet_id_print_type)l);
5074 print_data:
5075 if (flags & PD_SHOW_DATA)
5076 buf_printf (&out, " DATA %s", format_hex (BPTR (&buf), BLEN (&buf), 80, gc));
5077 else
5078 buf_printf (&out, " DATA len=%d", buf.len);
5080 done:
5081 return BSTR (&out);
5084 #else
5085 static void dummy(void) {}
5086 #endif /* USE_CRYPTO && USE_SSL*/