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
8 * Copyright (C) 2002-2005 OpenVPN Solutions LLC <info@openvpn.net>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program (see the file COPYING included with this
21 * distribution); if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 * The routines in this file deal with dynamically negotiating
27 * the data channel HMAC and cipher keys through a TLS session.
29 * Both the TLS session and the data channel are multiplexed
30 * over the same TCP/UDP port.
34 #include "config-win32.h"
39 #if defined(USE_CRYPTO) && defined(USE_SSL)
57 #include "cryptoapi.h"
63 static const char ssl_default_options_string
[] = "V0 UNDEF";
66 static inline const char *
67 local_options_string (const struct tls_session
*session
)
70 return session
->opt
->local_options
;
72 return ssl_default_options_string
;
76 #ifdef MEASURE_TLS_HANDSHAKE_STATS
78 static int tls_handshake_success
; /* GLOBAL */
79 static int tls_handshake_error
; /* GLOBAL */
80 static int tls_packets_generated
; /* GLOBAL */
81 static int tls_packets_sent
; /* GLOBAL */
83 #define INCR_SENT ++tls_packets_sent
84 #define INCR_GENERATED ++tls_packets_generated
85 #define INCR_SUCCESS ++tls_handshake_success
86 #define INCR_ERROR ++tls_handshake_error
89 show_tls_performance_stats(void)
91 msg (D_TLS_DEBUG_LOW
, "TLS Handshakes, success=%f%% (good=%d, bad=%d), retransmits=%f%%",
92 (double) tls_handshake_success
/ (tls_handshake_success
+ tls_handshake_error
) * 100.0,
93 tls_handshake_success
, tls_handshake_error
,
94 (double) (tls_packets_sent
- tls_packets_generated
) / tls_packets_generated
* 100.0);
99 #define INCR_GENERATED
107 #warning BIO_DEBUG defined
109 static FILE *biofp
; /* GLOBAL */
110 static bool biofp_toggle
; /* GLOBAL */
111 static time_t biofp_last_open
; /* GLOBAL */
112 static const int biofp_reopen_interval
= 600; /* GLOBAL */
119 ASSERT (!fclose (biofp
));
127 const time_t current
= time (NULL
);
128 const pid_t pid
= getpid ();
130 if (biofp_last_open
+ biofp_reopen_interval
< current
)
135 openvpn_snprintf(fn
, sizeof(fn
), "bio/%d-%d.log", pid
, biofp_toggle
);
136 biofp
= fopen (fn
, "w");
138 biofp_last_open
= time (NULL
);
144 bio_debug_data (const char *mode
, BIO
*bio
, const uint8_t *buf
, int len
, const char *desc
)
146 struct gc_arena gc
= gc_new ();
150 fprintf(biofp
, "BIO_%s %s time=" time_format
" bio=" ptr_format
" len=%d data=%s\n",
151 mode
, desc
, time (NULL
), (ptr_type
)bio
, len
, format_hex (buf
, len
, 0, &gc
));
158 bio_debug_oc (const char *mode
, BIO
*bio
)
161 fprintf(biofp
, "BIO %s time=" time_format
" bio=" ptr_format
"\n",
162 mode
, time (NULL
), (ptr_type
)bio
);
169 * Max number of bytes we will add
170 * for data structures common to both
171 * data and control channel packets.
175 tls_adjust_frame_parameters(struct frame
*frame
)
177 frame_add_to_extra_frame (frame
, 1); /* space for opcode */
181 * Max number of bytes we will add
182 * to control channel packet.
185 tls_init_control_channel_frame_parameters(const struct frame
*data_channel_frame
,
189 * frame->extra_frame is already initialized with tls_auth buffer requirements,
190 * if --tls-auth is enabled.
193 /* inherit link MTU and extra_link from data channel */
194 frame
->link_mtu
= data_channel_frame
->link_mtu
;
195 frame
->extra_link
= data_channel_frame
->extra_link
;
197 /* set extra_frame */
198 tls_adjust_frame_parameters (frame
);
199 reliable_ack_adjust_frame_parameters (frame
, CONTROL_SEND_ACK_MAX
);
200 frame_add_to_extra_frame (frame
, SID_SIZE
+ sizeof (packet_id_type
));
202 /* set dynamic link MTU to minimum value */
203 frame_set_mtu_dynamic (frame
, 0, SET_MTU_TUN
);
207 * Allocate space in SSL objects
208 * in which to store a struct tls_session
209 * pointer back to parent.
212 static int mydata_index
; /* GLOBAL */
215 ssl_set_mydata_index ()
217 mydata_index
= SSL_get_ex_new_index (0, "struct session *", NULL
, NULL
, NULL
);
218 ASSERT (mydata_index
>= 0);
225 SSL_load_error_strings ();
226 OpenSSL_add_all_algorithms ();
231 * If you build the OpenSSL library and OpenVPN with
232 * CRYPTO_MDEBUG, you will get a listing of OpenSSL
233 * memory leaks on program termination.
236 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON
);
239 ssl_set_mydata_index ();
246 FILE* fp
= fopen ("sdlog", "w");
248 CRYPTO_mem_leaks_fp (fp
);
252 uninit_crypto_lib ();
258 * OpenSSL library calls pem_password_callback if the
259 * private key is protected by a password.
262 static struct user_pass passbuf
; /* GLOBAL */
265 pem_password_setup (const char *auth_file
)
267 if (!strlen (passbuf
.password
))
268 get_user_pass (&passbuf
, auth_file
, true, UP_TYPE_PRIVATE_KEY
, GET_USER_PASS_MANAGEMENT
|GET_USER_PASS_SENSITIVE
);
272 pem_password_callback (char *buf
, int size
, int rwflag
, void *u
)
276 /* prompt for password even if --askpass wasn't specified */
277 pem_password_setup (NULL
);
278 strncpynt (buf
, passbuf
.password
, size
);
279 purge_user_pass (&passbuf
, false);
287 * Auth username/password handling
290 static bool auth_user_pass_enabled
; /* GLOBAL */
291 static struct user_pass auth_user_pass
; /* GLOBAL */
294 auth_user_pass_setup (const char *auth_file
)
296 auth_user_pass_enabled
= true;
297 if (!auth_user_pass
.defined
)
298 get_user_pass (&auth_user_pass
, auth_file
, false, UP_TYPE_AUTH
, GET_USER_PASS_MANAGEMENT
|GET_USER_PASS_SENSITIVE
);
302 * Disable password caching
305 ssl_set_auth_nocache (void)
307 passbuf
.nocache
= true;
308 auth_user_pass
.nocache
= true;
312 * Forget private key password AND auth-user-pass username/password.
315 ssl_purge_auth (void)
317 #if 1 /* JYFIXME -- todo: bad private key should trigger a signal, then this code can be included */
318 purge_user_pass (&passbuf
, true);
320 purge_user_pass (&auth_user_pass
, true);
324 * OpenSSL callback to get a temporary RSA key, mostly
325 * used for export ciphers.
328 tmp_rsa_cb (SSL
* s
, int is_export
, int keylength
)
330 static RSA
*rsa_tmp
= NULL
;
333 msg (D_HANDSHAKE
, "Generating temp (%d bit) RSA key", keylength
);
334 rsa_tmp
= RSA_generate_key (keylength
, RSA_F4
, NULL
, NULL
);
340 * Extract a field from an X509 subject name.
344 * /C=US/ST=CO/L=Denver/O=ORG/CN=Test-CA/Email=jim@yonan.net
346 * The common name is 'Test-CA'
349 extract_x509_field (const char *x509
, const char *field_name
, char *out
, int size
)
352 struct buffer x509_buf
;
356 buf_set_read (&x509_buf
, (uint8_t *)x509
, strlen (x509
));
357 while (buf_parse (&x509_buf
, '/', field_buf
, sizeof (field_buf
)))
359 struct buffer component_buf
;
360 char field_name_buf
[64];
361 char field_value_buf
[256];
362 buf_set_read (&component_buf
, (const uint8_t *) field_buf
, strlen (field_buf
));
363 buf_parse (&component_buf
, '=', field_name_buf
, sizeof (field_name_buf
));
364 buf_parse (&component_buf
, '=', field_value_buf
, sizeof (field_value_buf
));
365 if (!strcmp (field_name_buf
, field_name
))
367 strncpynt (out
, field_value_buf
, size
);
374 setenv_untrusted (struct tls_session
*session
)
376 setenv_sockaddr (session
->opt
->es
, "untrusted", &session
->untrusted_sockaddr
, SA_IP_PORT
);
380 set_common_name (struct tls_session
*session
, const char *common_name
)
382 if (session
->common_name
)
384 free (session
->common_name
);
385 session
->common_name
= NULL
;
389 session
->common_name
= string_alloc (common_name
, NULL
);
394 * nsCertType checking
397 #define verify_nsCertType(x, usage) (((x)->ex_flags & EXFLAG_NSCERT) && ((x)->ex_nscert & (usage)))
400 print_nsCertType (int type
)
414 * Our verify callback function -- check
415 * that an incoming peer certificate is good.
419 verify_callback (int preverify_ok
, X509_STORE_CTX
* ctx
)
423 char common_name
[TLS_CN_LEN
];
425 struct tls_session
*session
;
426 const struct tls_options
*opt
;
427 const int max_depth
= 8;
429 /* get the tls_session pointer */
430 ssl
= X509_STORE_CTX_get_ex_data (ctx
, SSL_get_ex_data_X509_STORE_CTX_idx());
432 session
= (struct tls_session
*) SSL_get_ex_data (ssl
, mydata_index
);
437 session
->verified
= false;
439 /* get the X509 name */
440 X509_NAME_oneline (X509_get_subject_name (ctx
->current_cert
), subject
,
442 subject
[sizeof (subject
) - 1] = '\0';
444 /* enforce character class restrictions in X509 name */
445 string_mod (subject
, X509_NAME_CHAR_CLASS
, 0, '_');
447 /* extract the common name */
448 extract_x509_field (subject
, "CN", common_name
, TLS_CN_LEN
);
449 string_mod (common_name
, COMMON_NAME_CHAR_CLASS
, 0, '_');
451 #if 0 /* print some debugging info */
452 msg (D_LOW
, "LOCAL OPT: %s", opt
->local_options
);
453 msg (D_LOW
, "X509: %s", subject
);
456 /* did peer present cert which was signed our root cert? */
459 /* Remote site specified a certificate, but it's not correct */
460 msg (D_TLS_ERRORS
, "VERIFY ERROR: depth=%d, error=%s: %s",
461 ctx
->error_depth
, X509_verify_cert_error_string (ctx
->error
), subject
);
462 goto err
; /* Reject connection */
465 /* warn if cert chain is too deep */
466 if (ctx
->error_depth
>= max_depth
)
467 msg (M_WARN
, "TLS Warning: Convoluted certificate chain detected with depth [%d] greater than %d", ctx
->error_depth
, max_depth
);
469 /* save common name in session object */
470 if (ctx
->error_depth
== 0)
471 set_common_name (session
, common_name
);
473 /* export subject name string as environmental variable */
474 session
->verify_maxlevel
= max_int (session
->verify_maxlevel
, ctx
->error_depth
);
475 openvpn_snprintf (envname
, sizeof(envname
), "tls_id_%d", ctx
->error_depth
);
476 setenv_str (opt
->es
, envname
, subject
);
479 /* export common name string as environmental variable */
480 openvpn_snprintf (envname
, sizeof(envname
), "tls_common_name_%d", ctx
->error_depth
);
481 setenv_str (opt
->es
, envname
, common_name
);
484 /* export serial number as environmental variable */
486 const int serial
= (int) ASN1_INTEGER_get (X509_get_serialNumber (ctx
->current_cert
));
487 openvpn_snprintf (envname
, sizeof(envname
), "tls_serial_%d", ctx
->error_depth
);
488 setenv_int (opt
->es
, envname
, serial
);
491 /* export current untrusted IP */
492 setenv_untrusted (session
);
494 /* verify certificate nsCertType */
495 if (opt
->ns_cert_type
&& ctx
->error_depth
== 0)
497 if (verify_nsCertType (ctx
->current_cert
, opt
->ns_cert_type
))
499 msg (D_HANDSHAKE
, "VERIFY OK: nsCertType=%s",
500 print_nsCertType (opt
->ns_cert_type
));
504 msg (D_HANDSHAKE
, "VERIFY nsCertType ERROR: %s, require nsCertType=%s",
505 subject
, print_nsCertType (opt
->ns_cert_type
));
506 goto err
; /* Reject connection */
510 /* verify X509 name or common name against --tls-remote */
511 if (opt
->verify_x509name
&& strlen (opt
->verify_x509name
) > 0 && ctx
->error_depth
== 0)
513 if (strcmp (opt
->verify_x509name
, subject
) == 0
514 || strncmp (opt
->verify_x509name
, common_name
, strlen (opt
->verify_x509name
)) == 0)
515 msg (D_HANDSHAKE
, "VERIFY X509NAME OK: %s", subject
);
518 msg (D_HANDSHAKE
, "VERIFY X509NAME ERROR: %s, must be %s",
519 subject
, opt
->verify_x509name
);
520 goto err
; /* Reject connection */
524 /* call --tls-verify plug-in(s) */
525 if (plugin_defined (opt
->plugins
, OPENVPN_PLUGIN_TLS_VERIFY
))
531 buf_set_write (&out
, (uint8_t*)command
, sizeof (command
));
532 buf_printf (&out
, "%d %s",
536 ret
= plugin_call (opt
->plugins
, OPENVPN_PLUGIN_TLS_VERIFY
, command
, opt
->es
);
540 msg (D_HANDSHAKE
, "VERIFY PLUGIN OK: depth=%d, %s",
541 ctx
->error_depth
, subject
);
545 msg (D_HANDSHAKE
, "VERIFY PLUGIN ERROR: depth=%d, %s",
546 ctx
->error_depth
, subject
);
547 goto err
; /* Reject connection */
551 /* run --tls-verify script */
552 if (opt
->verify_command
)
558 setenv_str (opt
->es
, "script_type", "tls-verify");
560 buf_set_write (&out
, (uint8_t*)command
, sizeof (command
));
561 buf_printf (&out
, "%s %d %s",
565 dmsg (D_TLS_DEBUG
, "TLS: executing verify command: %s", command
);
566 ret
= openvpn_system (command
, opt
->es
, S_SCRIPT
);
570 msg (D_HANDSHAKE
, "VERIFY SCRIPT OK: depth=%d, %s",
571 ctx
->error_depth
, subject
);
575 if (!system_executed (ret
))
576 msg (M_ERR
, "Verify command failed to execute: %s", command
);
577 msg (D_HANDSHAKE
, "VERIFY SCRIPT ERROR: depth=%d, %s",
578 ctx
->error_depth
, subject
);
579 goto err
; /* Reject connection */
583 /* check peer cert against CRL */
587 X509_REVOKED
*revoked
;
591 in
=BIO_new(BIO_s_file());
594 msg (M_ERR
, "CRL: BIO err");
597 if (BIO_read_filename(in
, opt
->crl_file
) <= 0) {
598 msg (M_ERR
, "CRL: cannot read: %s", opt
->crl_file
);
601 crl
=PEM_read_bio_X509_CRL(in
,NULL
,NULL
,NULL
);
603 msg (M_ERR
, "CRL: cannot read CRL from file %s", opt
->crl_file
);
607 if (X509_NAME_cmp(X509_CRL_get_issuer(crl
), X509_get_issuer_name(ctx
->current_cert
)) != 0) {
608 msg (M_WARN
, "CRL: CRL %s is from a different issuer than the issuer of certificate %s", opt
->crl_file
, subject
);
613 n
= sk_num(X509_CRL_get_REVOKED(crl
));
615 for (i
= 0; i
< n
; i
++) {
616 revoked
= (X509_REVOKED
*)sk_value(X509_CRL_get_REVOKED(crl
), i
);
617 if (ASN1_INTEGER_cmp(revoked
->serialNumber
, X509_get_serialNumber(ctx
->current_cert
)) == 0) {
618 msg (D_HANDSHAKE
, "CRL CHECK FAILED: %s is REVOKED",subject
);
624 msg (D_HANDSHAKE
, "CRL CHECK OK: %s",subject
);
635 msg (D_HANDSHAKE
, "VERIFY OK: depth=%d, %s", ctx
->error_depth
, subject
);
637 session
->verified
= true;
638 return 1; /* Accept connection */
642 return 0; /* Reject connection */
646 tls_set_common_name (struct tls_multi
*multi
, const char *common_name
)
649 set_common_name (&multi
->session
[TM_ACTIVE
], common_name
);
653 tls_common_name (struct tls_multi
*multi
, bool null
)
655 const char *ret
= NULL
;
657 ret
= multi
->session
[TM_ACTIVE
].common_name
;
658 if (ret
&& strlen (ret
))
667 tls_lock_common_name (struct tls_multi
*multi
)
669 const char *cn
= multi
->session
[TM_ACTIVE
].common_name
;
670 if (cn
&& !multi
->locked_cn
)
671 multi
->locked_cn
= string_alloc (cn
, NULL
);
675 * Return true if at least one valid key state exists
676 * which has passed authentication. If we are using
677 * username/password authentication, and the authentication
678 * failed, we may have a live S_ACTIVE/S_NORMAL key state
679 * even though the 'authenticated' var might be false.
681 * This is so that we can return an AUTH_FAILED error
682 * message to the client over the TLS channel.
684 * If 'authenticated' is false, tunnel traffic forwarding
685 * is disabled but TLS channel data can still be sent
689 tls_authenticated (struct tls_multi
*multi
)
694 for (i
= 0; i
< KEY_SCAN_SIZE
; ++i
)
696 const struct key_state
*ks
= multi
->key_scan
[i
];
697 if (DECRYPT_KEY_ENABLED (multi
, ks
) && ks
->authenticated
)
705 tls_deauthenticate (struct tls_multi
*multi
)
710 for (i
= 0; i
< TM_SIZE
; ++i
)
711 for (j
= 0; j
< KS_SIZE
; ++j
)
712 multi
->session
[i
].key
[j
].authenticated
= false;
717 * Print debugging information on SSL/TLS session negotiation.
720 info_callback (INFO_CALLBACK_SSL_CONST SSL
* s
, int where
, int ret
)
722 if (where
& SSL_CB_LOOP
)
724 dmsg (D_HANDSHAKE_VERBOSE
, "SSL state (%s): %s",
725 where
& SSL_ST_CONNECT
? "connect" :
726 where
& SSL_ST_ACCEPT
? "accept" :
727 "undefined", SSL_state_string_long (s
));
729 else if (where
& SSL_CB_ALERT
)
731 dmsg (D_HANDSHAKE_VERBOSE
, "SSL alert (%s): %s: %s",
732 where
& SSL_CB_READ
? "read" : "write",
733 SSL_alert_type_string_long (ret
),
734 SSL_alert_desc_string_long (ret
));
739 * Initialize SSL context.
740 * All files are in PEM format.
743 init_ssl (const struct options
*options
)
748 bool using_cert_file
= false;
752 if (options
->tls_server
)
754 ctx
= SSL_CTX_new (TLSv1_server_method ());
756 msg (M_SSLERR
, "SSL_CTX_new TLSv1_server_method");
758 SSL_CTX_set_tmp_rsa_callback (ctx
, tmp_rsa_cb
);
760 /* Get Diffie Hellman Parameters */
761 if (!(bio
= BIO_new_file (options
->dh_file
, "r")))
762 msg (M_SSLERR
, "Cannot open %s for DH parameters", options
->dh_file
);
763 dh
= PEM_read_bio_DHparams (bio
, NULL
, NULL
, NULL
);
766 msg (M_SSLERR
, "Cannot load DH parameters from %s", options
->dh_file
);
767 if (!SSL_CTX_set_tmp_dh (ctx
, dh
))
768 msg (M_SSLERR
, "SSL_CTX_set_tmp_dh");
769 msg (D_TLS_DEBUG_LOW
, "Diffie-Hellman initialized with %d bit key",
775 ctx
= SSL_CTX_new (TLSv1_client_method ());
777 msg (M_SSLERR
, "SSL_CTX_new TLSv1_client_method");
780 /* Set SSL options */
781 SSL_CTX_set_session_cache_mode (ctx
, SSL_SESS_CACHE_OFF
);
782 SSL_CTX_set_options (ctx
, SSL_OP_SINGLE_DH_USE
);
784 /* Set callback for getting password from user to decrypt private key */
785 SSL_CTX_set_default_passwd_cb (ctx
, pem_password_callback
);
787 if (options
->pkcs12_file
)
789 /* Use PKCS #12 file for key, cert and CA certs */
794 STACK_OF(X509
) *ca
= NULL
;
799 /* Load the PKCS #12 file */
800 if (!(fp
= fopen(options
->pkcs12_file
, "rb")))
801 msg (M_SSLERR
, "Error opening file %s", options
->pkcs12_file
);
802 p12
= d2i_PKCS12_fp(fp
, NULL
);
804 if (!p12
) msg (M_SSLERR
, "Error reading PKCS#12 file %s", options
->pkcs12_file
);
806 /* Parse the PKCS #12 file */
807 if (!PKCS12_parse(p12
, "", &pkey
, &cert
, &ca
))
809 pem_password_callback (password
, sizeof(password
) - 1, 0, NULL
);
810 /* Reparse the PKCS #12 file with password */
812 if (!PKCS12_parse(p12
, password
, &pkey
, &cert
, &ca
))
815 msg (M_WARN
|M_SSL
, "Error parsing PKCS#12 file %s", options
->pkcs12_file
);
821 /* Load Certificate */
822 if (!SSL_CTX_use_certificate (ctx
, cert
))
823 msg (M_SSLERR
, "Cannot use certificate");
825 /* Load Private Key */
826 if (!SSL_CTX_use_PrivateKey (ctx
, pkey
))
827 msg (M_SSLERR
, "Cannot use private key");
828 warn_if_group_others_accessible (options
->pkcs12_file
);
830 /* Check Private Key */
831 if (!SSL_CTX_check_private_key (ctx
))
832 msg (M_SSLERR
, "Private key does not match the certificate");
834 /* Set Certificate Verification chain */
835 if (ca
&& sk_num(ca
))
837 for (i
= 0; i
< sk_X509_num(ca
); i
++)
839 if (!X509_STORE_add_cert(ctx
->cert_store
,sk_X509_value(ca
, i
)))
840 msg (M_SSLERR
, "Cannot add certificate to certificate chain (X509_STORE_add_cert)");
841 if (!SSL_CTX_add_client_CA(ctx
, sk_X509_value(ca
, i
)))
842 msg (M_SSLERR
, "Cannot add certificate to client CA list (SSL_CTX_add_client_CA)");
848 /* Use seperate PEM files for key, cert and CA certs */
851 if (options
->cryptoapi_cert
)
853 /* Load Certificate and Private Key */
854 if (!SSL_CTX_use_CryptoAPI_certificate (ctx
, options
->cryptoapi_cert
))
855 msg (M_SSLERR
, "Cannot load certificate \"%s\" from Microsoft Certificate Store",
856 options
->cryptoapi_cert
);
861 /* Load Certificate */
862 if (options
->cert_file
)
864 using_cert_file
= true;
865 if (!SSL_CTX_use_certificate_file (ctx
, options
->cert_file
, SSL_FILETYPE_PEM
))
866 msg (M_SSLERR
, "Cannot load certificate file %s", options
->cert_file
);
869 /* Load Private Key */
870 if (options
->priv_key_file
)
872 if (!SSL_CTX_use_PrivateKey_file (ctx
, options
->priv_key_file
, SSL_FILETYPE_PEM
))
874 #ifdef ENABLE_MANAGEMENT
875 if (management
&& (ERR_GET_REASON (ERR_peek_error()) == EVP_R_BAD_DECRYPT
))
876 management_auth_failure (management
, UP_TYPE_PRIVATE_KEY
);
878 msg (M_WARN
|M_SSL
, "Cannot load private key file %s", options
->priv_key_file
);
881 warn_if_group_others_accessible (options
->priv_key_file
);
883 /* Check Private Key */
884 if (!SSL_CTX_check_private_key (ctx
))
885 msg (M_SSLERR
, "Private key does not match the certificate");
889 /* Load CA file for verifying peer supplied certificate */
890 ASSERT (options
->ca_file
);
891 if (!SSL_CTX_load_verify_locations (ctx
, options
->ca_file
, NULL
))
892 msg (M_SSLERR
, "Cannot load CA certificate file %s (SSL_CTX_load_verify_locations)", options
->ca_file
);
894 /* Load names of CAs from file and use it as a client CA list */
896 STACK_OF(X509_NAME
) *cert_names
;
897 cert_names
= SSL_load_client_CA_file (options
->ca_file
);
899 msg (M_SSLERR
, "Cannot load CA certificate file %s (SSL_load_client_CA_file)", options
->ca_file
);
900 SSL_CTX_set_client_CA_list (ctx
, cert_names
);
905 /* Enable the use of certificate chains */
908 if (!SSL_CTX_use_certificate_chain_file (ctx
, options
->cert_file
))
909 msg (M_SSLERR
, "Cannot load certificate chain file %s (SSL_use_certificate_chain_file)", options
->cert_file
);
912 /* Require peer certificate verification */
914 if (options
->client_cert_not_required
)
916 msg (M_WARN
, "WARNING: This configuration may accept clients which do not present a certificate");
920 SSL_CTX_set_verify (ctx
, SSL_VERIFY_PEER
| SSL_VERIFY_FAIL_IF_NO_PEER_CERT
,
923 /* Connection information callback */
924 SSL_CTX_set_info_callback (ctx
, info_callback
);
926 /* Allowable ciphers */
927 if (options
->cipher_list
)
929 if (!SSL_CTX_set_cipher_list (ctx
, options
->cipher_list
))
930 msg (M_SSLERR
, "Problem with cipher list: %s", options
->cipher_list
);
945 * Print a one line summary of SSL/TLS session handshake.
948 print_details (SSL
* c_ssl
, const char *prefix
)
956 ciph
= SSL_get_current_cipher (c_ssl
);
957 openvpn_snprintf (s1
, sizeof (s1
), "%s %s, cipher %s %s",
959 SSL_get_version (c_ssl
),
960 SSL_CIPHER_get_version (ciph
),
961 SSL_CIPHER_get_name (ciph
));
962 cert
= SSL_get_peer_certificate (c_ssl
);
965 EVP_PKEY
*pkey
= X509_get_pubkey (cert
);
968 if (pkey
->type
== EVP_PKEY_RSA
&& pkey
->pkey
.rsa
!= NULL
969 && pkey
->pkey
.rsa
->n
!= NULL
)
971 openvpn_snprintf (s2
, sizeof (s2
), ", %d bit RSA",
972 BN_num_bits (pkey
->pkey
.rsa
->n
));
974 else if (pkey
->type
== EVP_PKEY_DSA
&& pkey
->pkey
.dsa
!= NULL
975 && pkey
->pkey
.dsa
->p
!= NULL
)
977 openvpn_snprintf (s2
, sizeof (s2
), ", %d bit DSA",
978 BN_num_bits (pkey
->pkey
.dsa
->p
));
980 EVP_PKEY_free (pkey
);
984 /* The SSL API does not allow us to look at temporary RSA/DH keys,
985 * otherwise we should print their lengths too */
986 msg (D_HANDSHAKE
, "%s%s", s1
, s2
);
990 * Show the TLS ciphers that are available for us to use
991 * in the OpenSSL library.
994 show_available_tls_ciphers ()
998 const char *cipher_name
;
1001 ctx
= SSL_CTX_new (TLSv1_method ());
1003 msg (M_SSLERR
, "Cannot create SSL_CTX object");
1004 ssl
= SSL_new (ctx
);
1006 msg (M_SSLERR
, "Cannot create SSL object");
1008 printf ("Available TLS Ciphers,\n");
1009 printf ("listed in order of preference:\n\n");
1010 while ((cipher_name
= SSL_get_cipher_list (ssl
, priority
++)))
1011 printf ("%s\n", cipher_name
);
1019 * The OpenSSL library has a notion of preference in TLS
1020 * ciphers. Higher preference == more secure.
1021 * Return the highest preference cipher.
1024 get_highest_preference_tls_cipher (char *buf
, int size
)
1028 const char *cipher_name
;
1030 ctx
= SSL_CTX_new (TLSv1_method ());
1032 msg (M_SSLERR
, "Cannot create SSL_CTX object");
1033 ssl
= SSL_new (ctx
);
1035 msg (M_SSLERR
, "Cannot create SSL object");
1037 cipher_name
= SSL_get_cipher_list (ssl
, 0);
1038 strncpynt (buf
, cipher_name
, size
);
1045 * Map internal constants to ascii names.
1048 state_name (int state
)
1057 return "S_PRE_START";
1061 return "S_SENT_KEY";
1076 packet_opcode_name (int op
)
1080 case P_CONTROL_HARD_RESET_CLIENT_V1
:
1081 return "P_CONTROL_HARD_RESET_CLIENT_V1";
1082 case P_CONTROL_HARD_RESET_SERVER_V1
:
1083 return "P_CONTROL_HARD_RESET_SERVER_V1";
1084 case P_CONTROL_HARD_RESET_CLIENT_V2
:
1085 return "P_CONTROL_HARD_RESET_CLIENT_V2";
1086 case P_CONTROL_HARD_RESET_SERVER_V2
:
1087 return "P_CONTROL_HARD_RESET_SERVER_V2";
1088 case P_CONTROL_SOFT_RESET_V1
:
1089 return "P_CONTROL_SOFT_RESET_V1";
1091 return "P_CONTROL_V1";
1102 session_index_name (int index
)
1109 return "TM_UNTRUSTED";
1111 return "TM_LAME_DUCK";
1121 print_key_id (struct tls_multi
*multi
, struct gc_arena
*gc
)
1124 struct buffer out
= alloc_buf_gc (256, gc
);
1126 for (i
= 0; i
< KEY_SCAN_SIZE
; ++i
)
1128 struct key_state
*ks
= multi
->key_scan
[i
];
1129 buf_printf (&out
, " [key#%d state=%s id=%d sid=%s]", i
,
1130 state_name (ks
->state
), ks
->key_id
,
1131 session_id_print (&ks
->session_id_remote
, gc
));
1138 * Given a key_method, return true if op
1139 * represents the required form of hard_reset.
1141 * If key_method = 0, return true if any
1142 * form of hard reset is used.
1145 is_hard_reset (int op
, int key_method
)
1147 if (!key_method
|| key_method
== 1)
1148 if (op
== P_CONTROL_HARD_RESET_CLIENT_V1
|| op
== P_CONTROL_HARD_RESET_SERVER_V1
)
1151 if (!key_method
|| key_method
>= 2)
1152 if (op
== P_CONTROL_HARD_RESET_CLIENT_V2
|| op
== P_CONTROL_HARD_RESET_SERVER_V2
)
1159 * OpenVPN's interface to SSL/TLS authentication,
1160 * encryption, and decryption is exclusively
1161 * through "memory BIOs".
1164 getbio (BIO_METHOD
* type
, const char *desc
)
1167 ret
= BIO_new (type
);
1169 msg (M_SSLERR
, "Error creating %s BIO", desc
);
1174 * Write to an OpenSSL BIO in non-blocking mode.
1177 bio_write (struct tls_multi
* multi
, BIO
*bio
, const uint8_t *data
, int size
, const char *desc
)
1185 * Free the L_TLS lock prior to calling BIO routines
1186 * so that foreground thread can still call
1187 * tls_pre_decrypt or tls_pre_encrypt,
1188 * allowing tunnel packet forwarding to continue.
1191 bio_debug_data ("write", bio
, data
, size
, desc
);
1193 i
= BIO_write (bio
, data
, size
);
1197 if (BIO_should_retry (bio
))
1203 msg (D_TLS_ERRORS
| M_SSL
, "TLS ERROR: BIO write %s error",
1211 msg (D_TLS_ERRORS
| M_SSL
,
1212 "TLS ERROR: BIO write %s incomplete %d/%d", desc
, i
, size
);
1217 { /* successful write */
1218 dmsg (D_HANDSHAKE_VERBOSE
, "BIO write %s %d bytes", desc
, i
);
1226 * Read from an OpenSSL BIO in non-blocking mode.
1229 bio_read (struct tls_multi
* multi
, BIO
*bio
, struct buffer
*buf
, int maxlen
, const char *desc
)
1233 ASSERT (buf
->len
>= 0);
1240 int len
= buf_forward_capacity (buf
);
1245 * BIO_read brackets most of the serious RSA
1246 * key negotiation number crunching.
1248 i
= BIO_read (bio
, BPTR (buf
), len
);
1250 VALGRIND_MAKE_READABLE ((void *) &i
, sizeof (i
));
1253 bio_debug_data ("read", bio
, BPTR (buf
), i
, desc
);
1257 if (BIO_should_retry (bio
))
1263 msg (D_TLS_ERRORS
| M_SSL
, "TLS_ERROR: BIO read %s error",
1275 { /* successful read */
1276 dmsg (D_HANDSHAKE_VERBOSE
, "BIO read %s %d bytes", desc
, i
);
1279 VALGRIND_MAKE_READABLE ((void *) BPTR (buf
), BLEN (buf
));
1286 * Inline functions for reading from and writing
1291 bio_write_post (const int status
, struct buffer
*buf
)
1293 if (status
== 1) /* success status return from bio_write? */
1295 memset (BPTR (buf
), 0, BLEN (buf
)); /* erase data just written */
1301 key_state_write_plaintext (struct tls_multi
*multi
, struct key_state
*ks
, struct buffer
*buf
)
1304 perf_push (PERF_BIO_WRITE_PLAINTEXT
);
1305 ret
= bio_write (multi
, ks
->ssl_bio
, BPTR(buf
), BLEN(buf
), "tls_write_plaintext");
1306 bio_write_post (ret
, buf
);
1312 key_state_write_plaintext_const (struct tls_multi
*multi
, struct key_state
*ks
, const uint8_t *data
, int len
)
1315 perf_push (PERF_BIO_WRITE_PLAINTEXT
);
1316 ret
= bio_write (multi
, ks
->ssl_bio
, data
, len
, "tls_write_plaintext_const");
1322 key_state_write_ciphertext (struct tls_multi
*multi
, struct key_state
*ks
, struct buffer
*buf
)
1325 perf_push (PERF_BIO_WRITE_CIPHERTEXT
);
1326 ret
= bio_write (multi
, ks
->ct_in
, BPTR(buf
), BLEN(buf
), "tls_write_ciphertext");
1327 bio_write_post (ret
, buf
);
1333 key_state_read_plaintext (struct tls_multi
*multi
, struct key_state
*ks
, struct buffer
*buf
,
1337 perf_push (PERF_BIO_READ_PLAINTEXT
);
1338 ret
= bio_read (multi
, ks
->ssl_bio
, buf
, maxlen
, "tls_read_plaintext");
1344 key_state_read_ciphertext (struct tls_multi
*multi
, struct key_state
*ks
, struct buffer
*buf
,
1348 perf_push (PERF_BIO_READ_CIPHERTEXT
);
1349 ret
= bio_read (multi
, ks
->ct_out
, buf
, maxlen
, "tls_read_ciphertext");
1355 * Initialize a key_state. Each key_state corresponds to
1356 * a specific SSL/TLS session.
1359 key_state_init (struct tls_session
*session
, struct key_state
*ks
)
1364 * Build TLS object that reads/writes ciphertext
1365 * to/from memory BIOs.
1369 ks
->ssl
= SSL_new (session
->opt
->ssl_ctx
);
1371 msg (M_SSLERR
, "SSL_new failed");
1373 /* put session * in ssl object so we can access it
1374 from verify callback*/
1375 SSL_set_ex_data (ks
->ssl
, mydata_index
, session
);
1377 ks
->ssl_bio
= getbio (BIO_f_ssl (), "ssl_bio");
1378 ks
->ct_in
= getbio (BIO_s_mem (), "ct_in");
1379 ks
->ct_out
= getbio (BIO_s_mem (), "ct_out");
1382 bio_debug_oc ("open ssl_bio", ks
->ssl_bio
);
1383 bio_debug_oc ("open ct_in", ks
->ct_in
);
1384 bio_debug_oc ("open ct_out", ks
->ct_out
);
1387 if (session
->opt
->server
)
1388 SSL_set_accept_state (ks
->ssl
);
1390 SSL_set_connect_state (ks
->ssl
);
1392 SSL_set_bio (ks
->ssl
, ks
->ct_in
, ks
->ct_out
);
1393 BIO_set_ssl (ks
->ssl_bio
, ks
->ssl
, BIO_NOCLOSE
);
1395 /* Set control-channel initiation mode */
1396 ks
->initial_opcode
= session
->initial_opcode
;
1397 session
->initial_opcode
= P_CONTROL_SOFT_RESET_V1
;
1398 ks
->state
= S_INITIAL
;
1399 ks
->key_id
= session
->key_id
;
1402 * key_id increments to KEY_ID_MASK then recycles back to 1.
1403 * This way you know that if key_id is 0, it is the first key.
1406 session
->key_id
&= P_KEY_ID_MASK
;
1407 if (!session
->key_id
)
1408 session
->key_id
= 1;
1410 /* allocate key source material object */
1411 ALLOC_OBJ_CLEAR (ks
->key_src
, struct key_source2
);
1413 /* allocate reliability objects */
1414 ALLOC_OBJ_CLEAR (ks
->send_reliable
, struct reliable
);
1415 ALLOC_OBJ_CLEAR (ks
->rec_reliable
, struct reliable
);
1416 ALLOC_OBJ_CLEAR (ks
->rec_ack
, struct reliable_ack
);
1418 /* allocate buffers */
1419 ks
->plaintext_read_buf
= alloc_buf (PLAINTEXT_BUFFER_SIZE
);
1420 ks
->plaintext_write_buf
= alloc_buf (PLAINTEXT_BUFFER_SIZE
);
1421 ks
->ack_write_buf
= alloc_buf (BUF_SIZE (&session
->opt
->frame
));
1422 reliable_init (ks
->send_reliable
, BUF_SIZE (&session
->opt
->frame
),
1423 FRAME_HEADROOM (&session
->opt
->frame
), TLS_RELIABLE_N_SEND_BUFFERS
);
1424 reliable_init (ks
->rec_reliable
, BUF_SIZE (&session
->opt
->frame
),
1425 FRAME_HEADROOM (&session
->opt
->frame
), TLS_RELIABLE_N_REC_BUFFERS
);
1426 reliable_set_timeout (ks
->send_reliable
, session
->opt
->packet_timeout
);
1428 /* init packet ID tracker */
1429 packet_id_init (&ks
->packet_id
,
1430 session
->opt
->replay_window
,
1431 session
->opt
->replay_time
);
1435 key_state_free (struct key_state
*ks
, bool clear
)
1437 ks
->state
= S_UNDEF
;
1441 bio_debug_oc ("close ssl_bio", ks
->ssl_bio
);
1442 bio_debug_oc ("close ct_in", ks
->ct_in
);
1443 bio_debug_oc ("close ct_out", ks
->ct_out
);
1445 BIO_free_all(ks
->ssl_bio
);
1449 free_key_ctx_bi (&ks
->key
);
1450 free_buf (&ks
->plaintext_read_buf
);
1451 free_buf (&ks
->plaintext_write_buf
);
1452 free_buf (&ks
->ack_write_buf
);
1454 if (ks
->send_reliable
)
1456 reliable_free (ks
->send_reliable
);
1457 free (ks
->send_reliable
);
1460 if (ks
->rec_reliable
)
1462 reliable_free (ks
->rec_reliable
);
1463 free (ks
->rec_reliable
);
1472 packet_id_free (&ks
->packet_id
);
1479 * Must be called if we move a tls_session in memory.
1481 static inline void tls_session_set_self_referential_pointers (struct tls_session
* session
) {
1482 session
->tls_auth
.packet_id
= &session
->tls_auth_pid
;
1486 * Initialize a TLS session. A TLS session normally has 2 key_state objects,
1487 * one for the current key, and one for the lame duck (i.e. retiring) key.
1490 tls_session_init (struct tls_multi
*multi
, struct tls_session
*session
)
1492 struct gc_arena gc
= gc_new ();
1494 dmsg (D_TLS_DEBUG
, "TLS: tls_session_init: entry");
1498 /* Set options data to point to parent's option structure */
1499 session
->opt
= &multi
->opt
;
1501 /* Randomize session # if it is 0 */
1502 while (!session_id_defined(&session
->session_id
))
1503 session_id_random (&session
->session_id
);
1505 /* Are we a TLS server or client? */
1506 ASSERT (session
->opt
->key_method
>= 1);
1507 if (session
->opt
->key_method
== 1)
1509 session
->initial_opcode
= session
->opt
->server
?
1510 P_CONTROL_HARD_RESET_SERVER_V1
: P_CONTROL_HARD_RESET_CLIENT_V1
;
1512 else /* session->opt->key_method >= 2 */
1514 session
->initial_opcode
= session
->opt
->server
?
1515 P_CONTROL_HARD_RESET_SERVER_V2
: P_CONTROL_HARD_RESET_CLIENT_V2
;
1518 /* Initialize control channel authentication parameters */
1519 session
->tls_auth
= session
->opt
->tls_auth
;
1521 /* Set session internal pointers (also called if session object is moved in memory) */
1522 tls_session_set_self_referential_pointers (session
);
1524 /* initialize packet ID replay window for --tls-auth */
1525 packet_id_init (session
->tls_auth
.packet_id
,
1526 session
->opt
->replay_window
,
1527 session
->opt
->replay_time
);
1529 /* load most recent packet-id to replay protect on --tls-auth */
1530 packet_id_persist_load_obj (session
->tls_auth
.pid_persist
, session
->tls_auth
.packet_id
);
1532 key_state_init (session
, &session
->key
[KS_PRIMARY
]);
1534 dmsg (D_TLS_DEBUG
, "TLS: tls_session_init: new session object, sid=%s",
1535 session_id_print (&session
->session_id
, &gc
));
1541 tls_session_free (struct tls_session
*session
, bool clear
)
1545 if (session
->tls_auth
.packet_id
)
1546 packet_id_free (session
->tls_auth
.packet_id
);
1548 for (i
= 0; i
< KS_SIZE
; ++i
)
1549 key_state_free (&session
->key
[i
], false);
1551 if (session
->common_name
)
1552 free (session
->common_name
);
1559 move_session (struct tls_multi
* multi
, int dest
, int src
, bool reinit_src
)
1561 msg (D_TLS_DEBUG_LOW
, "TLS: move_session: dest=%s src=%s reinit_src=%d",
1562 session_index_name(dest
),
1563 session_index_name(src
),
1565 ASSERT (src
!= dest
);
1566 ASSERT (src
>= 0 && src
< TM_SIZE
);
1567 ASSERT (dest
>= 0 && dest
< TM_SIZE
);
1568 tls_session_free (&multi
->session
[dest
], false);
1569 multi
->session
[dest
] = multi
->session
[src
];
1570 tls_session_set_self_referential_pointers (&multi
->session
[dest
]);
1573 tls_session_init (multi
, &multi
->session
[src
]);
1575 CLEAR (multi
->session
[src
]);
1577 dmsg (D_TLS_DEBUG
, "TLS: move_session: exit");
1581 reset_session (struct tls_multi
*multi
, struct tls_session
*session
)
1583 tls_session_free (session
, false);
1584 tls_session_init (multi
, session
);
1589 * Transmit a TLS reset on our untrusted channel.
1592 initiate_untrusted_session (struct tls_multi
*multi
, struct sockaddr_in
*to
)
1594 struct tls_session
*session
= &multi
->session
[TM_UNTRUSTED
];
1595 struct key_state
*ks
= &session
->key
[KS_PRIMARY
];
1597 reset_session (multi
, session
);
1598 ks
->remote_addr
= *to
;
1599 msg (D_TLS_DEBUG_LOW
, "TLS: initiate_untrusted_session: addr=%s", print_sockaddr (to
));
1604 * Used to determine in how many seconds we should be
1608 compute_earliest_wakeup (interval_t
*earliest
, interval_t seconds_from_now
) {
1609 if (seconds_from_now
< *earliest
)
1610 *earliest
= seconds_from_now
;
1616 * Return true if "lame duck" or retiring key has expired and can
1617 * no longer be used.
1620 lame_duck_must_die (const struct tls_session
* session
, interval_t
*wakeup
)
1622 const struct key_state
* lame
= &session
->key
[KS_LAME_DUCK
];
1623 if (lame
->state
>= S_INITIAL
)
1625 const time_t local_now
= now
;
1626 ASSERT (lame
->must_die
); /* a lame duck key must always have an expiration */
1627 if (local_now
< lame
->must_die
)
1629 compute_earliest_wakeup (wakeup
, lame
->must_die
- local_now
);
1635 else if (lame
->state
== S_ERROR
)
1642 * A tls_multi object fully encapsulates OpenVPN's TLS state.
1643 * See ssl.h for more comments.
1646 tls_multi_init (struct tls_options
*tls_options
)
1648 struct tls_multi
*ret
;
1650 ALLOC_OBJ_CLEAR (ret
, struct tls_multi
);
1652 /* get command line derived options */
1653 ret
->opt
= *tls_options
;
1655 /* set up pointer to HMAC object for TLS packet authentication */
1656 ret
->opt
.tls_auth
.key_ctx_bi
= &ret
->opt
.tls_auth_key
;
1658 /* set up list of keys to be scanned by data channel encrypt and decrypt routines */
1659 ASSERT (SIZE (ret
->key_scan
) == 3);
1660 ret
->key_scan
[0] = &ret
->session
[TM_ACTIVE
].key
[KS_PRIMARY
];
1661 ret
->key_scan
[1] = &ret
->session
[TM_ACTIVE
].key
[KS_LAME_DUCK
];
1662 ret
->key_scan
[2] = &ret
->session
[TM_LAME_DUCK
].key
[KS_LAME_DUCK
];
1668 * Finalize our computation of frame sizes.
1671 tls_multi_init_finalize (struct tls_multi
* multi
, const struct frame
* frame
)
1673 tls_init_control_channel_frame_parameters (frame
, &multi
->opt
.frame
);
1675 /* initialize the active and untrusted sessions */
1677 tls_session_init (multi
, &multi
->session
[TM_ACTIVE
]);
1679 if (!multi
->opt
.single_session
)
1680 tls_session_init (multi
, &multi
->session
[TM_UNTRUSTED
]);
1684 * Initialize and finalize a standalone tls-auth verification object.
1687 struct tls_auth_standalone
*
1688 tls_auth_standalone_init (struct tls_options
*tls_options
,
1689 struct gc_arena
*gc
)
1691 struct tls_auth_standalone
*tas
;
1693 ALLOC_OBJ_CLEAR_GC (tas
, struct tls_auth_standalone
, gc
);
1695 /* set up pointer to HMAC object for TLS packet authentication */
1696 tas
->tls_auth_key
= tls_options
->tls_auth_key
;
1697 tas
->tls_auth_options
.key_ctx_bi
= &tas
->tls_auth_key
;
1698 tas
->tls_auth_options
.flags
|= CO_PACKET_ID_LONG_FORM
;
1700 /* get initial frame parms, still need to finalize */
1701 tas
->frame
= tls_options
->frame
;
1707 tls_auth_standalone_finalize (struct tls_auth_standalone
*tas
,
1708 const struct frame
*frame
)
1710 tls_init_control_channel_frame_parameters (frame
, &tas
->frame
);
1714 * Set local and remote option compatibility strings.
1715 * Used to verify compatibility of local and remote option
1719 tls_multi_init_set_options (struct tls_multi
* multi
,
1724 /* initialize options string */
1725 multi
->opt
.local_options
= local
;
1726 multi
->opt
.remote_options
= remote
;
1731 tls_multi_free (struct tls_multi
*multi
, bool clear
)
1737 if (multi
->locked_cn
)
1738 free (multi
->locked_cn
);
1740 for (i
= 0; i
< TM_SIZE
; ++i
)
1741 tls_session_free (&multi
->session
[i
], false);
1750 * Move a packet authentication HMAC + related fields to or from the front
1751 * of the buffer so it can be processed by encrypt/decrypt.
1755 * Dependent on hmac size, opcode size, and session_id size.
1756 * Will assert if too small.
1758 #define SWAP_BUF_SIZE 256
1761 swap_hmac (struct buffer
*buf
, const struct crypto_options
*co
, bool incoming
)
1763 struct key_ctx
*ctx
;
1767 ctx
= (incoming
? &co
->key_ctx_bi
->decrypt
: &co
->key_ctx_bi
->encrypt
);
1771 /* hmac + packet_id (8 bytes) */
1772 const int hmac_size
= HMAC_size (ctx
->hmac
) + packet_id_size (true);
1774 /* opcode + session_id */
1775 const int osid_size
= 1 + SID_SIZE
;
1778 uint8_t *b
= BPTR (buf
);
1779 uint8_t buf1
[SWAP_BUF_SIZE
];
1780 uint8_t buf2
[SWAP_BUF_SIZE
];
1793 ASSERT (e1
<= SWAP_BUF_SIZE
&& e2
<= SWAP_BUF_SIZE
);
1795 if (buf
->len
>= e1
+ e2
)
1797 memcpy (buf1
, b
, e1
);
1798 memcpy (buf2
, b
+ e1
, e2
);
1799 memcpy (b
, buf2
, e2
);
1800 memcpy (b
+ e2
, buf1
, e1
);
1808 #undef SWAP_BUF_SIZE
1811 * Write a control channel authentication record.
1814 write_control_auth (struct tls_session
*session
,
1815 struct key_state
*ks
,
1817 struct sockaddr_in
*to_link_addr
,
1823 struct buffer null
= clear_buf ();
1825 ASSERT (addr_defined (&ks
->remote_addr
));
1826 ASSERT (reliable_ack_write
1827 (ks
->rec_ack
, buf
, &ks
->session_id_remote
, max_ack
, prepend_ack
));
1828 ASSERT (session_id_write_prepend (&session
->session_id
, buf
));
1829 ASSERT (header
= buf_prepend (buf
, 1));
1830 *header
= ks
->key_id
| (opcode
<< P_OPCODE_SHIFT
);
1831 if (session
->tls_auth
.key_ctx_bi
->encrypt
.hmac
)
1833 /* no encryption, only write hmac */
1834 openvpn_encrypt (buf
, null
, &session
->tls_auth
, NULL
);
1835 ASSERT (swap_hmac (buf
, &session
->tls_auth
, false));
1837 *to_link_addr
= ks
->remote_addr
;
1841 * Read a control channel authentication record.
1844 read_control_auth (struct buffer
*buf
,
1845 const struct crypto_options
*co
,
1846 const struct sockaddr_in
*from
)
1848 struct gc_arena gc
= gc_new ();
1850 if (co
->key_ctx_bi
->decrypt
.hmac
)
1852 struct buffer null
= clear_buf ();
1854 /* move the hmac record to the front of the packet */
1855 if (!swap_hmac (buf
, co
, true))
1858 "TLS Error: cannot locate HMAC in incoming packet from %s",
1859 print_sockaddr (from
, &gc
));
1864 /* authenticate only (no decrypt) and remove the hmac record
1865 from the head of the buffer */
1866 openvpn_decrypt (buf
, null
, co
, NULL
);
1870 "TLS Error: incoming packet authentication failed from %s",
1871 print_sockaddr (from
, &gc
));
1878 /* advance buffer pointer past opcode & session_id since our caller
1880 buf_advance (buf
, SID_SIZE
+ 1);
1887 * For debugging, print contents of key_source2 structure.
1891 key_source_print (const struct key_source
*k
,
1894 struct gc_arena gc
= gc_new ();
1896 VALGRIND_MAKE_READABLE ((void *)k
->pre_master
, sizeof (k
->pre_master
));
1897 VALGRIND_MAKE_READABLE ((void *)k
->random1
, sizeof (k
->random1
));
1898 VALGRIND_MAKE_READABLE ((void *)k
->random2
, sizeof (k
->random2
));
1900 dmsg (D_SHOW_KEY_SOURCE
,
1901 "%s pre_master: %s",
1903 format_hex (k
->pre_master
, sizeof (k
->pre_master
), 0, &gc
));
1904 dmsg (D_SHOW_KEY_SOURCE
,
1907 format_hex (k
->random1
, sizeof (k
->random1
), 0, &gc
));
1908 dmsg (D_SHOW_KEY_SOURCE
,
1911 format_hex (k
->random2
, sizeof (k
->random2
), 0, &gc
));
1917 key_source2_print (const struct key_source2
*k
)
1919 key_source_print (&k
->client
, "Client");
1920 key_source_print (&k
->server
, "Server");
1924 * Use the TLS PRF function for generating data channel keys.
1925 * This code is taken from the OpenSSL library.
1927 * TLS generates keys as such:
1929 * master_secret[48] = PRF(pre_master_secret[48], "master secret",
1930 * ClientHello.random[32] + ServerHello.random[32])
1932 * key_block[] = PRF(SecurityParameters.master_secret[48],
1934 * SecurityParameters.server_random[32] +
1935 * SecurityParameters.client_random[32]);
1939 * (1) key_block contains a full set of 4 keys.
1940 * (2) The pre-master secret is generated by the client.
1944 tls1_P_hash(const EVP_MD
*md
,
1947 const uint8_t *seed
,
1952 struct gc_arena gc
= gc_new ();
1957 uint8_t A1
[EVP_MAX_MD_SIZE
];
1958 unsigned int A1_len
;
1961 const int olen_orig
= olen
;
1962 const uint8_t *out_orig
= out
;
1965 dmsg (D_SHOW_KEY_SOURCE
, "tls1_P_hash sec: %s", format_hex (sec
, sec_len
, 0, &gc
));
1966 dmsg (D_SHOW_KEY_SOURCE
, "tls1_P_hash seed: %s", format_hex (seed
, seed_len
, 0, &gc
));
1968 chunk
=EVP_MD_size(md
);
1970 HMAC_CTX_init(&ctx
);
1971 HMAC_CTX_init(&ctx_tmp
);
1972 HMAC_Init_ex(&ctx
,sec
,sec_len
,md
, NULL
);
1973 HMAC_Init_ex(&ctx_tmp
,sec
,sec_len
,md
, NULL
);
1974 HMAC_Update(&ctx
,seed
,seed_len
);
1975 HMAC_Final(&ctx
,A1
,&A1_len
);
1980 HMAC_Init_ex(&ctx
,NULL
,0,NULL
,NULL
); /* re-init */
1981 HMAC_Init_ex(&ctx_tmp
,NULL
,0,NULL
,NULL
); /* re-init */
1982 HMAC_Update(&ctx
,A1
,A1_len
);
1983 HMAC_Update(&ctx_tmp
,A1
,A1_len
);
1984 HMAC_Update(&ctx
,seed
,seed_len
);
1988 HMAC_Final(&ctx
,out
,&j
);
1991 HMAC_Final(&ctx_tmp
,A1
,&A1_len
); /* calc the next A1 value */
1995 HMAC_Final(&ctx
,A1
,&A1_len
);
1996 memcpy(out
,A1
,olen
);
2000 HMAC_CTX_cleanup(&ctx
);
2001 HMAC_CTX_cleanup(&ctx_tmp
);
2004 dmsg (D_SHOW_KEY_SOURCE
, "tls1_P_hash out: %s", format_hex (out_orig
, olen_orig
, 0, &gc
));
2009 tls1_PRF(uint8_t *label
,
2016 struct gc_arena gc
= gc_new ();
2017 const EVP_MD
*md5
= EVP_md5();
2018 const EVP_MD
*sha1
= EVP_sha1();
2020 const uint8_t *S1
,*S2
;
2023 out2
= (uint8_t *) gc_malloc (olen
, false, &gc
);
2028 len
+=(slen
&1); /* add for odd, make longer */
2031 tls1_P_hash(md5
,S1
,len
,label
,label_len
,out1
,olen
);
2032 tls1_P_hash(sha1
,S2
,len
,label
,label_len
,out2
,olen
);
2034 for (i
=0; i
<olen
; i
++)
2037 memset (out2
, 0, olen
);
2039 dmsg (D_SHOW_KEY_SOURCE
, "tls1_PRF out[%d]: %s", olen
, format_hex (out1
, olen
, 0, &gc
));
2045 openvpn_PRF (const uint8_t *secret
,
2048 const uint8_t *client_seed
,
2049 int client_seed_len
,
2050 const uint8_t *server_seed
,
2051 int server_seed_len
,
2052 const struct session_id
*client_sid
,
2053 const struct session_id
*server_sid
,
2057 /* concatenate seed components */
2059 struct buffer seed
= alloc_buf (strlen (label
)
2064 ASSERT (buf_write (&seed
, label
, strlen (label
)));
2065 ASSERT (buf_write (&seed
, client_seed
, client_seed_len
));
2066 ASSERT (buf_write (&seed
, server_seed
, server_seed_len
));
2069 ASSERT (buf_write (&seed
, client_sid
->id
, SID_SIZE
));
2071 ASSERT (buf_write (&seed
, server_sid
->id
, SID_SIZE
));
2074 tls1_PRF (BPTR(&seed
), BLEN(&seed
), secret
, secret_len
, output
, output_len
);
2079 VALGRIND_MAKE_READABLE ((void *)output
, output_len
);
2083 * Using source entropy from local and remote hosts, mix into
2087 generate_key_expansion (struct key_ctx_bi
*key
,
2088 const struct key_type
*key_type
,
2089 const struct key_source2
*key_src
,
2090 const struct session_id
*client_sid
,
2091 const struct session_id
*server_sid
,
2102 /* debugging print of source key material */
2103 key_source2_print (key_src
);
2105 /* compute master secret */
2106 openvpn_PRF (key_src
->client
.pre_master
,
2107 sizeof(key_src
->client
.pre_master
),
2108 KEY_EXPANSION_ID
" master secret",
2109 key_src
->client
.random1
,
2110 sizeof(key_src
->client
.random1
),
2111 key_src
->server
.random1
,
2112 sizeof(key_src
->server
.random1
),
2118 /* compute key expansion */
2119 openvpn_PRF (master
,
2121 KEY_EXPANSION_ID
" key expansion",
2122 key_src
->client
.random2
,
2123 sizeof(key_src
->client
.random2
),
2124 key_src
->server
.random2
,
2125 sizeof(key_src
->server
.random2
),
2128 (uint8_t*)key2
.keys
,
2133 key2_print (&key2
, key_type
, "Master Encrypt", "Master Decrypt");
2135 /* check for weak keys */
2136 for (i
= 0; i
< 2; ++i
)
2138 fixup_key (&key2
.keys
[i
], key_type
);
2139 if (!check_key (&key2
.keys
[i
], key_type
))
2141 msg (D_TLS_ERRORS
, "TLS Error: Bad dynamic key generated");
2146 /* Initialize OpenSSL key contexts */
2148 ASSERT (server
== true || server
== false);
2150 init_key_ctx (&key
->encrypt
,
2151 &key2
.keys
[(int)server
],
2154 "Data Channel Encrypt");
2156 init_key_ctx (&key
->decrypt
,
2157 &key2
.keys
[1-(int)server
],
2160 "Data Channel Decrypt");
2172 random_bytes_to_buf (struct buffer
*buf
,
2176 if (!RAND_bytes (out
, outlen
))
2177 msg (M_FATAL
, "ERROR: Random number generator cannot obtain entropy for key generation [SSL]");
2178 if (!buf_write (buf
, out
, outlen
))
2184 key_source2_randomize_write (struct key_source2
*k2
,
2188 struct key_source
*k
= &k2
->client
;
2196 if (!random_bytes_to_buf (buf
, k
->pre_master
, sizeof (k
->pre_master
)))
2200 if (!random_bytes_to_buf (buf
, k
->random1
, sizeof (k
->random1
)))
2202 if (!random_bytes_to_buf (buf
, k
->random2
, sizeof (k
->random2
)))
2209 key_source2_read (struct key_source2
*k2
,
2213 struct key_source
*k
= &k2
->client
;
2222 if (!buf_read (buf
, k
->pre_master
, sizeof (k
->pre_master
)))
2226 if (!buf_read (buf
, k
->random1
, sizeof (k
->random1
)))
2228 if (!buf_read (buf
, k
->random2
, sizeof (k
->random2
)))
2235 * Macros for key_state_soft_reset & tls_process
2237 #define ks (&session->key[KS_PRIMARY]) /* primary key */
2238 #define ks_lame (&session->key[KS_LAME_DUCK]) /* retiring key */
2240 /* true if no in/out acknowledgements pending */
2242 (reliable_empty(ks->send_reliable) && reliable_ack_empty (ks->rec_ack))
2245 * Move the active key to the lame duck key and reinitialize the
2249 key_state_soft_reset (struct tls_session
*session
)
2251 ks
->must_die
= now
+ session
->opt
->transition_window
; /* remaining lifetime of old key */
2252 key_state_free (ks_lame
, false);
2255 key_state_init (session
, ks
);
2256 ks
->session_id_remote
= ks_lame
->session_id_remote
;
2257 ks
->remote_addr
= ks_lame
->remote_addr
;
2261 * Read/write strings from/to a struct buffer with a u16 length prefix.
2265 write_string (struct buffer
*buf
, const char *str
, const int maxlen
)
2267 const int len
= strlen (str
) + 1;
2268 if (len
< 1 || (maxlen
>= 0 && len
> maxlen
))
2270 if (!buf_write_u16 (buf
, len
))
2272 if (!buf_write (buf
, str
, len
))
2278 read_string (struct buffer
*buf
, char *str
, const unsigned int capacity
)
2280 const int len
= buf_read_u16 (buf
);
2281 if (len
< 1 || len
> (int)capacity
)
2283 if (!buf_read (buf
, str
, len
))
2290 * Authenticate a client using username/password.
2293 * If you want to add new authentication methods,
2294 * this is the place to start.
2298 verify_user_pass_script (struct tls_session
*session
, const struct user_pass
*up
)
2300 struct gc_arena gc
= gc_new ();
2301 struct buffer cmd
= alloc_buf_gc (256, &gc
);
2302 const char *tmp_file
= "";
2306 /* Is username defined? */
2307 if (strlen (up
->username
))
2309 /* Set environmental variables prior to calling script */
2310 setenv_str (session
->opt
->es
, "script_type", "user-pass-verify");
2312 if (session
->opt
->auth_user_pass_verify_script_via_file
)
2314 struct status_output
*so
;
2316 tmp_file
= create_temp_filename (session
->opt
->tmp_dir
, &gc
);
2317 so
= status_open (tmp_file
, 0, -1, NULL
, STATUS_OUTPUT_WRITE
);
2318 status_printf (so
, "%s", up
->username
);
2319 status_printf (so
, "%s", up
->password
);
2320 if (!status_close (so
))
2322 msg (D_TLS_ERRORS
, "TLS Auth Error: could not write username/password to file: %s",
2329 setenv_str (session
->opt
->es
, "username", up
->username
);
2330 setenv_str (session
->opt
->es
, "password", up
->password
);
2333 /* setenv incoming cert common name for script */
2334 setenv_str (session
->opt
->es
, "common_name", session
->common_name
);
2336 /* setenv client real IP address */
2337 setenv_untrusted (session
);
2339 /* format command line */
2340 buf_printf (&cmd
, "%s %s", session
->opt
->auth_user_pass_verify_script
, tmp_file
);
2343 retval
= openvpn_system (BSTR (&cmd
), session
->opt
->es
, S_SCRIPT
);
2345 /* test return status of command */
2346 if (system_ok (retval
))
2348 else if (!system_executed (retval
))
2349 msg (D_TLS_ERRORS
, "TLS Auth Error: user-pass-verify script failed to execute: %s", BSTR (&cmd
));
2351 if (!session
->opt
->auth_user_pass_verify_script_via_file
)
2352 setenv_del (session
->opt
->es
, "password");
2356 msg (D_TLS_ERRORS
, "TLS Auth Error: peer provided a blank username");
2360 if (strlen (tmp_file
) > 0)
2361 delete_file (tmp_file
);
2368 verify_user_pass_plugin (struct tls_session
*session
, const struct user_pass
*up
, const char *raw_username
)
2373 /* Is username defined? */
2374 if (strlen (up
->username
))
2376 /* set username/password in private env space */
2377 setenv_str (session
->opt
->es
, "username", raw_username
);
2378 setenv_str (session
->opt
->es
, "password", up
->password
);
2380 /* setenv incoming cert common name for script */
2381 setenv_str (session
->opt
->es
, "common_name", session
->common_name
);
2383 /* setenv client real IP address */
2384 setenv_untrusted (session
);
2387 retval
= plugin_call (session
->opt
->plugins
, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY
, NULL
, session
->opt
->es
);
2392 setenv_del (session
->opt
->es
, "password");
2393 setenv_str (session
->opt
->es
, "username", up
->username
);
2397 msg (D_TLS_ERRORS
, "TLS Auth Error: peer provided a blank username");
2404 * Handle the reading and writing of key data to and from
2405 * the TLS control channel (cleartext).
2409 key_method_1_write (struct buffer
*buf
, struct tls_session
*session
)
2413 ASSERT (session
->opt
->key_method
== 1);
2414 ASSERT (buf_init (buf
, 0));
2416 generate_key_random (&key
, &session
->opt
->key_type
);
2417 if (!check_key (&key
, &session
->opt
->key_type
))
2419 msg (D_TLS_ERRORS
, "TLS Error: Bad encrypting key generated");
2423 if (!write_key (&key
, &session
->opt
->key_type
, buf
))
2425 msg (D_TLS_ERRORS
, "TLS Error: write_key failed");
2429 init_key_ctx (&ks
->key
.encrypt
, &key
, &session
->opt
->key_type
,
2430 DO_ENCRYPT
, "Data Channel Encrypt");
2433 /* send local options string */
2435 const char *local_options
= local_options_string (session
);
2436 const int optlen
= strlen (local_options
) + 1;
2437 if (!buf_write (buf
, local_options
, optlen
))
2439 msg (D_TLS_ERRORS
, "TLS Error: KM1 write options failed");
2448 key_method_2_write (struct buffer
*buf
, struct tls_session
*session
)
2450 ASSERT (session
->opt
->key_method
== 2);
2451 ASSERT (buf_init (buf
, 0));
2453 /* write a uint32 0 */
2454 if (!buf_write_u32 (buf
, 0))
2457 /* write key_method + flags */
2458 if (!buf_write_u8 (buf
, (session
->opt
->key_method
& KEY_METHOD_MASK
)))
2461 /* write key source material */
2462 if (!key_source2_randomize_write (ks
->key_src
, buf
, session
->opt
->server
))
2465 /* write options string */
2467 if (!write_string (buf
, local_options_string (session
), TLS_OPTIONS_LEN
))
2471 /* write username/password if specified */
2472 if (auth_user_pass_enabled
)
2474 auth_user_pass_setup (NULL
);
2475 if (!write_string (buf
, auth_user_pass
.username
, -1))
2477 if (!write_string (buf
, auth_user_pass
.password
, -1))
2479 purge_user_pass (&auth_user_pass
, false);
2483 * generate tunnel keys if server
2485 if (session
->opt
->server
)
2487 if (ks
->authenticated
)
2489 if (!generate_key_expansion (&ks
->key
,
2490 &session
->opt
->key_type
,
2492 &ks
->session_id_remote
,
2493 &session
->session_id
,
2496 msg (D_TLS_ERRORS
, "TLS Error: server generate_key_expansion failed");
2501 CLEAR (*ks
->key_src
);
2507 msg (D_TLS_ERRORS
, "TLS Error: Key Method #2 write failed");
2508 CLEAR (*ks
->key_src
);
2513 key_method_1_read (struct buffer
*buf
, struct tls_session
*session
)
2518 ASSERT (session
->opt
->key_method
== 1);
2520 if (!session
->verified
)
2523 "TLS Error: Certificate verification failed (key-method 1)");
2527 status
= read_key (&key
, &session
->opt
->key_type
, buf
);
2531 "TLS Error: Error reading data channel key from plaintext buffer");
2535 if (!check_key (&key
, &session
->opt
->key_type
))
2537 msg (D_TLS_ERRORS
, "TLS Error: Bad decrypting key received from peer");
2543 msg (D_TLS_ERRORS
, "TLS Error: Missing options string");
2548 /* compare received remote options string
2549 with our locally computed options string */
2550 if (!session
->opt
->disable_occ
&&
2551 !options_cmp_equal_safe ((char *) BPTR (buf
), session
->opt
->remote_options
, buf
->len
))
2553 options_warning_safe ((char *) BPTR (buf
), session
->opt
->remote_options
, buf
->len
);
2559 init_key_ctx (&ks
->key
.decrypt
, &key
, &session
->opt
->key_type
,
2560 DO_DECRYPT
, "Data Channel Decrypt");
2562 ks
->authenticated
= true;
2572 key_method_2_read (struct buffer
*buf
, struct tls_multi
*multi
, struct tls_session
*session
)
2574 struct gc_arena gc
= gc_new ();
2575 int key_method_flags
;
2577 struct user_pass
*up
;
2579 ASSERT (session
->opt
->key_method
== 2);
2581 /* allocate temporary objects */
2582 ALLOC_ARRAY_CLEAR_GC (options
, char, TLS_OPTIONS_LEN
, &gc
);
2584 /* discard leading uint32 */
2585 ASSERT (buf_advance (buf
, 4));
2587 /* get key method */
2588 key_method_flags
= buf_read_u8 (buf
);
2589 if ((key_method_flags
& KEY_METHOD_MASK
) != 2)
2592 "TLS ERROR: Unknown key_method/flags=%d received from remote host",
2597 /* get key source material (not actual keys yet) */
2598 if (!key_source2_read (ks
->key_src
, buf
, session
->opt
->server
))
2600 msg (D_TLS_ERRORS
, "TLS Error: Error reading remote data channel key source entropy from plaintext buffer");
2605 if (!read_string (buf
, options
, TLS_OPTIONS_LEN
))
2607 msg (D_TLS_ERRORS
, "TLS Error: Failed to read required OCC options string");
2611 /* should we check username/password? */
2612 ks
->authenticated
= false;
2613 if (session
->opt
->auth_user_pass_verify_script
2614 || plugin_defined (session
->opt
->plugins
, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY
))
2620 /* get username/password from plaintext buffer */
2621 ALLOC_OBJ_CLEAR_GC (up
, struct user_pass
, &gc
);
2622 if (!read_string (buf
, up
->username
, USER_PASS_LEN
)
2623 || !read_string (buf
, up
->password
, USER_PASS_LEN
))
2625 msg (D_TLS_ERRORS
, "TLS Error: Auth Username/Password was not provided by peer");
2630 /* preserve raw username before string_mod remapping, for plugins */
2631 ALLOC_ARRAY_CLEAR_GC (raw_username
, char, USER_PASS_LEN
, &gc
);
2632 strcpy (raw_username
, up
->username
);
2633 string_mod (raw_username
, CC_PRINT
, CC_CRLF
, '_');
2635 /* enforce character class restrictions in username/password */
2636 string_mod (up
->username
, COMMON_NAME_CHAR_CLASS
, 0, '_');
2637 string_mod (up
->password
, CC_PRINT
, CC_CRLF
, '_');
2639 /* call plugin(s) and/or script */
2640 if (plugin_defined (session
->opt
->plugins
, OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY
))
2641 s1
= verify_user_pass_plugin (session
, up
, raw_username
);
2642 if (session
->opt
->auth_user_pass_verify_script
)
2643 s2
= verify_user_pass_script (session
, up
);
2645 /* auth succeeded? */
2648 ks
->authenticated
= true;
2649 if (session
->opt
->username_as_common_name
)
2650 set_common_name (session
, up
->username
);
2651 msg (D_HANDSHAKE
, "TLS: Username/Password authentication succeeded for username '%s' %s",
2653 session
->opt
->username_as_common_name
? "[CN SET]" : "");
2657 msg (D_TLS_ERRORS
, "TLS Auth Error: Auth Username/Password verification failed for peer");
2664 if (!session
->verified
)
2667 "TLS Error: Certificate verification failed (key-method 2)");
2670 ks
->authenticated
= true;
2673 /* While it shouldn't really happen, don't allow the common name to be NULL */
2674 if (!session
->common_name
)
2675 set_common_name (session
, "");
2677 /* Don't allow the CN to change once it's been locked */
2678 if (ks
->authenticated
&& multi
->locked_cn
)
2680 const char *cn
= session
->common_name
;
2681 if (cn
&& strcmp (cn
, multi
->locked_cn
))
2683 msg (D_TLS_ERRORS
, "TLS Auth Error: TLS object CN attempted to change from '%s' to '%s' -- tunnel disabled",
2687 /* change the common name back to its original value and disable the tunnel */
2688 set_common_name (session
, multi
->locked_cn
);
2689 tls_deauthenticate (multi
);
2693 /* verify --client-config-dir based authentication */
2694 if (ks
->authenticated
&& session
->opt
->client_config_dir_exclusive
)
2696 const char *cn
= session
->common_name
;
2697 const char *path
= gen_path (session
->opt
->client_config_dir_exclusive
, cn
, &gc
);
2698 if (!cn
|| !strcmp (cn
, CCD_DEFAULT
) || !test_file (path
))
2700 ks
->authenticated
= false;
2701 msg (D_TLS_ERRORS
, "TLS Auth Error: --client-config-dir authentication failed for common name '%s' file='%s'",
2702 session
->common_name
,
2703 path
? path
: "UNDEF");
2708 /* check options consistency */
2709 if (!session
->opt
->disable_occ
&&
2710 !options_cmp_equal (options
, session
->opt
->remote_options
))
2712 options_warning (options
, session
->opt
->remote_options
);
2719 * generate tunnel keys if client
2721 if (!session
->opt
->server
)
2723 if (!generate_key_expansion (&ks
->key
,
2724 &session
->opt
->key_type
,
2726 &session
->session_id
,
2727 &ks
->session_id_remote
,
2730 msg (D_TLS_ERRORS
, "TLS Error: client generate_key_expansion failed");
2734 CLEAR (*ks
->key_src
);
2741 CLEAR (*ks
->key_src
);
2748 * This is the primary routine for processing TLS stuff inside the
2749 * the main event loop. When this routine exits
2750 * with non-error status, it will set *wakeup to the number of seconds
2751 * when it wants to be called again.
2753 * Return value is true if we have placed a packet in *to_link which we
2754 * want to send to our peer.
2757 tls_process (struct tls_multi
*multi
,
2758 struct tls_session
*session
,
2759 struct buffer
*to_link
,
2760 struct sockaddr_in
*to_link_addr
,
2761 struct link_socket_info
*to_link_socket_info
,
2764 struct gc_arena gc
= gc_new ();
2766 bool state_change
= false;
2767 bool active
= false;
2769 /* Make sure we were initialized and that we're not in an error state */
2770 ASSERT (ks
->state
!= S_UNDEF
);
2771 ASSERT (ks
->state
!= S_ERROR
);
2772 ASSERT (session_id_defined (&session
->session_id
));
2774 /* Should we trigger a soft reset? -- new key, keeps old key for a while */
2775 if (ks
->state
>= S_ACTIVE
&&
2776 ((session
->opt
->renegotiate_seconds
2777 && now
>= ks
->established
+ session
->opt
->renegotiate_seconds
)
2778 || (session
->opt
->renegotiate_bytes
2779 && ks
->n_bytes
>= session
->opt
->renegotiate_bytes
)
2780 || (session
->opt
->renegotiate_packets
2781 && ks
->n_packets
>= session
->opt
->renegotiate_packets
)
2782 || (packet_id_close_to_wrapping (&ks
->packet_id
.send
))))
2784 msg (D_TLS_DEBUG_LOW
, "TLS: soft reset sec=%d bytes=%d/%d pkts=%d/%d",
2785 (int)(ks
->established
+ session
->opt
->renegotiate_seconds
- now
),
2786 ks
->n_bytes
, session
->opt
->renegotiate_bytes
,
2787 ks
->n_packets
, session
->opt
->renegotiate_packets
);
2788 key_state_soft_reset (session
);
2791 /* Kill lame duck key transition_window seconds after primary key negotiation */
2792 if (lame_duck_must_die (session
, wakeup
)) {
2793 key_state_free (ks_lame
, true);
2794 msg (D_TLS_DEBUG_LOW
, "TLS: tls_process: killed expiring key");
2797 /*mutex_cycle (multi->mutex);*/
2803 dmsg (D_TLS_DEBUG
, "TLS: tls_process: chg=%d ks=%s lame=%s to_link->len=%d wakeup=%d",
2805 state_name (ks
->state
),
2806 state_name (ks_lame
->state
),
2810 state_change
= false;
2813 * TLS activity is finished once we get to S_ACTIVE,
2814 * though we will still process acknowledgements.
2816 * CHANGED with 2.0 -> now we may send tunnel configuration
2817 * info over the control channel.
2821 /* Initial handshake */
2822 if (ks
->state
== S_INITIAL
)
2824 buf
= reliable_get_buf_output_sequenced (ks
->send_reliable
);
2827 ks
->must_negotiate
= now
+ session
->opt
->handshake_window
;
2830 reliable_mark_active_outgoing (ks
->send_reliable
, buf
, ks
->initial_opcode
);
2833 ks
->state
= S_PRE_START
;
2834 state_change
= true;
2835 dmsg (D_TLS_DEBUG
, "TLS: Initial Handshake, sid=%s",
2836 session_id_print (&session
->session_id
, &gc
));
2838 #ifdef ENABLE_MANAGEMENT
2839 if (management
&& ks
->initial_opcode
!= P_CONTROL_SOFT_RESET_V1
)
2841 management_set_state (management
,
2850 /* Are we timed out on receive? */
2851 if (now
>= ks
->must_negotiate
)
2853 if (ks
->state
< S_ACTIVE
)
2856 "TLS Error: TLS key negotiation failed to occur within %d seconds (check your network connectivity)",
2857 session
->opt
->handshake_window
);
2860 else /* assume that ks->state == S_ACTIVE */
2862 dmsg (D_TLS_DEBUG_MED
, "STATE S_NORMAL");
2863 ks
->state
= S_NORMAL
;
2864 ks
->must_negotiate
= 0;
2868 /* Wait for Initial Handshake ACK */
2869 if (ks
->state
== S_PRE_START
&& FULL_SYNC
)
2871 ks
->state
= S_START
;
2872 state_change
= true;
2873 dmsg (D_TLS_DEBUG_MED
, "STATE S_START");
2877 if (((ks
->state
== S_GOT_KEY
&& !session
->opt
->server
) ||
2878 (ks
->state
== S_SENT_KEY
&& session
->opt
->server
)))
2882 ks
->established
= now
;
2883 dmsg (D_TLS_DEBUG_MED
, "STATE S_ACTIVE");
2884 if (check_debug_level (D_HANDSHAKE
))
2885 print_details (ks
->ssl
, "Control Channel:");
2886 state_change
= true;
2887 ks
->state
= S_ACTIVE
;
2890 /* Set outgoing address for data channel packets */
2891 link_socket_set_outgoing_addr (NULL
, to_link_socket_info
, &ks
->remote_addr
, session
->common_name
, session
->opt
->es
);
2893 #ifdef MEASURE_TLS_HANDSHAKE_STATS
2894 show_tls_performance_stats();
2899 /* Reliable buffer to outgoing TCP/UDP (send up to CONTROL_SEND_ACK_MAX ACKs
2900 for previously received packets) */
2901 if (!to_link
->len
&& reliable_can_send (ks
->send_reliable
))
2906 buf
= reliable_send (ks
->send_reliable
, &opcode
);
2911 write_control_auth (session
, ks
, &b
, to_link_addr
, opcode
,
2912 CONTROL_SEND_ACK_MAX
, true);
2915 state_change
= true;
2916 dmsg (D_TLS_DEBUG
, "Reliable -> TCP/UDP");
2920 #ifndef TLS_AGGREGATE_ACK
2921 /* Send 1 or more ACKs (each received control packet gets one ACK) */
2922 if (!to_link
->len
&& !reliable_ack_empty (ks
->rec_ack
))
2924 buf
= &ks
->ack_write_buf
;
2925 ASSERT (buf_init (buf
, FRAME_HEADROOM (&multi
->opt
.frame
)));
2926 write_control_auth (session
, ks
, buf
, to_link_addr
, P_ACK_V1
,
2927 RELIABLE_ACK_SIZE
, false);
2930 state_change
= true;
2931 dmsg (D_TLS_DEBUG
, "Dedicated ACK -> TCP/UDP");
2936 /* Write incoming ciphertext to TLS object */
2937 buf
= reliable_get_buf_sequenced (ks
->rec_reliable
);
2943 status
= key_state_write_ciphertext (multi
, ks
, buf
);
2947 "TLS Error: Incoming Ciphertext -> TLS object write error");
2957 reliable_mark_deleted (ks
->rec_reliable
, buf
, true);
2958 state_change
= true;
2959 dmsg (D_TLS_DEBUG
, "Incoming Ciphertext -> TLS");
2963 /* Read incoming plaintext from TLS object */
2964 buf
= &ks
->plaintext_read_buf
;
2969 ASSERT (buf_init (buf
, 0));
2970 status
= key_state_read_plaintext (multi
, ks
, buf
, PLAINTEXT_BUFFER_SIZE
);
2974 msg (D_TLS_ERRORS
, "TLS Error: TLS object -> incoming plaintext read error");
2979 state_change
= true;
2980 dmsg (D_TLS_DEBUG
, "TLS -> Incoming Plaintext");
2982 #if 0 /* show null plaintext reads */
2984 msg (M_INFO
, "TLS plaintext read -> NULL return");
2989 buf
= &ks
->plaintext_write_buf
;
2990 if (!buf
->len
&& ((ks
->state
== S_START
&& !session
->opt
->server
) ||
2991 (ks
->state
== S_GOT_KEY
&& session
->opt
->server
)))
2993 if (session
->opt
->key_method
== 1)
2995 if (!key_method_1_write (buf
, session
))
2998 else if (session
->opt
->key_method
== 2)
3000 if (!key_method_2_write (buf
, session
))
3008 state_change
= true;
3009 dmsg (D_TLS_DEBUG_MED
, "STATE S_SENT_KEY");
3010 ks
->state
= S_SENT_KEY
;
3014 buf
= &ks
->plaintext_read_buf
;
3016 && ((ks
->state
== S_SENT_KEY
&& !session
->opt
->server
)
3017 || (ks
->state
== S_START
&& session
->opt
->server
)))
3019 if (session
->opt
->key_method
== 1)
3021 if (!key_method_1_read (buf
, session
))
3024 else if (session
->opt
->key_method
== 2)
3026 if (!key_method_2_read (buf
, multi
, session
))
3034 state_change
= true;
3035 dmsg (D_TLS_DEBUG_MED
, "STATE S_GOT_KEY");
3036 ks
->state
= S_GOT_KEY
;
3039 /* Write outgoing plaintext to TLS object */
3040 buf
= &ks
->plaintext_write_buf
;
3043 int status
= key_state_write_plaintext (multi
, ks
, buf
);
3047 "TLS ERROR: Outgoing Plaintext -> TLS object write error");
3052 state_change
= true;
3053 dmsg (D_TLS_DEBUG
, "Outgoing Plaintext -> TLS");
3057 /* Outgoing Ciphertext to reliable buffer */
3058 if (ks
->state
>= S_START
)
3060 buf
= reliable_get_buf_output_sequenced (ks
->send_reliable
);
3063 int status
= key_state_read_ciphertext (multi
, ks
, buf
, PAYLOAD_SIZE_DYNAMIC (&multi
->opt
.frame
));
3067 "TLS Error: Ciphertext -> reliable TCP/UDP transport read error");
3072 reliable_mark_active_outgoing (ks
->send_reliable
, buf
, P_CONTROL_V1
);
3074 state_change
= true;
3075 dmsg (D_TLS_DEBUG
, "Outgoing Ciphertext -> Reliable");
3080 /*mutex_cycle (multi->mutex);*/
3082 while (state_change
);
3086 #ifdef TLS_AGGREGATE_ACK
3087 /* Send 1 or more ACKs (each received control packet gets one ACK) */
3088 if (!to_link
->len
&& !reliable_ack_empty (ks
->rec_ack
))
3090 buf
= &ks
->ack_write_buf
;
3091 ASSERT (buf_init (buf
, FRAME_HEADROOM (&multi
->opt
.frame
)));
3092 write_control_auth (session
, ks
, buf
, to_link_addr
, P_ACK_V1
,
3093 RELIABLE_ACK_SIZE
, false);
3096 state_change
= true;
3097 dmsg (D_TLS_DEBUG
, "Dedicated ACK -> TCP/UDP");
3101 /* When should we wake up again? */
3103 if (ks
->state
>= S_INITIAL
)
3105 compute_earliest_wakeup (wakeup
,
3106 reliable_send_timeout (ks
->send_reliable
));
3108 if (ks
->must_negotiate
)
3109 compute_earliest_wakeup (wakeup
, ks
->must_negotiate
- now
);
3112 if (ks
->established
&& session
->opt
->renegotiate_seconds
)
3113 compute_earliest_wakeup (wakeup
,
3114 ks
->established
+ session
->opt
->renegotiate_seconds
- now
);
3116 /* prevent event-loop spinning by setting minimum wakeup of 1 second */
3121 /* if we had something to send to remote, but to_link was busy,
3122 let caller know we need to be called again soon */
3126 dmsg (D_TLS_DEBUG
, "TLS: tls_process: timeout set to %d", *wakeup
);
3134 ks
->state
= S_ERROR
;
3135 msg (D_TLS_ERRORS
, "TLS Error: TLS handshake failed");
3145 * Called by the top-level event loop.
3147 * Basically decides if we should call tls_process for
3148 * the active or untrusted sessions.
3152 tls_multi_process (struct tls_multi
*multi
,
3153 struct buffer
*to_link
,
3154 struct sockaddr_in
*to_link_addr
,
3155 struct link_socket_info
*to_link_socket_info
,
3158 struct gc_arena gc
= gc_new ();
3160 bool active
= false;
3163 perf_push (PERF_TLS_MULTI_PROCESS
);
3168 * Process each session object having state of S_INITIAL or greater,
3169 * and which has a defined remote IP addr.
3172 for (i
= 0; i
< TM_SIZE
; ++i
)
3174 struct tls_session
*session
= &multi
->session
[i
];
3175 struct key_state
*ks
= &session
->key
[KS_PRIMARY
];
3176 struct key_state
*ks_lame
= &session
->key
[KS_LAME_DUCK
];
3178 /* set initial remote address */
3179 if (i
== TM_ACTIVE
&& ks
->state
== S_INITIAL
&&
3180 addr_defined (&to_link_socket_info
->lsa
->actual
))
3181 ks
->remote_addr
= to_link_socket_info
->lsa
->actual
;
3184 "TLS: tls_multi_process: i=%d state=%s, mysid=%s, stored-sid=%s, stored-ip=%s",
3186 state_name (ks
->state
),
3187 session_id_print (&session
->session_id
, &gc
),
3188 session_id_print (&ks
->session_id_remote
, &gc
),
3189 print_sockaddr (&ks
->remote_addr
, &gc
));
3191 if (ks
->state
>= S_INITIAL
&& addr_defined (&ks
->remote_addr
))
3195 if (tls_process (multi
, session
, to_link
, to_link_addr
,
3196 to_link_socket_info
, wakeup
))
3200 * If tls_process hits an error:
3201 * (1) If the session has an unexpired lame duck key, preserve it.
3202 * (2) Reinitialize the session.
3203 * (3) Increment soft error count
3205 if (ks
->state
== S_ERROR
)
3207 ++multi
->n_soft_errors
;
3213 && ks_lame
->state
>= S_ACTIVE
3214 && !multi
->opt
.single_session
)
3215 move_session (multi
, TM_LAME_DUCK
, TM_ACTIVE
, true);
3217 reset_session (multi
, session
);
3220 /*mutex_cycle (multi->mutex);*/
3226 * If lame duck session expires, kill it.
3228 if (lame_duck_must_die (&multi
->session
[TM_LAME_DUCK
], wakeup
)) {
3229 tls_session_free (&multi
->session
[TM_LAME_DUCK
], true);
3230 msg (D_TLS_DEBUG_LOW
, "TLS: tls_multi_process: killed expiring key");
3234 * If untrusted session achieves TLS authentication,
3235 * move it to active session, usurping any prior session.
3237 * A semi-trusted session is one in which the certificate authentication
3238 * succeeded (if cert verification is enabled) but the username/password
3239 * verification failed. A semi-trusted session can forward data on the
3240 * TLS control channel but not on the tunnel channel.
3242 if (DECRYPT_KEY_ENABLED (multi
, &multi
->session
[TM_UNTRUSTED
].key
[KS_PRIMARY
])) {
3243 move_session (multi
, TM_ACTIVE
, TM_UNTRUSTED
, true);
3244 msg (D_TLS_DEBUG_LOW
, "TLS: tls_multi_process: untrusted session promoted to %strusted",
3245 tls_authenticated (multi
) ? "" : "semi-");
3249 * A hard error means that TM_ACTIVE hit an S_ERROR state and that no
3250 * other key state objects are S_ACTIVE or higher.
3254 for (i
= 0; i
< (int) SIZE (multi
->key_scan
); ++i
)
3256 if (multi
->key_scan
[i
]->state
>= S_ACTIVE
)
3259 ++multi
->n_hard_errors
;
3264 /* DEBUGGING -- flood peer with repeating connection attempts */
3266 const int throw_level
= GREMLIN_CONNECTION_FLOOD_LEVEL (multi
->opt
.gremlin
);
3269 for (i
= 0; i
< (int) SIZE (multi
->key_scan
); ++i
)
3271 if (multi
->key_scan
[i
]->state
>= throw_level
)
3273 ++multi
->n_hard_errors
;
3274 ++multi
->n_soft_errors
;
3287 * Pre and post-process the encryption & decryption buffers in order
3288 * to implement a multiplexed TLS channel over the TCP/UDP port.
3293 * When we are in TLS mode, this is the first routine which sees
3294 * an incoming packet.
3296 * If it's a data packet, we set opt so that our caller can
3297 * decrypt it. We also give our caller the appropriate decryption key.
3299 * If it's a control packet, we authenticate it and process it,
3300 * possibly creating a new tls_session if it represents the
3301 * first packet of a new session. For control packets, we will
3302 * also zero the size of *buf so that our caller ignores the
3303 * packet on our return.
3305 * Note that openvpn only allows one active session at a time,
3306 * so a new session (once authenticated) will always usurp
3309 * Return true if input was an authenticated control channel
3312 * If we are running in TLS thread mode, all public routines
3313 * below this point must be called with the L_TLS lock held.
3317 tls_pre_decrypt (struct tls_multi
*multi
,
3318 struct sockaddr_in
*from
,
3320 struct crypto_options
*opt
)
3322 struct gc_arena gc
= gc_new ();
3331 /* get opcode and key ID */
3333 uint8_t c
= *BPTR (buf
);
3334 op
= c
>> P_OPCODE_SHIFT
;
3335 key_id
= c
& P_KEY_ID_MASK
;
3338 if (op
== P_DATA_V1
)
3339 { /* data channel packet */
3340 for (i
= 0; i
< KEY_SCAN_SIZE
; ++i
)
3342 struct key_state
*ks
= multi
->key_scan
[i
];
3345 * This is the basic test of TLS state compatibility between a local OpenVPN
3346 * instance and its remote peer.
3348 * If the test fails, it tells us that we are getting a packet from a source
3349 * which claims reference to a prior negotiated TLS session, but the local
3350 * OpenVPN instance has no memory of such a negotiation.
3352 * It almost always occurs on UDP sessions when the passive side of the
3353 * connection is restarted without the active side restarting as well (the
3354 * passive side is the server which only listens for the connections, the
3355 * active side is the client which initiates connections).
3357 if (DECRYPT_KEY_ENABLED (multi
, ks
)
3358 && key_id
== ks
->key_id
3359 && ks
->authenticated
3360 && addr_port_match(from
, &ks
->remote_addr
))
3362 /* return appropriate data channel decrypt key in opt */
3363 opt
->key_ctx_bi
= &ks
->key
;
3364 opt
->packet_id
= multi
->opt
.replay
? &ks
->packet_id
: NULL
;
3365 opt
->pid_persist
= NULL
;
3366 opt
->flags
&= multi
->opt
.crypto_flags_and
;
3367 opt
->flags
|= multi
->opt
.crypto_flags_or
;
3368 ASSERT (buf_advance (buf
, 1));
3370 ks
->n_bytes
+= buf
->len
;
3372 "TLS: data channel, key_id=%d, IP=%s",
3373 key_id
, print_sockaddr (from
, &gc
));
3377 #if 0 /* keys out of sync? */
3380 dmsg (D_TLS_DEBUG
, "TLS_PRE_DECRYPT: [%d] dken=%d rkid=%d lkid=%d auth=%d match=%d",
3382 DECRYPT_KEY_ENABLED (multi
, ks
),
3386 addr_port_match (from
, &ks
->remote_addr
));
3392 "TLS Error: local/remote TLS keys are out of sync: %s [%d]",
3393 print_sockaddr (from
, &gc
), key_id
);
3396 else /* control channel packet */
3398 bool do_burst
= false;
3399 bool new_link
= false;
3400 struct session_id sid
; /* remote session ID */
3402 /* verify legal opcode */
3403 if (op
< P_FIRST_OPCODE
|| op
> P_LAST_OPCODE
)
3406 "TLS Error: unknown opcode received from %s op=%d",
3407 print_sockaddr (from
, &gc
), op
);
3412 if (is_hard_reset (op
, 0))
3414 /* verify client -> server or server -> client connection */
3415 if (((op
== P_CONTROL_HARD_RESET_CLIENT_V1
3416 || op
== P_CONTROL_HARD_RESET_CLIENT_V2
) && !multi
->opt
.server
)
3417 || ((op
== P_CONTROL_HARD_RESET_SERVER_V1
3418 || op
== P_CONTROL_HARD_RESET_SERVER_V2
) && multi
->opt
.server
))
3421 "TLS Error: client->client or server->server connection attempted from %s",
3422 print_sockaddr (from
, &gc
));
3428 * Authenticate Packet
3430 dmsg (D_TLS_DEBUG
, "TLS: control channel, op=%s, IP=%s",
3431 packet_opcode_name (op
), print_sockaddr (from
, &gc
));
3433 /* get remote session-id */
3435 struct buffer tmp
= *buf
;
3436 buf_advance (&tmp
, 1);
3437 if (!session_id_read (&sid
, &tmp
) || !session_id_defined (&sid
))
3440 "TLS Error: session-id not found in packet from %s",
3441 print_sockaddr (from
, &gc
));
3446 /* use session ID to match up packet with appropriate tls_session object */
3447 for (i
= 0; i
< TM_SIZE
; ++i
)
3449 struct tls_session
*session
= &multi
->session
[i
];
3450 struct key_state
*ks
= &session
->key
[KS_PRIMARY
];
3453 "TLS: initial packet test, i=%d state=%s, mysid=%s, rec-sid=%s, rec-ip=%s, stored-sid=%s, stored-ip=%s",
3455 state_name (ks
->state
),
3456 session_id_print (&session
->session_id
, &gc
),
3457 session_id_print (&sid
, &gc
),
3458 print_sockaddr (from
, &gc
),
3459 session_id_print (&ks
->session_id_remote
, &gc
),
3460 print_sockaddr (&ks
->remote_addr
, &gc
));
3462 if (session_id_equal (&ks
->session_id_remote
, &sid
))
3465 if (i
== TM_LAME_DUCK
) {
3467 "TLS ERROR: received control packet with stale session-id=%s",
3468 session_id_print (&sid
, &gc
));
3472 "TLS: found match, session[%d], sid=%s",
3473 i
, session_id_print (&sid
, &gc
));
3479 * Initial packet received.
3482 if (i
== TM_SIZE
&& is_hard_reset (op
, 0))
3484 struct tls_session
*session
= &multi
->session
[TM_ACTIVE
];
3485 struct key_state
*ks
= &session
->key
[KS_PRIMARY
];
3487 if (!is_hard_reset (op
, multi
->opt
.key_method
))
3489 msg (D_TLS_ERRORS
, "TLS ERROR: initial packet local/remote key_method mismatch, local key_method=%d, op=%s",
3490 multi
->opt
.key_method
,
3491 packet_opcode_name (op
));
3496 * If we have no session currently in progress, the initial packet will
3497 * open a new session in TM_ACTIVE rather than TM_UNTRUSTED.
3499 if (!session_id_defined (&ks
->session_id_remote
))
3501 if (multi
->opt
.single_session
&& multi
->n_sessions
)
3504 "TLS Error: Cannot accept new session request from %s due to session context expire or --single-session [1]",
3505 print_sockaddr (from
, &gc
));
3509 #ifdef ENABLE_MANAGEMENT
3512 management_set_state (management
,
3519 msg (D_TLS_DEBUG_LOW
,
3520 "TLS: Initial packet from %s, sid=%s",
3521 print_sockaddr (from
, &gc
),
3522 session_id_print (&sid
, &gc
));
3527 session
->untrusted_sockaddr
= *from
;
3531 if (i
== TM_SIZE
&& is_hard_reset (op
, 0))
3534 * No match with existing sessions,
3535 * probably a new session.
3537 struct tls_session
*session
= &multi
->session
[TM_UNTRUSTED
];
3540 * If --single-session, don't allow any hard-reset connection request
3541 * unless it the the first packet of the session.
3543 if (multi
->opt
.single_session
)
3546 "TLS Error: Cannot accept new session request from %s due to session context expire or --single-session [2]",
3547 print_sockaddr (from
, &gc
));
3551 if (!is_hard_reset (op
, multi
->opt
.key_method
))
3553 msg (D_TLS_ERRORS
, "TLS ERROR: new session local/remote key_method mismatch, local key_method=%d, op=%s",
3554 multi
->opt
.key_method
,
3555 packet_opcode_name (op
));
3559 if (!read_control_auth (buf
, &session
->tls_auth
, from
))
3563 * New session-initiating control packet is authenticated at this point,
3564 * assuming that the --tls-auth command line option was used.
3566 * Without --tls-auth, we leave authentication entirely up to TLS.
3568 msg (D_TLS_DEBUG_LOW
,
3569 "TLS: new session incoming connection from %s",
3570 print_sockaddr (from
, &gc
));
3574 session
->untrusted_sockaddr
= *from
;
3578 struct tls_session
*session
= &multi
->session
[i
];
3579 struct key_state
*ks
= &session
->key
[KS_PRIMARY
];
3582 * Packet must belong to an existing session.
3584 if (i
!= TM_ACTIVE
&& i
!= TM_UNTRUSTED
)
3587 "TLS Error: Unroutable control packet received from %s (si=%d op=%s)",
3588 print_sockaddr (from
, &gc
),
3590 packet_opcode_name (op
));
3595 * Verify remote IP address
3597 if (!new_link
&& !addr_port_match (&ks
->remote_addr
, from
))
3599 msg (D_TLS_ERRORS
, "TLS Error: Received control packet from unexpected IP addr: %s",
3600 print_sockaddr (from
, &gc
));
3605 * Remote is requesting a key renegotiation
3607 if (op
== P_CONTROL_SOFT_RESET_V1
3608 && DECRYPT_KEY_ENABLED (multi
, ks
))
3610 if (!read_control_auth (buf
, &session
->tls_auth
, from
))
3613 key_state_soft_reset (session
);
3616 "TLS: received P_CONTROL_SOFT_RESET_V1 s=%d sid=%s",
3617 i
, session_id_print (&sid
, &gc
));
3622 * Remote responding to our key renegotiation request?
3624 if (op
== P_CONTROL_SOFT_RESET_V1
)
3627 if (!read_control_auth (buf
, &session
->tls_auth
, from
))
3631 "TLS: received control channel packet s#=%d sid=%s",
3632 i
, session_id_print (&sid
, &gc
));
3637 * We have an authenticated packet (if --tls-auth was set).
3638 * Now pass to our reliability level which deals with
3639 * packet acknowledgements, retransmits, sequencing, etc.
3642 struct tls_session
*session
= &multi
->session
[i
];
3643 struct key_state
*ks
= &session
->key
[KS_PRIMARY
];
3645 /* Make sure we were initialized and that we're not in an error state */
3646 ASSERT (ks
->state
!= S_UNDEF
);
3647 ASSERT (ks
->state
!= S_ERROR
);
3648 ASSERT (session_id_defined (&session
->session_id
));
3650 /* Let our caller know we processed a control channel packet */
3654 * Set our remote address and remote session_id
3658 ks
->session_id_remote
= sid
;
3659 ks
->remote_addr
= *from
;
3660 ++multi
->n_sessions
;
3662 else if (!addr_port_match (&ks
->remote_addr
, from
))
3665 "TLS Error: Existing session control channel packet from unknown IP address: %s",
3666 print_sockaddr (from
, &gc
));
3671 * Should we do a retransmit of all unacknowledged packets in
3672 * the send buffer? This improves the start-up efficiency of the
3673 * initial key negotiation after the 2nd peer comes online.
3675 if (do_burst
&& !session
->burst
)
3677 reliable_schedule_now (ks
->send_reliable
);
3678 session
->burst
= true;
3682 if (ks
->key_id
!= key_id
)
3685 "TLS ERROR: local/remote key IDs out of sync (%d/%d) ID: %s",
3686 ks
->key_id
, key_id
, print_key_id (multi
, &gc
));
3691 * Process incoming ACKs for packets we can now
3692 * delete from reliable send buffer
3695 /* buffers all packet IDs to delete from send_reliable */
3696 struct reliable_ack send_ack
;
3699 if (!reliable_ack_read (&send_ack
, buf
, &session
->session_id
))
3702 "TLS Error: reading acknowledgement record from packet");
3705 reliable_send_purge (ks
->send_reliable
, &send_ack
);
3708 if (op
!= P_ACK_V1
&& reliable_can_get (ks
->rec_reliable
))
3712 /* Extract the packet ID from the packet */
3713 if (reliable_ack_read_packet_id (buf
, &id
))
3715 /* Avoid deadlock by rejecting packet that would de-sequentialize receive buffer */
3716 if (reliable_wont_break_sequentiality (ks
->rec_reliable
, id
))
3718 if (reliable_not_replay (ks
->rec_reliable
, id
))
3720 /* Save incoming ciphertext packet to reliable buffer */
3721 struct buffer
*in
= reliable_get_buf (ks
->rec_reliable
);
3723 ASSERT (buf_copy (in
, buf
));
3724 reliable_mark_active_incoming (ks
->rec_reliable
, in
, id
, op
);
3727 /* Process outgoing acknowledgment for packet just received, even if it's a replay */
3728 reliable_ack_acknowledge_packet_id (ks
->rec_ack
, id
);
3738 opt
->key_ctx_bi
= NULL
;
3739 opt
->packet_id
= NULL
;
3740 opt
->pid_persist
= NULL
;
3741 opt
->flags
&= multi
->opt
.crypto_flags_and
;
3747 ++multi
->n_soft_errors
;
3752 * This function is similar to tls_pre_decrypt, except it is called
3753 * when we are in server mode and receive an initial incoming
3754 * packet. Note that we don't modify
3755 * any state in our parameter objects. The purpose is solely to
3756 * determine whether we should generate a client instance
3757 * object, in which case true is returned.
3759 * This function is essentially the first-line HMAC firewall
3760 * on the UDP port listener in --mode server mode.
3763 tls_pre_decrypt_lite (const struct tls_auth_standalone
*tas
,
3764 const struct sockaddr_in
*from
,
3765 const struct buffer
*buf
)
3767 struct gc_arena gc
= gc_new ();
3775 /* get opcode and key ID */
3777 uint8_t c
= *BPTR (buf
);
3778 op
= c
>> P_OPCODE_SHIFT
;
3779 key_id
= c
& P_KEY_ID_MASK
;
3782 /* this packet is from an as-yet untrusted source, so
3783 scrutinize carefully */
3785 if (op
!= P_CONTROL_HARD_RESET_CLIENT_V2
)
3788 * This can occur due to bogus data or DoS packets.
3790 dmsg (D_TLS_STATE_ERRORS
,
3791 "TLS State Error: No TLS state for client %s, opcode=%d",
3792 print_sockaddr (from
, &gc
),
3799 dmsg (D_TLS_STATE_ERRORS
,
3800 "TLS State Error: Unknown key ID (%d) received from %s -- 0 was expected",
3802 print_sockaddr (from
, &gc
));
3806 if (buf
->len
> EXPANDED_SIZE_DYNAMIC (&tas
->frame
))
3808 dmsg (D_TLS_STATE_ERRORS
,
3809 "TLS State Error: Large packet (size %d) received from %s -- a packet no larger than %d bytes was expected",
3811 print_sockaddr (from
, &gc
),
3812 EXPANDED_SIZE_DYNAMIC (&tas
->frame
));
3817 struct buffer newbuf
= clone_buf (buf
);
3818 struct crypto_options co
= tas
->tls_auth_options
;
3822 * We are in read-only mode at this point with respect to TLS
3823 * control channel state. After we build a new client instance
3824 * object, we will process this session-initiating packet for real.
3826 co
.flags
|= CO_IGNORE_PACKET_ID
;
3828 /* HMAC test, if --tls-auth was specified */
3829 status
= read_control_auth (&newbuf
, &co
, from
);
3835 * At this point, if --tls-auth is being used, we know that
3836 * the packet has passed the HMAC test, but we don't know if
3837 * it is a replay yet. We will attempt to defeat replays
3838 * by not advancing to the S_START state until we
3839 * receive an ACK from our first reply to the client
3840 * that includes an HMAC of our randomly generated 64 bit
3843 * On the other hand if --tls-auth is not being used, we
3844 * will proceed to begin the TLS authentication
3845 * handshake with only cursory integrity checks having
3846 * been performed, since we will be leaving the task
3847 * of authentication solely up to TLS.
3862 /* Choose the key with which to encrypt a data packet */
3864 tls_pre_encrypt (struct tls_multi
*multi
,
3865 struct buffer
*buf
, struct crypto_options
*opt
)
3867 multi
->save_ks
= NULL
;
3871 for (i
= 0; i
< KEY_SCAN_SIZE
; ++i
)
3873 struct key_state
*ks
= multi
->key_scan
[i
];
3874 if (ks
->state
>= S_ACTIVE
&& ks
->authenticated
)
3876 opt
->key_ctx_bi
= &ks
->key
;
3877 opt
->packet_id
= multi
->opt
.replay
? &ks
->packet_id
: NULL
;
3878 opt
->pid_persist
= NULL
;
3879 opt
->flags
&= multi
->opt
.crypto_flags_and
;
3880 opt
->flags
|= multi
->opt
.crypto_flags_or
;
3881 multi
->save_ks
= ks
;
3882 dmsg (D_TLS_DEBUG
, "TLS: tls_pre_encrypt: key_id=%d", ks
->key_id
);
3888 struct gc_arena gc
= gc_new ();
3889 dmsg (D_TLS_NO_SEND_KEY
, "TLS Warning: no data channel send key available: %s",
3890 print_key_id (multi
, &gc
));
3896 opt
->key_ctx_bi
= NULL
;
3897 opt
->packet_id
= NULL
;
3898 opt
->pid_persist
= NULL
;
3899 opt
->flags
&= multi
->opt
.crypto_flags_and
;
3902 /* Prepend the appropriate opcode to encrypted buffer prior to TCP/UDP send */
3904 tls_post_encrypt (struct tls_multi
*multi
, struct buffer
*buf
)
3906 struct key_state
*ks
;
3909 ks
= multi
->save_ks
;
3910 multi
->save_ks
= NULL
;
3914 ASSERT (op
= buf_prepend (buf
, 1));
3915 *op
= (P_DATA_V1
<< P_OPCODE_SHIFT
) | ks
->key_id
;
3917 ks
->n_bytes
+= buf
->len
;
3922 * Send a payload over the TLS control channel.
3923 * Called externally.
3927 tls_send_payload (struct tls_multi
*multi
,
3928 const uint8_t *data
,
3931 struct tls_session
*session
;
3932 struct key_state
*ks
;
3939 session
= &multi
->session
[TM_ACTIVE
];
3940 ks
= &session
->key
[KS_PRIMARY
];
3942 if (ks
->state
>= S_ACTIVE
)
3944 if (key_state_write_plaintext_const (multi
, ks
, data
, size
) == 1)
3954 tls_rec_payload (struct tls_multi
*multi
,
3957 struct tls_session
*session
;
3958 struct key_state
*ks
;
3965 session
= &multi
->session
[TM_ACTIVE
];
3966 ks
= &session
->key
[KS_PRIMARY
];
3968 if (ks
->state
>= S_ACTIVE
&& BLEN (&ks
->plaintext_read_buf
))
3970 if (buf_copy (buf
, &ks
->plaintext_read_buf
))
3972 ks
->plaintext_read_buf
.len
= 0;
3981 * Dump a human-readable rendition of an openvpn packet
3982 * into a garbage collectable string which is returned.
3985 protocol_dump (struct buffer
*buffer
, unsigned int flags
, struct gc_arena
*gc
)
3987 struct buffer out
= alloc_buf_gc (256, gc
);
3988 struct buffer buf
= *buffer
;
3994 int tls_auth_hmac_size
= (flags
& PD_TLS_AUTH_HMAC_SIZE_MASK
);
3998 buf_printf (&out
, "DATA UNDEF len=%d", buf
.len
);
4002 if (!(flags
& PD_TLS
))
4006 * Initial byte (opcode)
4008 if (!buf_read (&buf
, &c
, sizeof (c
)))
4010 op
= (c
>> P_OPCODE_SHIFT
);
4011 key_id
= c
& P_KEY_ID_MASK
;
4012 buf_printf (&out
, "%s kid=%d", packet_opcode_name (op
), key_id
);
4014 if (op
== P_DATA_V1
)
4021 struct session_id sid
;
4023 if (!session_id_read (&sid
, &buf
))
4025 if (flags
& PD_VERBOSE
)
4026 buf_printf (&out
, " sid=%s", session_id_print (&sid
, gc
));
4030 * tls-auth hmac + packet_id
4032 if (tls_auth_hmac_size
)
4034 struct packet_id_net pin
;
4035 uint8_t tls_auth_hmac
[MAX_HMAC_KEY_LENGTH
];
4037 ASSERT (tls_auth_hmac_size
<= MAX_HMAC_KEY_LENGTH
);
4039 if (!buf_read (&buf
, tls_auth_hmac
, tls_auth_hmac_size
))
4041 if (flags
& PD_VERBOSE
)
4042 buf_printf (&out
, " tls_hmac=%s", format_hex (tls_auth_hmac
, tls_auth_hmac_size
, 0, gc
));
4044 if (!packet_id_read (&pin
, &buf
, true))
4046 buf_printf(&out
, " pid=%s", packet_id_net_print (&pin
, (flags
& PD_VERBOSE
), gc
));
4052 buf_printf (&out
, " %s", reliable_ack_print(&buf
, (flags
& PD_VERBOSE
), gc
));
4062 if (!buf_read (&buf
, &l
, sizeof (l
)))
4065 buf_printf (&out
, " pid=" packet_id_format
, (packet_id_print_type
)l
);
4069 if (flags
& PD_SHOW_DATA
)
4070 buf_printf (&out
, " DATA %s", format_hex (BPTR (&buf
), BLEN (&buf
), 80, gc
));
4072 buf_printf (&out
, " DATA len=%d", buf
.len
);
4078 #ifdef EXTRACT_X509_FIELD_TEST
4081 extract_x509_field_test (void)
4085 static const char field_name
[] = "CN";
4087 while (fgets (line
, sizeof (line
), stdin
))
4090 extract_x509_field (line
, field_name
, field
, sizeof (field
));
4091 printf ("CN: '%s'\n", field
);
4098 static void dummy(void) {}
4099 #endif /* USE_CRYPTO && USE_SSL*/