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-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.
35 #if defined(USE_CRYPTO) && defined(USE_SSL)
53 #include "cryptoapi.h"
59 static const char ssl_default_options_string
[] = "V0 UNDEF";
62 static inline const char *
63 local_options_string (const struct tls_session
*session
)
66 return session
->opt
->local_options
;
68 return ssl_default_options_string
;
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
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);
95 #define INCR_GENERATED
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 */
115 ASSERT (!fclose (biofp
));
123 const time_t current
= time (NULL
);
124 const pid_t pid
= getpid ();
126 if (biofp_last_open
+ biofp_reopen_interval
< current
)
131 openvpn_snprintf(fn
, sizeof(fn
), "bio/%d-%d.log", pid
, biofp_toggle
);
132 biofp
= fopen (fn
, "w");
134 biofp_last_open
= time (NULL
);
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 ();
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
));
154 bio_debug_oc (const char *mode
, BIO
*bio
)
157 fprintf(biofp
, "BIO %s time=" time_format
" bio=" ptr_format
"\n",
158 mode
, time (NULL
), (ptr_type
)bio
);
165 * Max number of bytes we will add
166 * for data structures common to both
167 * data and control channel packets.
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.
181 tls_init_control_channel_frame_parameters(const struct frame
*data_channel_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 */
211 ssl_set_mydata_index ()
213 mydata_index
= SSL_get_ex_new_index (0, "struct session *", NULL
, NULL
, NULL
);
214 ASSERT (mydata_index
>= 0);
221 SSL_load_error_strings ();
222 OpenSSL_add_all_algorithms ();
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.
232 CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON
);
235 ssl_set_mydata_index ();
242 FILE* fp
= fopen ("sdlog", "w");
244 CRYPTO_mem_leaks_fp (fp
);
248 uninit_crypto_lib ();
254 * OpenSSL library calls pem_password_callback if the
255 * private key is protected by a password.
258 static struct user_pass passbuf
; /* GLOBAL */
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
)
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);
283 * Auth username/password handling
286 static bool auth_user_pass_enabled
; /* GLOBAL */
287 static struct user_pass auth_user_pass
; /* GLOBAL */
290 auth_user_pass_setup (const char *auth_file
)
292 auth_user_pass_enabled
= true;
293 if (!auth_user_pass
.defined
)
296 get_user_pass_auto_userid (&auth_user_pass
, auth_file
);
298 get_user_pass (&auth_user_pass
, auth_file
, UP_TYPE_AUTH
, GET_USER_PASS_MANAGEMENT
|GET_USER_PASS_SENSITIVE
);
304 * Disable password caching
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.
317 ssl_purge_auth (void)
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.
331 tmp_rsa_cb (SSL
* s
, int is_export
, int keylength
)
333 static RSA
*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
);
343 * Cert hash functions
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
);
363 cert_hash_print (const struct cert_hash_set
*chs
, int msglevel
)
365 struct gc_arena gc
= gc_new ();
366 msg (msglevel
, "CERT_HASH");
370 for (i
= 0; i
< MAX_CERT_DEPTH
; ++i
)
372 const struct cert_hash
*ch
= chs
->ch
[i
];
374 msg (msglevel
, "%d:%s", i
, format_hex(ch
->sha1_hash
, SHA_DIGEST_LENGTH
, 0, &gc
));
382 cert_hash_free (struct cert_hash_set
*chs
)
387 for (i
= 0; i
< MAX_CERT_DEPTH
; ++i
)
394 cert_hash_compare (const struct cert_hash_set
*chs1
, const struct cert_hash_set
*chs2
)
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
];
406 else if (ch1
&& ch2
&& !memcmp (ch1
->sha1_hash
, ch2
->sha1_hash
, SHA_DIGEST_LENGTH
))
413 else if (!chs1
&& !chs2
)
419 static struct cert_hash_set
*
420 cert_hash_copy (const struct cert_hash_set
*chs
)
422 struct cert_hash_set
*dest
= NULL
;
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
];
432 ALLOC_OBJ (dest
->ch
[i
], struct cert_hash
);
433 memcpy (dest
->ch
[i
]->sha1_hash
, ch
->sha1_hash
, SHA_DIGEST_LENGTH
);
441 * Extract a field from an X509 subject name.
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).
453 extract_x509_field_ssl (X509_NAME
*x509
, const char *field_name
, char *out
, int size
)
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
);
466 tmp
= X509_NAME_get_index_by_NID(x509
, nid
, lastpos
);
473 x509ne
= X509_NAME_get_entry(x509
, lastpos
);
477 asn1
= X509_NAME_ENTRY_get_data(x509ne
);
480 tmp
= ASN1_STRING_to_UTF8(&buf
, asn1
);
484 strncpynt(out
, (char *)buf
, size
);
487 const bool ret
= (strlen ((char *)buf
) < size
);
494 * Save X509 fields to environment, using the naming convention:
496 * X509_{cert_depth}_{name}={value}
499 setenv_x509 (struct env_set
*es
, const int error_depth
, X509_NAME
*x509
)
505 X509_NAME_ENTRY
*ent
;
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
);
517 fn
= X509_NAME_ENTRY_get_object (ent
);
520 val
= X509_NAME_ENTRY_get_data (ent
);
523 fn_nid
= OBJ_obj2nid (fn
);
524 if (fn_nid
== NID_undef
)
526 objbuf
= OBJ_nid2sn (fn_nid
);
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)
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
);
545 setenv_untrusted (struct tls_session
*session
)
547 setenv_link_socket_actual (session
->opt
->es
, "untrusted", &session
->untrusted_addr
, SA_IP_PORT
);
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
;
558 session
->common_name_hashval
= 0;
563 session
->common_name
= string_alloc (common_name
, NULL
);
566 const uint32_t len
= (uint32_t) strlen (common_name
);
568 session
->common_name_hashval
= hash_func ((const uint8_t*)common_name
, len
+1, 0);
570 session
->common_name_hashval
= 0;
576 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
578 bool verify_cert_eku (X509
*x509
, const char * const expected_oid
) {
580 EXTENDED_KEY_USAGE
*eku
= NULL
;
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");
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
);
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
)) {
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
)) {
610 sk_ASN1_OBJECT_pop_free (eku
, ASN1_OBJECT_free
);
616 bool verify_cert_ku (X509
*x509
, const unsigned * const expected_ku
, int expected_len
) {
618 ASN1_BIT_STRING
*ku
= NULL
;
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");
628 if (ASN1_BIT_STRING_get_bit (ku
, i
)) {
634 * Fixup if no LSB bits
636 if ((nku
& 0xff) == 0) {
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
]) {
653 ASN1_BIT_STRING_free (ku
);
659 #endif /* OPENSSL_VERSION_NUMBER */
662 * nsCertType checking
665 #define verify_nsCertType(x, usage) (((x)->ex_flags & EXFLAG_NSCERT) && ((x)->ex_nscert & (usage)))
668 print_nsCertType (int type
)
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
, '_');
687 string_mod (str
, restrictive_flags
, 0, '_');
691 * Our verify callback function -- check
692 * that an incoming peer certificate is good.
696 verify_callback (int preverify_ok
, X509_STORE_CTX
* ctx
)
698 char *subject
= NULL
;
700 char common_name
[TLS_CN_LEN
];
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());
710 session
= (struct tls_session
*) SSL_get_ex_data (ssl
, mydata_index
);
715 session
->verified
= false;
717 /* get the X509 name */
718 subject
= X509_NAME_oneline (X509_get_subject_name (ctx
->current_cert
), NULL
, 0);
721 msg (D_TLS_ERRORS
, "VERIFY ERROR: depth=%d, could not extract X509 subject string from certificate", ctx
->error_depth
);
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",
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
));
758 /* did peer present cert which was signed our root cert? */
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
);
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
);
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
));
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");
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");
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
);
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
))
866 argv_printf (&argv
, "%d %s",
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
);
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
)
890 setenv_str (opt
->es
, "script_type", "tls-verify");
892 argv_printf (&argv
, "%sc %d %s",
896 argv_msg_prefix (D_TLS_DEBUG
, &argv
, "TLS: executing verify command");
897 ret
= openvpn_execve (&argv
, opt
->es
, S_SCRIPT
);
901 msg (D_HANDSHAKE
, "VERIFY SCRIPT OK: depth=%d, %s",
902 ctx
->error_depth
, subject
);
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 */
918 X509_REVOKED
*revoked
;
922 in
=BIO_new(BIO_s_file());
925 msg (M_ERR
, "CRL: BIO err");
928 if (BIO_read_filename(in
, opt
->crl_file
) <= 0) {
929 msg (M_ERR
, "CRL: cannot read: %s", opt
->crl_file
);
932 crl
=PEM_read_bio_X509_CRL(in
,NULL
,NULL
,NULL
);
934 msg (M_ERR
, "CRL: cannot read CRL from file %s", opt
->crl_file
);
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
);
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
);
955 msg (D_HANDSHAKE
, "CRL CHECK OK: %s",subject
);
966 msg (D_HANDSHAKE
, "VERIFY OK: depth=%d, %s", ctx
->error_depth
, subject
);
968 session
->verified
= true;
971 return 1; /* Accept connection */
977 return 0; /* Reject connection */
981 tls_set_common_name (struct tls_multi
*multi
, const char *common_name
)
984 set_common_name (&multi
->session
[TM_ACTIVE
], common_name
);
988 tls_common_name (const struct tls_multi
*multi
, const bool null
)
990 const char *ret
= NULL
;
992 ret
= multi
->session
[TM_ACTIVE
].common_name
;
993 if (ret
&& strlen (ret
))
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
);
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
);
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
,
1028 /* disable the tunnel */
1029 tls_deauthenticate (multi
);
1036 multi
->locked_username
= string_alloc (username
, NULL
);
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
1050 #ifdef MANAGEMENT_DEF_AUTH
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
;
1069 return ACF_DISABLED
;
1073 #ifdef PLUGIN_DEF_AUTH
1076 * auth_control_file functions
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
;
1091 key_state_gen_auth_control_file (struct key_state
*ks
, const struct tls_options
*opt
)
1093 struct gc_arena gc
= gc_new ();
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
);
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");
1115 const int c
= fgetc (fp
);
1117 ret
= ACF_SUCCEEDED
;
1121 ks
->auth_control_status
= ret
;
1126 return ACF_DISABLED
;
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 */
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
;
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
))
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
);
1189 #ifdef MANAGEMENT_DEF_AUTH
1190 s2
= man_def_auth_test (ks
);
1192 ASSERT (s1
< 4 && s2
< 4);
1193 switch (acf_merge
[(s1
<<2) + s2
])
1198 ks
->auth_deferred
= false;
1201 if (now
< ks
->auth_deferred_expire
)
1205 ks
->authenticated
= false;
1219 dmsg (D_TLS_ERRORS
, "TAS: a=%d s=%d d=%d", active
, success
, deferred
);
1223 return TLS_AUTHENTICATION_SUCCEEDED
;
1224 else if (!active
|| deferred
)
1225 return TLS_AUTHENTICATION_DEFERRED
;
1227 return TLS_AUTHENTICATION_FAILED
;
1230 #ifdef MANAGEMENT_DEF_AUTH
1232 tls_authenticate_key (struct tls_multi
*multi
, const unsigned int mda_key_id
, const bool auth
, const char *client_reason
)
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
;
1254 tls_deauthenticate (struct tls_multi
*multi
)
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.
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
1290 use_inline_load_verify_locations (SSL_CTX
*ctx
, const char *ca_string
)
1292 X509_STORE
*store
= NULL
;
1297 in
= BIO_new_mem_buf ((char *)ca_string
, -1);
1303 if (!PEM_read_bio_X509 (in
, &cert
, 0, NULL
))
1311 store
= SSL_CTX_get_cert_store (ctx
);
1315 if (!X509_STORE_add_cert (store
, cert
))
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
)
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);
1353 if ((sk
== NULL
) || (in
== NULL
))
1358 if (PEM_read_bio_X509(in
,&x
,NULL
,NULL
) == NULL
)
1362 ret
= sk_X509_NAME_new_null();
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)
1374 sk_X509_NAME_push(sk
,xn
);
1375 sk_X509_NAME_push(ret
,xn
);
1382 if (ret
!= NULL
) sk_X509_NAME_pop_free(ret
,X509_NAME_free
);
1385 if (sk
!= NULL
) sk_X509_NAME_free(sk
);
1386 if (in
!= NULL
) BIO_free(in
);
1387 if (x
!= NULL
) X509_free(x
);
1394 use_inline_certificate_file (SSL_CTX
*ctx
, const char *cert_string
)
1400 in
= BIO_new_mem_buf ((char *)cert_string
, -1);
1404 x
= PEM_read_bio_X509 (in
,
1406 ctx
->default_passwd_callback
,
1407 ctx
->default_passwd_callback_userdata
);
1411 ret
= SSL_CTX_use_certificate(ctx
, x
);
1422 use_inline_PrivateKey_file (SSL_CTX
*ctx
, const char *key_string
)
1425 EVP_PKEY
*pkey
= NULL
;
1428 in
= BIO_new_mem_buf ((char *)key_string
, -1);
1432 pkey
= PEM_read_bio_PrivateKey (in
,
1434 ctx
->default_passwd_callback
,
1435 ctx
->default_passwd_callback_userdata
);
1439 ret
= SSL_CTX_use_PrivateKey (ctx
, pkey
);
1443 EVP_PKEY_free (pkey
);
1452 * Initialize SSL context.
1453 * All files are in PEM format.
1456 init_ssl (const struct options
*options
)
1458 SSL_CTX
*ctx
= NULL
;
1461 bool using_cert_file
= false;
1465 if (options
->tls_server
)
1467 ctx
= SSL_CTX_new (TLSv1_server_method ());
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");
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
);
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",
1497 else /* if client */
1499 ctx
= SSL_CTX_new (TLSv1_client_method ());
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 */
1518 STACK_OF(X509
) *ca
= NULL
;
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
);
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 */
1536 if (!PKCS12_parse(p12
, password
, &pkey
, &cert
, &ca
))
1539 msg (M_WARN
|M_SSL
, "Error parsing PKCS#12 file %s", options
->pkcs12_file
);
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)");
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
);
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
);
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");
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
)
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
);
1632 status
= SSL_CTX_use_PrivateKey_file (ctx
, options
->priv_key_file
, SSL_FILETYPE_PEM
);
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
);
1640 msg (M_WARN
|M_SSL
, "Cannot load private key file %s", options
->priv_key_file
);
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
)
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
);
1664 /* Load CA file for verifying peer supplied certificate */
1665 status
= SSL_CTX_load_verify_locations (ctx
, options
->ca_file
, options
->ca_path
);
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
);
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
);
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
);
1685 msg(M_WARN
, "WARNING: this version of OpenSSL cannot handle CRL files in capath");
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
);
1703 cert_names
= SSL_load_client_CA_file (options
->ca_file
);
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 */
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");
1726 SSL_CTX_set_verify (ctx
, SSL_VERIFY_PEER
| SSL_VERIFY_FAIL_IF_NO_PEER_CERT
,
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
);
1751 * Print a one line summary of SSL/TLS session handshake.
1754 print_details (SSL
* c_ssl
, const char *prefix
)
1762 ciph
= SSL_get_current_cipher (c_ssl
);
1763 openvpn_snprintf (s1
, sizeof (s1
), "%s %s, cipher %s %s",
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
);
1771 EVP_PKEY
*pkey
= X509_get_pubkey (cert
);
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
);
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.
1800 show_available_tls_ciphers ()
1804 const char *cipher_name
;
1807 ctx
= SSL_CTX_new (TLSv1_method ());
1809 msg (M_SSLERR
, "Cannot create SSL_CTX object");
1810 ssl
= SSL_new (ctx
);
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
);
1825 * The OpenSSL library has a notion of preference in TLS
1826 * ciphers. Higher preference == more secure.
1827 * Return the highest preference cipher.
1830 get_highest_preference_tls_cipher (char *buf
, int size
)
1834 const char *cipher_name
;
1836 ctx
= SSL_CTX_new (TLSv1_method ());
1838 msg (M_SSLERR
, "Cannot create SSL_CTX object");
1839 ssl
= SSL_new (ctx
);
1841 msg (M_SSLERR
, "Cannot create SSL object");
1843 cipher_name
= SSL_get_cipher_list (ssl
, 0);
1844 strncpynt (buf
, cipher_name
, size
);
1851 * Map internal constants to ascii names.
1854 state_name (int state
)
1863 return "S_PRE_START";
1867 return "S_SENT_KEY";
1873 return "S_NORMAL_OP";
1882 packet_opcode_name (int 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";
1897 return "P_CONTROL_V1";
1908 session_index_name (int index
)
1915 return "TM_UNTRUSTED";
1917 return "TM_LAME_DUCK";
1927 print_key_id (struct tls_multi
*multi
, struct gc_arena
*gc
)
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
));
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.
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
)
1957 if (!key_method
|| key_method
>= 2)
1958 if (op
== P_CONTROL_HARD_RESET_CLIENT_V2
|| op
== P_CONTROL_HARD_RESET_SERVER_V2
)
1965 * OpenVPN's interface to SSL/TLS authentication,
1966 * encryption, and decryption is exclusively
1967 * through "memory BIOs".
1970 getbio (BIO_METHOD
* type
, const char *desc
)
1973 ret
= BIO_new (type
);
1975 msg (M_SSLERR
, "Error creating %s BIO", desc
);
1980 * Write to an OpenSSL BIO in non-blocking mode.
1983 bio_write (struct tls_multi
* multi
, BIO
*bio
, const uint8_t *data
, int size
, const char *desc
)
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.
1997 bio_debug_data ("write", bio
, data
, size
, desc
);
1999 i
= BIO_write (bio
, data
, size
);
2003 if (BIO_should_retry (bio
))
2009 msg (D_TLS_ERRORS
| M_SSL
, "TLS ERROR: BIO write %s error",
2017 msg (D_TLS_ERRORS
| M_SSL
,
2018 "TLS ERROR: BIO write %s incomplete %d/%d", desc
, i
, size
);
2023 { /* successful write */
2024 dmsg (D_HANDSHAKE_VERBOSE
, "BIO write %s %d bytes", desc
, i
);
2032 * Read from an OpenSSL BIO in non-blocking mode.
2035 bio_read (struct tls_multi
* multi
, BIO
*bio
, struct buffer
*buf
, int maxlen
, const char *desc
)
2039 ASSERT (buf
->len
>= 0);
2046 int len
= buf_forward_capacity (buf
);
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
));
2059 bio_debug_data ("read", bio
, BPTR (buf
), i
, desc
);
2063 if (BIO_should_retry (bio
))
2069 msg (D_TLS_ERRORS
| M_SSL
, "TLS_ERROR: BIO read %s error",
2081 { /* successful read */
2082 dmsg (D_HANDSHAKE_VERBOSE
, "BIO read %s %d bytes", desc
, i
);
2085 VALGRIND_MAKE_READABLE ((void *) BPTR (buf
), BLEN (buf
));
2092 * Inline functions for reading from and writing
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 */
2107 key_state_write_plaintext (struct tls_multi
*multi
, struct key_state
*ks
, struct buffer
*buf
)
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
);
2118 key_state_write_plaintext_const (struct tls_multi
*multi
, struct key_state
*ks
, const uint8_t *data
, int len
)
2121 perf_push (PERF_BIO_WRITE_PLAINTEXT
);
2122 ret
= bio_write (multi
, ks
->ssl_bio
, data
, len
, "tls_write_plaintext_const");
2128 key_state_write_ciphertext (struct tls_multi
*multi
, struct key_state
*ks
, struct buffer
*buf
)
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
);
2139 key_state_read_plaintext (struct tls_multi
*multi
, struct key_state
*ks
, struct buffer
*buf
,
2143 perf_push (PERF_BIO_READ_PLAINTEXT
);
2144 ret
= bio_read (multi
, ks
->ssl_bio
, buf
, maxlen
, "tls_read_plaintext");
2150 key_state_read_ciphertext (struct tls_multi
*multi
, struct key_state
*ks
, struct buffer
*buf
,
2154 perf_push (PERF_BIO_READ_CIPHERTEXT
);
2155 ret
= bio_read (multi
, ks
->ct_out
, buf
, maxlen
, "tls_read_ciphertext");
2161 * Initialize a key_state. Each key_state corresponds to
2162 * a specific SSL/TLS session.
2165 key_state_init (struct tls_session
*session
, struct key_state
*ks
)
2170 * Build TLS object that reads/writes ciphertext
2171 * to/from memory BIOs.
2175 ks
->ssl
= SSL_new (session
->opt
->ssl_ctx
);
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");
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
);
2193 if (session
->opt
->server
)
2194 SSL_set_accept_state (ks
->ssl
);
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.
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
,
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
++;
2247 key_state_free (struct key_state
*ks
, bool clear
)
2249 ks
->state
= S_UNDEF
;
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
);
2257 BIO_free_all(ks
->ssl_bio
);
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
);
2284 packet_id_free (&ks
->packet_id
);
2286 #ifdef PLUGIN_DEF_AUTH
2287 key_state_rm_auth_control_file (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.
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");
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
));
2357 tls_session_free (struct tls_session
*session
, bool clear
)
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
);
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
),
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
]);
2391 tls_session_init (multi
, &multi
->session
[src
]);
2393 CLEAR (multi
->session
[src
]);
2395 dmsg (D_TLS_DEBUG
, "TLS: move_session: exit");
2399 reset_session (struct tls_multi
*multi
, struct tls_session
*session
)
2401 tls_session_free (session
, false);
2402 tls_session_init (multi
, session
);
2407 * Transmit a TLS reset on our untrusted channel.
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
));
2422 * Used to determine in how many seconds we should be
2426 compute_earliest_wakeup (interval_t
*earliest
, interval_t seconds_from_now
) {
2427 if (seconds_from_now
< *earliest
)
2428 *earliest
= seconds_from_now
;
2434 * Return true if "lame duck" or retiring key has expired and can
2435 * no longer be used.
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
);
2453 else if (lame
->state
== S_ERROR
)
2460 * A tls_multi object fully encapsulates OpenVPN's TLS state.
2461 * See ssl.h for more comments.
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
];
2486 * Finalize our computation of frame sizes.
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
;
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
2537 tls_multi_init_set_options (struct tls_multi
* multi
,
2542 /* initialize options string */
2543 multi
->opt
.local_options
= local
;
2544 multi
->opt
.remote_options
= remote
;
2549 tls_multi_free (struct tls_multi
*multi
, bool clear
)
2555 #ifdef MANAGEMENT_DEF_AUTH
2556 man_def_auth_set_client_reason(multi
, NULL
);
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);
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
2588 swap_hmac (struct buffer
*buf
, const struct crypto_options
*co
, bool incoming
)
2590 struct key_ctx
*ctx
;
2594 ctx
= (incoming
? &co
->key_ctx_bi
->decrypt
: &co
->key_ctx_bi
->encrypt
);
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
;
2605 uint8_t *b
= BPTR (buf
);
2606 uint8_t buf1
[SWAP_BUF_SIZE
];
2607 uint8_t buf2
[SWAP_BUF_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
);
2635 #undef SWAP_BUF_SIZE
2638 * Write a control channel authentication record.
2641 write_control_auth (struct tls_session
*session
,
2642 struct key_state
*ks
,
2644 struct link_socket_actual
**to_link_addr
,
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.
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))
2685 "TLS Error: cannot locate HMAC in incoming packet from %s",
2686 print_link_socket_actual (from
, &gc
));
2691 /* authenticate only (no decrypt) and remove the hmac record
2692 from the head of the buffer */
2693 openvpn_decrypt (buf
, null
, co
, NULL
);
2697 "TLS Error: incoming packet authentication failed from %s",
2698 print_link_socket_actual (from
, &gc
));
2705 /* advance buffer pointer past opcode & session_id since our caller
2707 buf_advance (buf
, SID_SIZE
+ 1);
2714 * For debugging, print contents of key_source2 structure.
2718 key_source_print (const struct key_source
*k
,
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",
2730 format_hex (k
->pre_master
, sizeof (k
->pre_master
), 0, &gc
));
2731 dmsg (D_SHOW_KEY_SOURCE
,
2734 format_hex (k
->random1
, sizeof (k
->random1
), 0, &gc
));
2735 dmsg (D_SHOW_KEY_SOURCE
,
2738 format_hex (k
->random2
, sizeof (k
->random2
), 0, &gc
));
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],
2761 * SecurityParameters.server_random[32] +
2762 * SecurityParameters.client_random[32]);
2766 * (1) key_block contains a full set of 4 keys.
2767 * (2) The pre-master secret is generated by the client.
2771 tls1_P_hash(const EVP_MD
*md
,
2774 const uint8_t *seed
,
2779 struct gc_arena gc
= gc_new ();
2784 uint8_t A1
[EVP_MAX_MD_SIZE
];
2785 unsigned int A1_len
;
2788 const int olen_orig
= olen
;
2789 const uint8_t *out_orig
= out
;
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
);
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
);
2815 HMAC_Final(&ctx
,out
,&j
);
2818 HMAC_Final(&ctx_tmp
,A1
,&A1_len
); /* calc the next A1 value */
2822 HMAC_Final(&ctx
,A1
,&A1_len
);
2823 memcpy(out
,A1
,olen
);
2827 HMAC_CTX_cleanup(&ctx
);
2828 HMAC_CTX_cleanup(&ctx_tmp
);
2831 dmsg (D_SHOW_KEY_SOURCE
, "tls1_P_hash out: %s", format_hex (out_orig
, olen_orig
, 0, &gc
));
2836 tls1_PRF(uint8_t *label
,
2843 struct gc_arena gc
= gc_new ();
2844 const EVP_MD
*md5
= EVP_md5();
2845 const EVP_MD
*sha1
= EVP_sha1();
2847 const uint8_t *S1
,*S2
;
2850 out2
= (uint8_t *) gc_malloc (olen
, false, &gc
);
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
++)
2864 memset (out2
, 0, olen
);
2866 dmsg (D_SHOW_KEY_SOURCE
, "tls1_PRF out[%d]: %s", olen
, format_hex (out1
, olen
, 0, &gc
));
2872 openvpn_PRF (const uint8_t *secret
,
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
,
2884 /* concatenate seed components */
2886 struct buffer seed
= alloc_buf (strlen (label
)
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
));
2896 ASSERT (buf_write (&seed
, client_sid
->id
, SID_SIZE
));
2898 ASSERT (buf_write (&seed
, server_sid
->id
, SID_SIZE
));
2901 tls1_PRF (BPTR(&seed
), BLEN(&seed
), secret
, secret_len
, output
, output_len
);
2906 VALGRIND_MAKE_READABLE ((void *)output
, output_len
);
2910 * Using source entropy from local and remote hosts, mix into
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
,
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
),
2945 /* compute key expansion */
2946 openvpn_PRF (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
),
2955 (uint8_t*)key2
.keys
,
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");
2973 /* Initialize OpenSSL key contexts */
2975 ASSERT (server
== true || server
== false);
2977 init_key_ctx (&key
->encrypt
,
2978 &key2
.keys
[(int)server
],
2981 "Data Channel Encrypt");
2983 init_key_ctx (&key
->decrypt
,
2984 &key2
.keys
[1-(int)server
],
2987 "Data Channel Decrypt");
2999 random_bytes_to_buf (struct buffer
*buf
,
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
))
3011 key_source2_randomize_write (struct key_source2
*k2
,
3015 struct key_source
*k
= &k2
->client
;
3023 if (!random_bytes_to_buf (buf
, k
->pre_master
, sizeof (k
->pre_master
)))
3027 if (!random_bytes_to_buf (buf
, k
->random1
, sizeof (k
->random1
)))
3029 if (!random_bytes_to_buf (buf
, k
->random2
, sizeof (k
->random2
)))
3036 key_source2_read (struct key_source2
*k2
,
3040 struct key_source
*k
= &k2
->client
;
3049 if (!buf_read (buf
, k
->pre_master
, sizeof (k
->pre_master
)))
3053 if (!buf_read (buf
, k
->random1
, sizeof (k
->random1
)))
3055 if (!buf_read (buf
, k
->random2
, sizeof (k
->random2
)))
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 */
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
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);
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.
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
))
3097 if (!buf_write_u16 (buf
, len
))
3099 if (!buf_write (buf
, str
, len
))
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
)
3110 if (!buf_read (buf
, str
, len
))
3117 * Authenticate a client using username/password.
3120 * If you want to add new authentication methods,
3121 * this is the place to start.
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
= "";
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",
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
);
3170 retval
= openvpn_execve (&argv
, session
->opt
->es
, S_SCRIPT
);
3172 /* test return status of command */
3173 if (system_ok (retval
))
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");
3183 msg (D_TLS_ERRORS
, "TLS Auth Error: peer provided a blank username");
3187 if (strlen (tmp_file
) > 0)
3188 delete_file (tmp_file
);
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
);
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
);
3227 setenv_del (session
->opt
->es
, "password");
3228 setenv_str (session
->opt
->es
, "username", up
->username
);
3232 msg (D_TLS_ERRORS
, "TLS Auth Error (verify_user_pass_plugin): peer provided a blank username");
3239 * MANAGEMENT_DEF_AUTH internal ssl.c status codes
3241 #define KMDA_ERROR 0
3242 #define KMDA_SUCCESS 1
3243 #define KMDA_UNDEF 2
3246 #ifdef MANAGEMENT_DEF_AUTH
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
);
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
;
3275 msg (D_TLS_ERRORS
, "TLS Auth Error (verify_user_pass_management): peer provided a blank username");
3283 * Handle the reading and writing of key data to and from
3284 * the TLS control channel (cleartext).
3288 key_method_1_write (struct buffer
*buf
, struct tls_session
*session
)
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");
3302 if (!write_key (&key
, &session
->opt
->key_type
, buf
))
3304 msg (D_TLS_ERRORS
, "TLS Error: write_key failed");
3308 init_key_ctx (&ks
->key
.encrypt
, &key
, &session
->opt
->key_type
,
3309 DO_ENCRYPT
, "Data Channel Encrypt");
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");
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))
3336 /* write key_method + flags */
3337 if (!buf_write_u8 (buf
, (session
->opt
->key_method
& KEY_METHOD_MASK
)))
3340 /* write key source material */
3341 if (!key_source2_randomize_write (ks
->key_src
, buf
, session
->opt
->server
))
3344 /* write options string */
3346 if (!write_string (buf
, local_options_string (session
), TLS_OPTIONS_LEN
))
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))
3356 if (!write_string (buf
, auth_user_pass
.password
, -1))
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
,
3371 &ks
->session_id_remote
,
3372 &session
->session_id
,
3375 msg (D_TLS_ERRORS
, "TLS Error: server generate_key_expansion failed");
3380 CLEAR (*ks
->key_src
);
3386 msg (D_TLS_ERRORS
, "TLS Error: Key Method #2 write failed");
3387 CLEAR (*ks
->key_src
);
3392 key_method_1_read (struct buffer
*buf
, struct tls_session
*session
)
3397 ASSERT (session
->opt
->key_method
== 1);
3399 if (!session
->verified
)
3402 "TLS Error: Certificate verification failed (key-method 1)");
3406 status
= read_key (&key
, &session
->opt
->key_type
, buf
);
3410 "TLS Error: Error reading data channel key from plaintext buffer");
3414 if (!check_key (&key
, &session
->opt
->key_type
))
3416 msg (D_TLS_ERRORS
, "TLS Error: Bad decrypting key received from peer");
3422 msg (D_TLS_ERRORS
, "TLS Error: Missing options string");
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
);
3438 init_key_ctx (&ks
->key
.decrypt
, &key
, &session
->opt
->key_type
,
3439 DO_DECRYPT
, "Data Channel Decrypt");
3441 ks
->authenticated
= true;
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
;
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
;
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)
3478 "TLS ERROR: Unknown key_method/flags=%d received from remote host",
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");
3491 if (!read_string (buf
, options
, TLS_OPTIONS_LEN
))
3493 msg (D_TLS_ERRORS
, "TLS Error: Failed to read required OCC options string");
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
;
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
))
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");
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
);
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
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;
3559 #ifdef MANAGEMENT_DEF_AUTH
3560 if (man_def_auth
!= KMDA_UNDEF
)
3561 ks
->auth_deferred
= true;
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",
3569 (session
->opt
->ssl_flags
& SSLF_USERNAME_AS_COMMON_NAME
) ? "[CN SET]" : "");
3571 msg (D_HANDSHAKE
, "TLS: Username/Password authentication %s for username '%s' %s",
3574 (session
->opt
->ssl_flags
& SSLF_USERNAME_AS_COMMON_NAME
) ? "[CN SET]" : "");
3579 msg (D_TLS_ERRORS
, "TLS Auth Error: Auth Username/Password verification failed for peer");
3586 if (!session
->verified
)
3589 "TLS Error: Certificate verification failed (key-method 2)");
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",
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");
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;
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
,
3677 &session
->session_id
,
3678 &ks
->session_id_remote
,
3681 msg (D_TLS_ERRORS
, "TLS Error: client generate_key_expansion failed");
3685 CLEAR (*ks
->key_src
);
3692 CLEAR (*ks
->key_src
);
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.
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
,
3723 struct gc_arena gc
= gc_new ();
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);*/
3762 dmsg (D_TLS_DEBUG
, "TLS: tls_process: chg=%d ks=%s lame=%s to_link->len=%d wakeup=%d",
3764 state_name (ks
->state
),
3765 state_name (ks_lame
->state
),
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.
3780 /* Initial handshake */
3781 if (ks
->state
== S_INITIAL
)
3783 buf
= reliable_get_buf_output_sequenced (ks
->send_reliable
);
3786 ks
->must_negotiate
= now
+ session
->opt
->handshake_window
;
3787 ks
->auth_deferred_expire
= now
+ auth_deferred_expire_window (session
->opt
);
3790 reliable_mark_active_outgoing (ks
->send_reliable
, buf
, ks
->initial_opcode
);
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
,
3811 /* Are we timed out on receive? */
3812 if (now
>= ks
->must_negotiate
)
3814 if (ks
->state
< S_ACTIVE
)
3817 "TLS Error: TLS key negotiation failed to occur within %d seconds (check your network connectivity)",
3818 session
->opt
->handshake_window
);
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");
3838 if (((ks
->state
== S_GOT_KEY
&& !session
->opt
->server
) ||
3839 (ks
->state
== S_SENT_KEY
&& session
->opt
->server
)))
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
;
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();
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
))
3867 buf
= reliable_send (ks
->send_reliable
, &opcode
);
3872 write_control_auth (session
, ks
, &b
, to_link_addr
, opcode
,
3873 CONTROL_SEND_ACK_MAX
, true);
3876 state_change
= true;
3877 dmsg (D_TLS_DEBUG
, "Reliable -> TCP/UDP");
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);
3891 state_change
= true;
3892 dmsg (D_TLS_DEBUG
, "Dedicated ACK -> TCP/UDP");
3897 /* Write incoming ciphertext to TLS object */
3898 buf
= reliable_get_buf_sequenced (ks
->rec_reliable
);
3904 status
= key_state_write_ciphertext (multi
, ks
, buf
);
3908 "TLS Error: Incoming Ciphertext -> TLS object write error");
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
;
3930 ASSERT (buf_init (buf
, 0));
3931 status
= key_state_read_plaintext (multi
, ks
, buf
, TLS_CHANNEL_BUF_SIZE
);
3935 msg (D_TLS_ERRORS
, "TLS Error: TLS object -> incoming plaintext read error");
3940 state_change
= true;
3941 dmsg (D_TLS_DEBUG
, "TLS -> Incoming Plaintext");
3943 #if 0 /* show null plaintext reads */
3945 msg (M_INFO
, "TLS plaintext read -> NULL return");
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
))
3959 else if (session
->opt
->key_method
== 2)
3961 if (!key_method_2_write (buf
, session
))
3969 state_change
= true;
3970 dmsg (D_TLS_DEBUG_MED
, "STATE S_SENT_KEY");
3971 ks
->state
= S_SENT_KEY
;
3975 buf
= &ks
->plaintext_read_buf
;
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
))
3985 else if (session
->opt
->key_method
== 2)
3987 if (!key_method_2_read (buf
, multi
, session
))
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
;
4004 int status
= key_state_write_plaintext (multi
, ks
, buf
);
4008 "TLS ERROR: Outgoing Plaintext -> TLS object write error");
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
);
4024 int status
= key_state_read_ciphertext (multi
, ks
, buf
, PAYLOAD_SIZE_DYNAMIC (&multi
->opt
.frame
));
4028 "TLS Error: Ciphertext -> reliable TCP/UDP transport read error");
4033 reliable_mark_active_outgoing (ks
->send_reliable
, buf
, P_CONTROL_V1
);
4035 state_change
= true;
4036 dmsg (D_TLS_DEBUG
, "Outgoing Ciphertext -> Reliable");
4041 /*mutex_cycle (multi->mutex);*/
4043 while (state_change
);
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);
4057 state_change
= true;
4058 dmsg (D_TLS_DEBUG
, "Dedicated ACK -> TCP/UDP");
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 */
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 */
4087 dmsg (D_TLS_DEBUG
, "TLS: tls_process: timeout set to %d", *wakeup
);
4095 ks
->state
= S_ERROR
;
4096 msg (D_TLS_ERRORS
, "TLS Error: TLS handshake failed");
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
,
4119 struct gc_arena gc
= gc_new ();
4121 int active
= TLSMP_INACTIVE
;
4125 perf_push (PERF_TLS_MULTI_PROCESS
);
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
;
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
;
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).
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
;
4188 && ks_lame
->state
>= S_ACTIVE
4189 && !multi
->opt
.single_session
)
4190 move_session (multi
, TM_LAME_DUCK
, TM_ACTIVE
, true);
4192 reset_session (multi
, session
);
4195 /*mutex_cycle (multi->mutex);*/
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.
4231 for (i
= 0; i
< (int) SIZE (multi
->key_scan
); ++i
)
4233 if (multi
->key_scan
[i
]->state
>= S_ACTIVE
)
4236 ++multi
->n_hard_errors
;
4241 /* DEBUGGING -- flood peer with repeating connection attempts */
4243 const int throw_level
= GREMLIN_CONNECTION_FLOOD_LEVEL (multi
->opt
.gremlin
);
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
;
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
4287 * Return true if input was an authenticated control channel
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.
4295 tls_pre_decrypt (struct tls_multi
*multi
,
4296 const struct link_socket_actual
*from
,
4298 struct crypto_options
*opt
)
4300 struct gc_arena gc
= gc_new ();
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
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));
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
));
4358 #if 0 /* keys out of sync? */
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
),
4367 #ifdef ENABLE_DEF_AUTH
4372 link_socket_actual_match (from
, &ks
->remote_addr
));
4378 "TLS Error: local/remote TLS keys are out of sync: %s [%d]",
4379 print_link_socket_actual (from
, &gc
), key_id
);
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
)
4392 "TLS Error: unknown opcode received from %s op=%d",
4393 print_link_socket_actual (from
, &gc
), op
);
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
))
4407 "TLS Error: client->client or server->server connection attempted from %s",
4408 print_link_socket_actual (from
, &gc
));
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
))
4426 "TLS Error: session-id not found in packet from %s",
4427 print_link_socket_actual (from
, &gc
));
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
];
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
))
4451 if (i
== TM_LAME_DUCK
) {
4453 "TLS ERROR: received control packet with stale session-id=%s",
4454 session_id_print (&sid
, &gc
));
4458 "TLS: found match, session[%d], sid=%s",
4459 i
, session_id_print (&sid
, &gc
));
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
));
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
)
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
));
4495 #ifdef ENABLE_MANAGEMENT
4498 management_set_state (management
,
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
));
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
)
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
));
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
));
4546 if (!read_control_auth (buf
, &session
->tls_auth
, from
))
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
));
4561 session
->untrusted_addr
= *from
;
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
)
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
));
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
));
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
))
4600 key_state_soft_reset (session
);
4603 "TLS: received P_CONTROL_SOFT_RESET_V1 s=%d sid=%s",
4604 i
, session_id_print (&sid
, &gc
));
4609 * Remote responding to our key renegotiation request?
4611 if (op
== P_CONTROL_SOFT_RESET_V1
)
4614 if (!read_control_auth (buf
, &session
->tls_auth
, from
))
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 */
4641 * Set our remote address and remote session_id
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
))
4652 "TLS Error: Existing session control channel packet from unknown IP address: %s",
4653 print_link_socket_actual (from
, &gc
));
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;
4669 if (ks
->key_id
!= key_id
)
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
));
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
;
4686 if (!reliable_ack_read (&send_ack
, buf
, &session
->session_id
))
4689 "TLS Error: reading acknowledgement record from packet");
4692 reliable_send_purge (ks
->send_reliable
, &send_ack
);
4695 if (op
!= P_ACK_V1
&& reliable_can_get (ks
->rec_reliable
))
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
);
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
);
4725 opt
->key_ctx_bi
= NULL
;
4726 opt
->packet_id
= NULL
;
4727 opt
->pid_persist
= NULL
;
4728 opt
->flags
&= multi
->opt
.crypto_flags_and
;
4733 ++multi
->n_soft_errors
;
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.
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 ();
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
),
4788 dmsg (D_TLS_STATE_ERRORS
,
4789 "TLS State Error: Unknown key ID (%d) received from %s -- 0 was expected",
4791 print_link_socket_actual (from
, &gc
));
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",
4800 print_link_socket_actual (from
, &gc
),
4801 EXPANDED_SIZE_DYNAMIC (&tas
->frame
));
4806 struct buffer newbuf
= clone_buf (buf
);
4807 struct crypto_options co
= tas
->tls_auth_options
;
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
);
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
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.
4851 /* Choose the key with which to encrypt a data packet */
4853 tls_pre_encrypt (struct tls_multi
*multi
,
4854 struct buffer
*buf
, struct crypto_options
*opt
)
4856 multi
->save_ks
= NULL
;
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
4873 if (now
>= ks
->auth_deferred_expire
)
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
);
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
));
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 */
4910 tls_post_encrypt (struct tls_multi
*multi
, struct buffer
*buf
)
4912 struct key_state
*ks
;
4915 ks
= multi
->save_ks
;
4916 multi
->save_ks
= NULL
;
4920 ASSERT (op
= buf_prepend (buf
, 1));
4921 *op
= (P_DATA_V1
<< P_OPCODE_SHIFT
) | ks
->key_id
;
4923 ks
->n_bytes
+= buf
->len
;
4928 * Send a payload over the TLS control channel.
4929 * Called externally.
4933 tls_send_payload (struct tls_multi
*multi
,
4934 const uint8_t *data
,
4937 struct tls_session
*session
;
4938 struct key_state
*ks
;
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)
4960 tls_rec_payload (struct tls_multi
*multi
,
4963 struct tls_session
*session
;
4964 struct key_state
*ks
;
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
))
4978 ks
->plaintext_read_buf
.len
= 0;
4987 * Dump a human-readable rendition of an openvpn packet
4988 * into a garbage collectable string which is returned.
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
;
5000 int tls_auth_hmac_size
= (flags
& PD_TLS_AUTH_HMAC_SIZE_MASK
);
5004 buf_printf (&out
, "DATA UNDEF len=%d", buf
.len
);
5008 if (!(flags
& PD_TLS
))
5012 * Initial byte (opcode)
5014 if (!buf_read (&buf
, &c
, sizeof (c
)))
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
)
5027 struct session_id sid
;
5029 if (!session_id_read (&sid
, &buf
))
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
))
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))
5052 buf_printf(&out
, " pid=%s", packet_id_net_print (&pin
, (flags
& PD_VERBOSE
), gc
));
5058 buf_printf (&out
, " %s", reliable_ack_print(&buf
, (flags
& PD_VERBOSE
), gc
));
5068 if (!buf_read (&buf
, &l
, sizeof (l
)))
5071 buf_printf (&out
, " pid=" packet_id_format
, (packet_id_print_type
)l
);
5075 if (flags
& PD_SHOW_DATA
)
5076 buf_printf (&out
, " DATA %s", format_hex (BPTR (&buf
), BLEN (&buf
), 80, gc
));
5078 buf_printf (&out
, " DATA len=%d", buf
.len
);
5085 static void dummy(void) {}
5086 #endif /* USE_CRYPTO && USE_SSL*/