OpenVPN
ssl.c
Go to the documentation of this file.
1/*
2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
6 * packet compression.
7 *
8 * Copyright (C) 2002-2026 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2026 Sentyron B.V. <openvpn@sentyron.com>
10 * Copyright (C) 2008-2026 David Sommerseth <dazo@eurephia.org>
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License version 2
14 * as published by the Free Software Foundation.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, see <https://www.gnu.org/licenses/>.
23 */
24
30/*
31 * The routines in this file deal with dynamically negotiating
32 * the data channel HMAC and cipher keys through a TLS session.
33 *
34 * Both the TLS session and the data channel are multiplexed
35 * over the same TCP/UDP port.
36 */
37#ifdef HAVE_CONFIG_H
38#include "config.h"
39#endif
40
41#include "syshead.h"
42#include "win32.h"
43
44#include "error.h"
45#include "common.h"
46#include "socket.h"
47#include "misc.h"
48#include "fdmisc.h"
49#include "interval.h"
50#include "status.h"
51#include "gremlin.h"
52#include "pkcs11.h"
53#include "route.h"
54#include "tls_crypt.h"
55
56#include "crypto_epoch.h"
57#include "ssl.h"
58#include "acc.h"
59#include "ssl_verify.h"
60#include "ssl_backend.h"
61#include "ssl_ncp.h"
62#include "ssl_util.h"
63#include "auth_token.h"
64#include "mss.h"
65#include "dco.h"
66#include "options_string.h"
67
68#include "memdbg.h"
69#include "openvpn.h"
70
71#ifdef MEASURE_TLS_HANDSHAKE_STATS
72
73static int tls_handshake_success; /* GLOBAL */
74static int tls_handshake_error; /* GLOBAL */
75static int tls_packets_generated; /* GLOBAL */
76static int tls_packets_sent; /* GLOBAL */
77
78#define INCR_SENT ++tls_packets_sent
79#define INCR_GENERATED ++tls_packets_generated
80#define INCR_SUCCESS ++tls_handshake_success
81#define INCR_ERROR ++tls_handshake_error
82
83void
84show_tls_performance_stats(void)
85{
86 msg(D_TLS_DEBUG_LOW, "TLS Handshakes, success=%f%% (good=%d, bad=%d), retransmits=%f%%",
87 (double)tls_handshake_success / (tls_handshake_success + tls_handshake_error) * 100.0,
88 tls_handshake_success, tls_handshake_error,
89 (double)(tls_packets_sent - tls_packets_generated) / tls_packets_generated * 100.0);
90}
91#else /* ifdef MEASURE_TLS_HANDSHAKE_STATS */
92
93#define INCR_SENT
94#define INCR_GENERATED
95#define INCR_SUCCESS
96#define INCR_ERROR
97
98#endif /* ifdef MEASURE_TLS_HANDSHAKE_STATS */
99
100/* forward decleration since tls_process needs this function prototype */
101static void
102check_session_buf_not_used(struct buffer *to_link, struct tls_session *session);
103
104static void
105check_keystate_buf_not_used(struct buffer *to_link, const struct key_state *ks);
106
107
115static void
116tls_limit_reneg_bytes(const char *ciphername, int64_t *reneg_bytes)
117{
118 if (cipher_kt_insecure(ciphername))
119 {
120 if (*reneg_bytes == -1) /* Not user-specified */
121 {
122 msg(M_WARN, "WARNING: cipher with small block size in use, "
123 "reducing reneg-bytes to 64MB to mitigate SWEET32 attacks.");
124 *reneg_bytes = 64 * 1024 * 1024;
125 }
126 }
127}
128
129static uint64_t
130tls_get_limit_aead(const char *ciphername, uint64_t override)
131{
132 uint64_t limit = cipher_get_aead_limits(ciphername);
133
134 if (limit == 0 && override == 0)
135 {
136 return 0;
137 }
138
139 /* set limit to 7/8 of the limit so the renegotiation can succeed before
140 * we go over the limit */
141 limit = limit / 8 * 7;
142
143 if (override > 0)
144 {
145 limit = override;
146 }
147
149 "Note: AEAD cipher %s will trigger a renegotiation"
150 " at a sum of %" PRIi64 " blocks and packets.",
151 ciphername, limit);
152 return limit;
153}
154
155#if defined(__GNUC__) || defined(__clang__)
156#pragma GCC diagnostic push
157#pragma GCC diagnostic ignored "-Wsign-conversion"
158#endif
159
160void
162{
163 /*
164 * frame->extra_frame is already initialized with tls_auth buffer requirements,
165 * if --tls-auth is enabled.
166 */
167
168 /* calculates the maximum overhead that control channel frames can have */
169 int overhead = 0;
170
171 /* Socks */
172 overhead += 10;
173
174 /* tls-auth and tls-crypt */
176
177 /* TCP length field and opcode */
178 overhead += 3;
179
180 /* ACK array and remote SESSION ID (part of the ACK array) */
181 overhead += ACK_SIZE(RELIABLE_ACK_SIZE);
182
183 /* Previous OpenVPN version calculated the maximum size and buffer of a
184 * control frame depending on the overhead of the data channel frame
185 * overhead and limited its maximum size to 1250. Since control frames
186 * also need to fit into data channel buffer we have the same
187 * default of 1500 + 100 as data channel buffers have. Increasing
188 * control channel mtu beyond this limit also increases the data channel
189 * buffers */
190 frame->buf.payload_size = max_int(1500, tls_mtu) + 100;
191
192 frame->buf.headroom = overhead;
193 frame->buf.tailroom = overhead;
194
195 frame->tun_mtu = tls_mtu;
196
197 /* Ensure the tun-mtu stays in a valid range */
200}
201
207static size_t
209{
210 const struct key_state *ks = &session->key[KS_PRIMARY];
211 size_t overhead = 0;
212
213 /* opcode */
214 overhead += 1;
215
216 /* our own session id */
217 overhead += SID_SIZE;
218
219 /* ACK array and remote SESSION ID (part of the ACK array) */
220 int ackstosend = reliable_ack_outstanding(ks->rec_ack) + ks->lru_acks->len;
221 overhead += ACK_SIZE(min_int(ackstosend, CONTROL_SEND_ACK_MAX));
222
223 /* Message packet id */
224 overhead += sizeof(packet_id_type);
225
226 if (session->tls_wrap.mode == TLS_WRAP_CRYPT)
227 {
228 overhead += tls_crypt_buf_overhead();
229 }
230 else if (session->tls_wrap.mode == TLS_WRAP_AUTH)
231 {
232 overhead += hmac_ctx_size(session->tls_wrap.opt.key_ctx_bi.encrypt.hmac);
233 overhead += packet_id_size(true);
234 }
235
236 /* Add the typical UDP overhead for an IPv6 UDP packet. TCP+IPv6 has a
237 * larger overhead but the risk of a TCP connection getting dropped because
238 * we try to send a too large packet is basically zero */
239 overhead += datagram_overhead(session->untrusted_addr.dest.addr.sa.sa_family, PROTO_UDP);
240
241 return overhead;
242}
243
244#if defined(__GNUC__) || defined(__clang__)
245#pragma GCC diagnostic pop
246#endif
247
248void
250{
251 tls_init_lib();
252
254}
255
256void
258{
260
261 tls_free_lib();
262}
263
264/*
265 * OpenSSL library calls pem_password_callback if the
266 * private key is protected by a password.
267 */
268
269static struct user_pass passbuf; /* GLOBAL */
270
271void
272pem_password_setup(const char *auth_file)
273{
275 if (!strlen(passbuf.password))
276 {
279 }
280}
281
282int
283pem_password_callback(char *buf, int size, int rwflag, void *u)
284{
285 if (buf)
286 {
287 /* prompt for password even if --askpass wasn't specified */
288 pem_password_setup(NULL);
290 strlcpy(buf, passbuf.password, (size_t)size);
291 purge_user_pass(&passbuf, false);
292
293 return (int)strlen(buf);
294 }
295 return 0;
296}
297
298/*
299 * Auth username/password handling
300 */
301
302static bool auth_user_pass_enabled; /* GLOBAL */
303static struct user_pass auth_user_pass; /* GLOBAL */
304static struct user_pass auth_token; /* GLOBAL */
305
306#ifdef ENABLE_MANAGEMENT
307static char *auth_challenge; /* GLOBAL */
308#endif
309
310void
315
316void
317auth_user_pass_setup(const char *auth_file, bool is_inline, bool username_only,
318 const struct static_challenge_info *sci)
319{
320 unsigned int flags = GET_USER_PASS_MANAGEMENT;
321
322 if (is_inline)
323 {
325 }
326 if (username_only)
327 {
329 }
330
332 {
334#ifdef ENABLE_MANAGEMENT
335 if (auth_challenge) /* dynamic challenge/response */
336 {
339 }
340 else if (sci) /* static challenge response */
341 {
343 if (sci->flags & SC_ECHO)
344 {
346 }
347 if (sci->flags & SC_CONCAT)
348 {
350 }
352 }
353 else
354#endif /* ifdef ENABLE_MANAGEMENT */
355 {
356 get_user_pass(&auth_user_pass, auth_file, UP_TYPE_AUTH, flags);
357 }
358 }
359}
360
361/*
362 * Disable password caching
363 */
364void
366{
367 passbuf.nocache = true;
368 auth_user_pass.nocache = true;
369}
370
371/*
372 * Get the password caching
373 */
374bool
376{
377 return passbuf.nocache;
378}
379
380/*
381 * Set an authentication token
382 */
383void
384ssl_set_auth_token(const char *token)
385{
386 set_auth_token(&auth_token, token);
387}
388
389void
394
395/*
396 * Cleans an auth token and checks if it was active
397 */
398bool
400{
401 bool wasdefined = auth_token.defined;
403 return wasdefined;
404}
405
406/*
407 * Forget private key password AND auth-user-pass username/password.
408 */
409void
410ssl_purge_auth(const bool auth_user_pass_only)
411{
412 if (!auth_user_pass_only)
413 {
414#ifdef ENABLE_PKCS11
415 pkcs11_logout();
416#endif
417 purge_user_pass(&passbuf, true);
418 }
420#ifdef ENABLE_MANAGEMENT
422#endif
423}
424
425#ifdef ENABLE_MANAGEMENT
426
427void
429{
430 free(auth_challenge);
431 auth_challenge = NULL;
432}
433
434void
435ssl_put_auth_challenge(const char *cr_str)
436{
438 auth_challenge = string_alloc(cr_str, NULL);
439}
440
441#endif
442
443/*
444 * Parse a TLS version string, returning a TLS_VER_x constant.
445 * If version string is not recognized and extra == "or-highest",
446 * return tls_version_max().
447 */
448int
449tls_version_parse(const char *vstr, const char *extra)
450{
451 const int max_version = tls_version_max();
452 if (!strcmp(vstr, "1.0") && TLS_VER_1_0 <= max_version)
453 {
454 return TLS_VER_1_0;
455 }
456 else if (!strcmp(vstr, "1.1") && TLS_VER_1_1 <= max_version)
457 {
458 return TLS_VER_1_1;
459 }
460 else if (!strcmp(vstr, "1.2") && TLS_VER_1_2 <= max_version)
461 {
462 return TLS_VER_1_2;
463 }
464 else if (!strcmp(vstr, "1.3") && TLS_VER_1_3 <= max_version)
465 {
466 return TLS_VER_1_3;
467 }
468 else if (extra && !strcmp(extra, "or-highest"))
469 {
470 return max_version;
471 }
472 else
473 {
474 return TLS_VER_BAD;
475 }
476}
477
489static void
490tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file, bool crl_file_inline)
491{
492 /* if something goes wrong with stat(), we'll store 0 as mtime */
493 platform_stat_t crl_stat = { 0 };
494
495 /*
496 * an inline CRL can't change at runtime, therefore there is no need to
497 * reload it. It will be reloaded upon config change + SIGHUP.
498 * Use always '1' as dummy timestamp in this case: it will trigger the
499 * first load, but will prevent any future reload.
500 */
501 if (crl_file_inline)
502 {
503 crl_stat.st_mtime = 1;
504 }
505 else if (platform_stat(crl_file, &crl_stat) < 0)
506 {
507 /* If crl_last_mtime is zero, the CRL file has not been read before. */
508 if (ssl_ctx->crl_last_mtime == 0)
509 {
510 msg(M_FATAL, "ERROR: Failed to stat CRL file during initialization, exiting.");
511 }
512 else
513 {
514 msg(M_WARN, "WARNING: Failed to stat CRL file, not reloading CRL.");
515 }
516 return;
517 }
518
519 /*
520 * Store the CRL if this is the first time or if the file was changed since
521 * the last load.
522 * Note: Windows does not support tv_nsec.
523 */
524 if ((ssl_ctx->crl_last_size == crl_stat.st_size)
525 && (ssl_ctx->crl_last_mtime == crl_stat.st_mtime))
526 {
527 return;
528 }
529
530 ssl_ctx->crl_last_mtime = crl_stat.st_mtime;
531 ssl_ctx->crl_last_size = crl_stat.st_size;
532 backend_tls_ctx_reload_crl(ssl_ctx, crl_file, crl_file_inline);
533}
534
535/*
536 * Initialize SSL context.
537 * All files are in PEM format.
538 */
539struct tls_root_ctx *
540init_ssl(const struct options *options, bool in_chroot)
541{
543
545 {
547 }
548
549 struct tls_root_ctx *new_ctx;
550 ALLOC_OBJ_CLEAR(new_ctx, struct tls_root_ctx);
551
552 tls_ctx_new(new_ctx);
553
555 {
557 }
558
559 /* Restrict allowed certificate crypto algorithms */
561
562 /* Allowable ciphers */
563 /* Since @SECLEVEL also influences loading of certificates, set the
564 * cipher restrictions before loading certificates */
567
568 /* Set the allow groups/curves for TLS if we want to override them */
569 if (options->tls_groups)
570 {
572 }
573
574 if (!tls_ctx_set_options(new_ctx, options->ssl_flags))
575 {
576 goto err;
577 }
578
579 if (options->pkcs12_file)
580 {
581 if (0
583 !options->ca_file))
584 {
585 goto err;
586 }
587 }
588#ifdef ENABLE_PKCS11
589 else if (options->pkcs11_providers[0])
590 {
591 if (!tls_ctx_use_pkcs11(new_ctx, options->pkcs11_id_management, options->pkcs11_id))
592 {
593 msg(M_WARN, "Cannot load certificate \"%s\" using PKCS#11 interface",
594 options->pkcs11_id);
595 goto err;
596 }
597 }
598#endif
599#ifdef ENABLE_CRYPTOAPI
600 else if (options->cryptoapi_cert)
601 {
603 }
604#endif
605#ifdef ENABLE_MANAGEMENT
607 {
609 tls_ctx_load_cert_file(new_ctx, cert, true);
610 free(cert);
611 }
612#endif
613 else if (options->cert_file)
614 {
616 }
617
619 {
620 if (0
623 {
624 goto err;
625 }
626 }
627#ifdef ENABLE_MANAGEMENT
629 {
631 {
632 msg(M_WARN, "Cannot initialize mamagement-external-key");
633 goto err;
634 }
635 }
636#endif
637
639 {
642 }
643
644 /* Load extra certificates that are part of our own certificate
645 * chain but shouldn't be included in the verify chain */
647 {
650 }
651
652 /* Check certificate notBefore and notAfter */
654
655 /* Read CRL */
657 {
658 /* If we're running with the chroot option, we may run init_ssl() before
659 * and after chroot-ing. We can use the crl_file path as-is if we're
660 * not going to chroot, or if we already are inside the chroot.
661 *
662 * If we're going to chroot later, we need to prefix the path of the
663 * chroot directory to crl_file.
664 */
665 if (!options->chroot_dir || in_chroot || options->crl_file_inline)
666 {
668 }
669 else
670 {
671 struct gc_arena gc = gc_new();
674 gc_free(&gc);
675 }
676 }
677
678 /* Once keys and cert are loaded, load ECDH parameters */
679 if (options->tls_server)
680 {
682 }
683
685 return new_ctx;
686
687err:
690 free(new_ctx);
691 return NULL;
692}
693
694/*
695 * Map internal constants to ascii names.
696 */
697static const char *
698state_name(int state)
699{
700 switch (state)
701 {
702 case S_UNDEF:
703 return "S_UNDEF";
704
705 case S_INITIAL:
706 return "S_INITIAL";
707
708 case S_PRE_START_SKIP:
709 return "S_PRE_START_SKIP";
710
711 case S_PRE_START:
712 return "S_PRE_START";
713
714 case S_START:
715 return "S_START";
716
717 case S_SENT_KEY:
718 return "S_SENT_KEY";
719
720 case S_GOT_KEY:
721 return "S_GOT_KEY";
722
723 case S_ACTIVE:
724 return "S_ACTIVE";
725
726 case S_ERROR:
727 return "S_ERROR";
728
729 case S_ERROR_PRE:
730 return "S_ERROR_PRE";
731
732 case S_GENERATED_KEYS:
733 return "S_GENERATED_KEYS";
734
735 default:
736 return "S_???";
737 }
738}
739
740static const char *
742{
743 switch (auth)
744 {
745 case KS_AUTH_TRUE:
746 return "KS_AUTH_TRUE";
747
748 case KS_AUTH_DEFERRED:
749 return "KS_AUTH_DEFERRED";
750
751 case KS_AUTH_FALSE:
752 return "KS_AUTH_FALSE";
753
754 default:
755 return "KS_????";
756 }
757}
758
759static const char *
761{
762 switch (index)
763 {
764 case TM_ACTIVE:
765 return "TM_ACTIVE";
766
767 case TM_INITIAL:
768 return "TM_INITIAL";
769
770 case TM_LAME_DUCK:
771 return "TM_LAME_DUCK";
772
773 default:
774 return "TM_???";
775 }
776}
777
778/*
779 * For debugging.
780 */
781static const char *
782print_key_id(struct tls_multi *multi, struct gc_arena *gc)
783{
784 struct buffer out = alloc_buf_gc(256, gc);
785
786 for (int i = 0; i < KEY_SCAN_SIZE; ++i)
787 {
788 struct key_state *ks = get_key_scan(multi, i);
789 buf_printf(&out, " [key#%d state=%s auth=%s id=%d sid=%s]", i, state_name(ks->state),
792 }
793
794 return BSTR(&out);
795}
796
797bool
799{
802 {
803 return true;
804 }
805
806 return false;
807}
808
809#if defined(__GNUC__) || defined(__clang__)
810#pragma GCC diagnostic push
811#pragma GCC diagnostic ignored "-Wsign-conversion"
812#endif
813
837static void
839{
840 update_time();
841
842 CLEAR(*ks);
843
844 /*
845 * Build TLS object that reads/writes ciphertext
846 * to/from memory BIOs.
847 */
848 key_state_ssl_init(&ks->ks_ssl, session->opt->ssl_ctx, session->opt->server, session);
849
850 /* Set control-channel initiation mode */
851 ks->initial_opcode = session->initial_opcode;
852 session->initial_opcode = P_CONTROL_SOFT_RESET_V1;
853 ks->state = S_INITIAL;
854 ks->key_id = session->key_id;
855
856 /*
857 * key_id increments to KEY_ID_MASK then recycles back to 1.
858 * This way you know that if key_id is 0, it is the first key.
859 */
860 ++session->key_id;
861 session->key_id &= P_KEY_ID_MASK;
862 if (!session->key_id)
863 {
864 session->key_id = 1;
865 }
866
867 /* allocate key source material object */
869
870 /* allocate reliability objects */
875
876 /* allocate buffers */
879 ks->ack_write_buf = alloc_buf(BUF_SIZE(&session->opt->frame));
880 reliable_init(ks->send_reliable, BUF_SIZE(&session->opt->frame),
881 session->opt->frame.buf.headroom, TLS_RELIABLE_N_SEND_BUFFERS,
882 ks->key_id ? false : session->opt->xmit_hold);
883 reliable_init(ks->rec_reliable, BUF_SIZE(&session->opt->frame),
884 session->opt->frame.buf.headroom, TLS_RELIABLE_N_REC_BUFFERS, false);
885 reliable_set_timeout(ks->send_reliable, session->opt->packet_timeout);
886
887 /* init packet ID tracker */
888 packet_id_init(&ks->crypto_options.packet_id, session->opt->replay_window,
889 session->opt->replay_time, "SSL", ks->key_id);
890
891#ifdef ENABLE_MANAGEMENT
892 ks->mda_key_id = session->opt->mda_context->mda_key_id_counter++;
893#endif
894
895 /*
896 * Attempt CRL reload before TLS negotiation. Won't be performed if
897 * the file was not modified since the last reload. This affects
898 * all instances (all instances share the same context).
899 */
900 if (session->opt->crl_file && !(session->opt->ssl_flags & SSLF_CRL_VERIFY_DIR))
901 {
902 tls_ctx_reload_crl(session->opt->ssl_ctx, session->opt->crl_file,
903 session->opt->crl_file_inline);
904 }
905}
906
907
924static void
925key_state_free(struct key_state *ks, bool clear, struct buffer *to_link)
926{
927 check_keystate_buf_not_used(to_link, ks);
928
929 ks->state = S_UNDEF;
930
932
939
942
943 free(ks->rec_ack);
944 free(ks->lru_acks);
945 if (ks->key_src)
946 {
947 secure_memzero(ks->key_src, sizeof(*ks->key_src));
948 }
949 free(ks->key_src);
950
952
955
956 if (clear)
957 {
958 secure_memzero(ks, sizeof(*ks));
959 }
960}
961
975static inline bool
977{
978 return (session->opt->auth_user_pass_verify_script
982#endif
983 );
984}
985
986
1007static void
1009{
1010 struct gc_arena gc = gc_new();
1011
1012 dmsg(D_TLS_DEBUG, "TLS: tls_session_init: entry");
1013
1014 CLEAR(*session);
1015
1016 /* Set options data to point to parent's option structure */
1017 session->opt = &multi->opt;
1018
1019 /* Randomize session # if it is 0 */
1020 while (!session_id_defined(&session->session_id))
1021 {
1022 session_id_random(&session->session_id);
1023 }
1024
1025 /* Are we a TLS server or client? */
1026 if (session->opt->server)
1027 {
1028 session->initial_opcode = P_CONTROL_HARD_RESET_SERVER_V2;
1029 }
1030 else
1031 {
1032 session->initial_opcode = session->opt->tls_crypt_v2 ? P_CONTROL_HARD_RESET_CLIENT_V3
1034 }
1035
1036 /* Initialize control channel authentication parameters */
1037 session->tls_wrap = session->opt->tls_wrap;
1038 session->tls_wrap.work = alloc_buf(BUF_SIZE(&session->opt->frame));
1039
1040 /* initialize packet ID replay window for --tls-auth */
1041 packet_id_init(&session->tls_wrap.opt.packet_id, session->opt->replay_window,
1042 session->opt->replay_time, "TLS_WRAP", session->key_id);
1043
1044 /* If we are using tls-crypt-v2 we manipulate the packet id to be (ab)used
1045 * to indicate early protocol negotiation */
1046 if (session->opt->tls_crypt_v2)
1047 {
1048 session->tls_wrap.opt.packet_id.send.time = now;
1049 session->tls_wrap.opt.packet_id.send.id = EARLY_NEG_START;
1050 }
1051
1053
1054 dmsg(D_TLS_DEBUG, "TLS: tls_session_init: new session object, sid=%s",
1055 session_id_print(&session->session_id, &gc));
1056
1057 gc_free(&gc);
1058}
1059
1060#if defined(__GNUC__) || defined(__clang__)
1061#pragma GCC diagnostic pop
1062#endif
1063
1081static void
1082tls_session_free(struct tls_session *session, bool clear, struct buffer *to_link)
1083{
1085 tls_wrap_free(&session->tls_wrap);
1086 tls_wrap_free(&session->tls_wrap_reneg);
1087
1088 for (size_t i = 0; i < KS_SIZE; ++i)
1089 {
1090 /* we don't need clear=true for this call since
1091 * the structs are part of session and get cleared
1092 * as part of session */
1093 key_state_free(&session->key[i], false, to_link);
1094 }
1095
1096 free(session->common_name);
1097
1098 cert_hash_free(session->cert_hash_set);
1099
1100 if (clear)
1101 {
1102 secure_memzero(session, sizeof(*session));
1103 }
1104}
1105
1111static void
1112move_session(struct tls_multi *multi, int dest, int src, bool reinit_src,
1113 struct buffer *to_link)
1114{
1115 check_session_buf_not_used(to_link, &multi->session[dest]);
1116 msg(D_TLS_DEBUG_LOW, "TLS: move_session: dest=%s src=%s reinit_src=%d",
1117 session_index_name(dest), session_index_name(src), reinit_src);
1118 ASSERT(src != dest);
1119 ASSERT(src >= 0 && src < TM_SIZE);
1120 ASSERT(dest >= 0 && dest < TM_SIZE);
1121 tls_session_free(&multi->session[dest], false, to_link);
1122 multi->session[dest] = multi->session[src];
1123
1124 if (reinit_src)
1125 {
1126 tls_session_init(multi, &multi->session[src]);
1127 }
1128 else
1129 {
1130 secure_memzero(&multi->session[src], sizeof(multi->session[src]));
1131 }
1132
1133 dmsg(D_TLS_DEBUG, "TLS: move_session: exit");
1134}
1135
1136static void
1137reset_session(struct tls_multi *multi, struct tls_session *session, struct buffer *to_link)
1138{
1139 tls_session_free(session, false, to_link);
1140 tls_session_init(multi, session);
1141}
1142
1143/*
1144 * Used to determine in how many seconds we should be
1145 * called again.
1146 */
1147static inline void
1148compute_earliest_wakeup(interval_t *earliest, time_t seconds_from_now)
1149{
1150 if (seconds_from_now < *earliest)
1151 {
1152 *earliest = (interval_t)seconds_from_now;
1153 }
1154 if (*earliest < 0)
1155 {
1156 *earliest = 0;
1157 }
1158}
1159
1160/*
1161 * Return true if "lame duck" or retiring key has expired and can
1162 * no longer be used.
1163 */
1164static inline bool
1166{
1167 const struct key_state *lame = &session->key[KS_LAME_DUCK];
1168 if (lame->state >= S_INITIAL)
1169 {
1170 ASSERT(lame->must_die); /* a lame duck key must always have an expiration */
1171 if (now < lame->must_die)
1172 {
1173 compute_earliest_wakeup(wakeup, lame->must_die - now);
1174 return false;
1175 }
1176 else
1177 {
1178 return true;
1179 }
1180 }
1181 else if (lame->state == S_ERROR)
1182 {
1183 return true;
1184 }
1185 else
1186 {
1187 return false;
1188 }
1189}
1190
1191struct tls_multi *
1193{
1194 struct tls_multi *ret;
1195
1196 ALLOC_OBJ_CLEAR(ret, struct tls_multi);
1197
1198 /* get command line derived options */
1199 ret->opt = *tls_options;
1200 ret->dco_peer_id = -1;
1201 ret->use_asymmetric_peer_id = false;
1202 /* The rx_peer_id is also used to identify DCO clients */
1203 ret->rx_peer_id = MAX_PEER_ID;
1204 ret->tx_peer_id = MAX_PEER_ID;
1205
1206 return ret;
1207}
1208
1209void
1210tls_multi_init_finalize(struct tls_multi *multi, int tls_mtu)
1211{
1213 /* initialize the active and untrusted sessions */
1214
1215 tls_session_init(multi, &multi->session[TM_ACTIVE]);
1216 tls_session_init(multi, &multi->session[TM_INITIAL]);
1217
1218 if (!multi->opt.dco_enabled)
1219 {
1220 /* Calculate the asymmetric peer-id */
1221 if (multi->rx_peer_id == MAX_PEER_ID && multi->session[TM_INITIAL].opt->mode != MODE_SERVER)
1222 {
1223 multi->rx_peer_id = (uint32_t)(get_random() % (MAX_PEER_ID - 1));
1224 }
1225 }
1226}
1227
1228/*
1229 * Initialize and finalize a standalone tls-auth verification object.
1230 */
1231
1232struct tls_auth_standalone *
1234{
1235 struct tls_auth_standalone *tas;
1236
1238
1240
1241 /*
1242 * Standalone tls-auth is in read-only mode with respect to TLS
1243 * control channel state. After we build a new client instance
1244 * object, we will process this session-initiating packet for real.
1245 */
1247
1248 /* get initial frame parms, still need to finalize */
1249 tas->frame = tls_options->frame;
1250
1252 tls_options->replay_time, "TAS", 0);
1253
1254 return tas;
1255}
1256
1257void
1259{
1260 if (!tas)
1261 {
1262 return;
1263 }
1264
1266}
1267
1268/*
1269 * Set local and remote option compatibility strings.
1270 * Used to verify compatibility of local and remote option
1271 * sets.
1272 */
1273void
1274tls_multi_init_set_options(struct tls_multi *multi, const char *local, const char *remote)
1275{
1276 /* initialize options string */
1277 multi->opt.local_options = local;
1278 multi->opt.remote_options = remote;
1279}
1280
1281/*
1282 * Cleanup a tls_multi structure and free associated memory allocations.
1283 */
1284void
1285tls_multi_free(struct tls_multi *multi, bool clear)
1286{
1287 ASSERT(multi);
1288
1289 auth_set_client_reason(multi, NULL);
1290
1291 free(multi->peer_info);
1292 free(multi->locked_cn);
1293 free(multi->locked_username);
1294 free(multi->locked_original_username);
1295 free(multi->acc_negotiated_protocols);
1296
1298
1299 wipe_auth_token(multi);
1300
1301 free(multi->remote_ciphername);
1302
1303 for (int i = 0; i < TM_SIZE; ++i)
1304 {
1305 tls_session_free(&multi->session[i], false, NULL);
1306 }
1307
1308 if (clear)
1309 {
1310 secure_memzero(multi, sizeof(*multi));
1311 }
1312
1313 free(multi);
1314}
1315
1316/*
1317 * For debugging, print contents of key_source2 structure.
1318 */
1319
1320static void
1321key_source_print(const struct key_source *k, const char *prefix)
1322{
1323 struct gc_arena gc = gc_new();
1324
1325 VALGRIND_MAKE_READABLE((void *)k->pre_master, sizeof(k->pre_master));
1326 VALGRIND_MAKE_READABLE((void *)k->random1, sizeof(k->random1));
1327 VALGRIND_MAKE_READABLE((void *)k->random2, sizeof(k->random2));
1328
1329 dmsg(D_SHOW_KEY_SOURCE, "%s pre_master: %s", prefix,
1330 format_hex(k->pre_master, sizeof(k->pre_master), 0, &gc));
1331 dmsg(D_SHOW_KEY_SOURCE, "%s random1: %s", prefix,
1332 format_hex(k->random1, sizeof(k->random1), 0, &gc));
1333 dmsg(D_SHOW_KEY_SOURCE, "%s random2: %s", prefix,
1334 format_hex(k->random2, sizeof(k->random2), 0, &gc));
1335
1336 gc_free(&gc);
1337}
1338
1339static void
1341{
1342 key_source_print(&k->client, "Client");
1343 key_source_print(&k->server, "Server");
1344}
1345
1346#if defined(__GNUC__) || defined(__clang__)
1347#pragma GCC diagnostic push
1348#pragma GCC diagnostic ignored "-Wsign-conversion"
1349#endif
1350
1351static bool
1352openvpn_PRF(const uint8_t *secret, size_t secret_len, const char *label, const uint8_t *client_seed,
1353 size_t client_seed_len, const uint8_t *server_seed, size_t server_seed_len,
1354 const struct session_id *client_sid, const struct session_id *server_sid,
1355 uint8_t *output, size_t output_len)
1356{
1357 /* concatenate seed components */
1358
1359 struct buffer seed =
1361
1365
1366 if (client_sid)
1367 {
1369 }
1370 if (server_sid)
1371 {
1373 }
1374
1375 /* compute PRF */
1377
1378 buf_clear(&seed);
1379 free_buf(&seed);
1380
1382 return ret;
1383}
1384
1385static void
1386init_epoch_keys(struct key_state *ks, struct tls_multi *multi, const struct key_type *key_type,
1387 bool server, const struct key2 *key2)
1388{
1389 /* For now we hardcode this to be 4 for the software based data channel
1390 * DCO based implementations/HW implementation might adjust this number
1391 * based on their expected speed.
1392 *
1393 * One epoch lasts 910 GiB with 128 byte packets or 78s at 100 GBit/s.
1394 * (respectively 1011 GiB and 86s with 1280 byte packets).
1395 */
1396 const uint8_t future_key_count = 4;
1397
1398 int key_direction = server ? KEY_DIRECTION_INVERSE : KEY_DIRECTION_NORMAL;
1399 struct key_direction_state kds;
1400 key_direction_state_init(&kds, key_direction);
1401
1402 struct crypto_options *co = &ks->crypto_options;
1403
1404 /* For the epoch key we use the first 32 bytes of key2 cipher keys
1405 * for the initial secret */
1406 struct epoch_key e1_send = { 0 };
1407 e1_send.epoch = 1;
1408 memcpy(&e1_send.epoch_key, key2->keys[kds.out_key].cipher, sizeof(e1_send.epoch_key));
1409
1410 struct epoch_key e1_recv = { 0 };
1411 e1_recv.epoch = 1;
1412 memcpy(&e1_recv.epoch_key, key2->keys[kds.in_key].cipher, sizeof(e1_recv.epoch_key));
1413
1414 /* DCO implementations have two choices at this point.
1415 *
1416 * a) (more likely) they probably to pass E1 directly to kernel
1417 * space at this point and do all the other key derivation in kernel
1418 *
1419 * b) They let userspace do the key derivation and pass all the individual
1420 * keys to the DCO layer.
1421 * */
1422 epoch_init_key_ctx(co, key_type, &e1_send, &e1_recv, future_key_count);
1423
1424 if (multi->opt.aead_usage_limit_override)
1425 {
1427 }
1428
1429 secure_memzero(&e1_send, sizeof(e1_send));
1430 secure_memzero(&e1_recv, sizeof(e1_recv));
1431}
1432
1447
1448static enum key_gen_status
1449init_key_contexts(struct key_state *ks, struct tls_multi *multi, const struct key_type *key_type,
1450 bool server, const struct key2 *key2, bool dco)
1451{
1452 struct key_ctx_bi *key = &ks->crypto_options.key_ctx_bi;
1453
1454 /* Initialize key contexts */
1455 int key_direction = server ? KEY_DIRECTION_INVERSE : KEY_DIRECTION_NORMAL;
1456
1457 if (dco)
1458 {
1459 if (key->encrypt.hmac)
1460 {
1461 msg(M_FATAL, "FATAL: DCO does not support --auth");
1462 }
1463
1464 int ret = init_key_dco_bi(multi, ks, key2, key_direction, key_type->cipher, server);
1465 if (ret < 0)
1466 {
1467 /* This normally means the DCO peer is gone from the kernel while
1468 * userspace still believes it exists. Do not take the whole
1469 * process down over a single peer: report the desync so that the
1470 * connection is restarted and the peer re-created from scratch */
1471 msg(M_WARN,
1472 "Impossible to install key material in DCO: %s. The underlying "
1473 "DCO peer may have been deleted from the kernel without "
1474 "notifying userspace. Restarting the session.",
1475 strerror(-ret));
1476 return KEY_GEN_DCO_DESYNC;
1477 }
1478
1479 /* encrypt/decrypt context are unused with DCO */
1480 CLEAR(key->encrypt);
1481 CLEAR(key->decrypt);
1482 key->initialized = true;
1483 }
1484 else if (multi->opt.crypto_flags & CO_EPOCH_DATA_KEY_FORMAT)
1485 {
1487 {
1488 /* The pulled options are validated in do_deferred_options(), so
1489 * reaching this point means a code path escaped that check. Fail
1490 * the session instead of the whole process */
1492 "TLS Error: AEAD cipher (currently %s) "
1493 "required for epoch data format.",
1495 return KEY_GEN_FAILED;
1496 }
1497 init_epoch_keys(ks, multi, key_type, server, key2);
1498 }
1499 else
1500 {
1501 init_key_ctx_bi(key, key2, key_direction, key_type, "Data Channel");
1502 }
1503
1504 return KEY_GEN_OK;
1505}
1506
1507static bool
1509{
1512 sizeof(key2->keys)))
1513 {
1514 return false;
1515 }
1516 key2->n = 2;
1517
1518 return true;
1519}
1520
1521static bool
1523{
1524 uint8_t master[48] = { 0 };
1525 bool ret = false;
1526
1527 const struct key_state *ks = &session->key[KS_PRIMARY];
1528 const struct key_source2 *key_src = ks->key_src;
1529
1530 const struct session_id *client_sid =
1531 session->opt->server ? &ks->session_id_remote : &session->session_id;
1532 const struct session_id *server_sid =
1533 !session->opt->server ? &ks->session_id_remote : &session->session_id;
1534
1535 /* debugging print of source key material */
1536 key_source2_print(key_src);
1537
1538 /* compute master secret */
1539 if (!openvpn_PRF(key_src->client.pre_master, sizeof(key_src->client.pre_master),
1540 KEY_EXPANSION_ID " master secret", key_src->client.random1,
1541 sizeof(key_src->client.random1), key_src->server.random1,
1542 sizeof(key_src->server.random1), NULL, NULL, master, sizeof(master)))
1543 {
1544 goto exit;
1545 }
1546
1547 /* compute key expansion */
1548 if (!openvpn_PRF(master, sizeof(master), KEY_EXPANSION_ID " key expansion",
1549 key_src->client.random2, sizeof(key_src->client.random2),
1550 key_src->server.random2, sizeof(key_src->server.random2), client_sid,
1551 server_sid, (uint8_t *)key2->keys, sizeof(key2->keys)))
1552 {
1553 goto exit;
1554 }
1555
1556 key2->n = 2;
1557 ret = true;
1558
1559exit:
1560 secure_memzero(&master, sizeof(master));
1561 return ret;
1562}
1563
1564/*
1565 * Using source entropy from local and remote hosts, mix into
1566 * master key.
1567 */
1568static enum key_gen_status
1570{
1571 const struct key_ctx_bi *key = &ks->crypto_options.key_ctx_bi;
1572 enum key_gen_status ret = KEY_GEN_FAILED;
1573 struct key2 key2;
1574
1575 if (key->initialized)
1576 {
1577 msg(D_TLS_ERRORS, "TLS Error: key already initialized");
1578 goto exit;
1579 }
1580
1581 bool server = session->opt->server;
1582
1583 if (session->opt->crypto_flags & CO_USE_TLS_KEY_MATERIAL_EXPORT)
1584 {
1586 {
1587 msg(D_TLS_ERRORS, "TLS Error: Keying material export failed");
1588 goto exit;
1589 }
1590 }
1591 else
1592 {
1594 {
1595 msg(D_TLS_ERRORS, "TLS Error: PRF calculation failed. Your system "
1596 "might not support the old TLS 1.0 PRF calculation anymore or "
1597 "the policy does not allow it (e.g. running in FIPS mode). "
1598 "The peer did not announce support for the modern TLS Export "
1599 "feature that replaces the TLS 1.0 PRF (requires OpenVPN "
1600 "2.6.x or higher)");
1601 goto exit;
1602 }
1603 }
1604
1605 key2_print(&key2, &session->opt->key_type, "Master Encrypt", "Master Decrypt");
1606
1607 /* check for weak keys */
1608 check_key2(&key2);
1609 ret = init_key_contexts(ks, multi, &session->opt->key_type, server, &key2,
1610 session->opt->dco_enabled);
1611
1612exit:
1613 secure_memzero(&key2, sizeof(key2));
1614
1615 return ret;
1616}
1617
1624static enum key_gen_status
1626{
1627 enum key_gen_status ret = KEY_GEN_FAILED;
1628 struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
1629
1630 if (ks->authenticated <= KS_AUTH_FALSE)
1631 {
1632 msg(D_TLS_ERRORS, "TLS Error: key_state not authenticated");
1633 goto cleanup;
1634 }
1635
1636 ks->crypto_options.flags = session->opt->crypto_flags;
1637
1638 ret = generate_key_expansion(multi, ks, session);
1639 if (ret != KEY_GEN_OK)
1640 {
1641 msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
1642 goto cleanup;
1643 }
1644 tls_limit_reneg_bytes(session->opt->key_type.cipher, &session->opt->renegotiate_bytes);
1645
1646 session->opt->aead_usage_limit = tls_get_limit_aead(session->opt->key_type.cipher, session->opt->aead_usage_limit_override);
1647
1648 /* set the state of the keys for the session to generated */
1649 ks->state = S_GENERATED_KEYS;
1650
1651cleanup:
1652 secure_memzero(ks->key_src, sizeof(*ks->key_src));
1653 return ret;
1654}
1655
1656bool
1658 const struct options *options, struct frame *frame,
1659 struct frame *frame_fragment,
1660 const struct link_socket_info *lsi,
1661 dco_context_t *dco)
1662{
1663 if (session->key[KS_PRIMARY].crypto_options.key_ctx_bi.initialized)
1664 {
1665 /* keys already generated, nothing to do */
1666 return true;
1667 }
1668
1669 init_key_type(&session->opt->key_type, options->ciphername, options->authname, true);
1670
1671 bool packet_id_long_form = cipher_kt_mode_ofb_cfb(session->opt->key_type.cipher);
1672 session->opt->crypto_flags &= ~(CO_PACKET_ID_LONG_FORM);
1673 if (packet_id_long_form)
1674 {
1675 session->opt->crypto_flags |= CO_PACKET_ID_LONG_FORM;
1676 }
1677
1678 frame_calculate_dynamic(frame, &session->opt->key_type, options, lsi);
1679
1680 frame_print(frame, D_MTU_INFO, "Data Channel MTU parms");
1681
1682 /*
1683 * mssfix uses data channel framing, which at this point contains
1684 * actual overhead. Fragmentation logic uses frame_fragment, which
1685 * still contains worst case overhead. Replace it with actual overhead
1686 * to prevent unneeded fragmentation.
1687 */
1688
1689 if (frame_fragment)
1690 {
1691 frame_calculate_dynamic(frame_fragment, &session->opt->key_type, options, lsi);
1692 frame_print(frame_fragment, D_MTU_INFO, "Fragmentation MTU parms");
1693 }
1694
1695 if (session->key[KS_PRIMARY].key_id == 0
1696 && session->opt->crypto_flags & CO_USE_DYNAMIC_TLS_CRYPT)
1697 {
1698 /* If dynamic tls-crypt has been negotiated, and we are on the
1699 * first session (key_id = 0), generate a tls-crypt key for the
1700 * following renegotiations */
1702 {
1703 return false;
1704 }
1705 }
1706
1707 if (dco_enabled(options))
1708 {
1709 /* dco_set_peer() must be called if either keepalive, ping, ping-restart,
1710 * ping-exit or mssfix are set to update in-kernel config */
1712 {
1713 int ret = dco_set_peer(dco, multi->dco_peer_id, options->ping_send_timeout,
1715 if (ret < 0)
1716 {
1717 msg(D_DCO, "Cannot set DCO peer parameters for peer (id=%d): %s",
1718 multi->dco_peer_id, strerror(-ret));
1719 return false;
1720 }
1721 }
1722 }
1723 /* A DCO desync is reported as a plain failure here: every caller of this
1724 * function already turns a failure into a SIGUSR1, which is exactly the
1725 * recovery a desync needs */
1727}
1728
1729bool
1731 struct options *options, struct frame *frame,
1732 struct frame *frame_fragment, const struct link_socket_info *lsi,
1733 dco_context_t *dco)
1734{
1736 {
1737 return false;
1738 }
1739
1740 /* Import crypto settings that might be set by pull/push */
1741 session->opt->crypto_flags |= options->imported_protocol_flags;
1742
1743 return tls_session_update_crypto_params_do_work(multi, session, options, frame, frame_fragment,
1744 lsi, dco);
1745}
1746
1747
1748static bool
1749random_bytes_to_buf(struct buffer *buf, uint8_t *out, int outlen)
1750{
1751 if (!rand_bytes(out, outlen))
1752 {
1753 msg(M_FATAL,
1754 "ERROR: Random number generator cannot obtain entropy for key generation [SSL]");
1755 }
1756 if (!buf_write(buf, out, outlen))
1757 {
1758 return false;
1759 }
1760 return true;
1761}
1762
1763static bool
1764key_source2_randomize_write(struct key_source2 *k2, struct buffer *buf, bool server)
1765{
1766 struct key_source *k = &k2->client;
1767 if (server)
1768 {
1769 k = &k2->server;
1770 }
1771
1772 CLEAR(*k);
1773
1774 if (!server)
1775 {
1776 if (!random_bytes_to_buf(buf, k->pre_master, sizeof(k->pre_master)))
1777 {
1778 return false;
1779 }
1780 }
1781
1782 if (!random_bytes_to_buf(buf, k->random1, sizeof(k->random1)))
1783 {
1784 return false;
1785 }
1786 if (!random_bytes_to_buf(buf, k->random2, sizeof(k->random2)))
1787 {
1788 return false;
1789 }
1790
1791 return true;
1792}
1793
1794static int
1795key_source2_read(struct key_source2 *k2, struct buffer *buf, bool server)
1796{
1797 struct key_source *k = &k2->client;
1798
1799 if (!server)
1800 {
1801 k = &k2->server;
1802 }
1803
1804 CLEAR(*k);
1805
1806 if (server)
1807 {
1808 if (!buf_read(buf, k->pre_master, sizeof(k->pre_master)))
1809 {
1810 return 0;
1811 }
1812 }
1813
1814 if (!buf_read(buf, k->random1, sizeof(k->random1)))
1815 {
1816 return 0;
1817 }
1818 if (!buf_read(buf, k->random2, sizeof(k->random2)))
1819 {
1820 return 0;
1821 }
1822
1823 return 1;
1824}
1825
1826static void
1828{
1829 const struct buffer *b;
1830
1831 while ((b = buffer_list_peek(ks->paybuf)))
1832 {
1833 key_state_write_plaintext_const(&ks->ks_ssl, b->data, b->len);
1835 }
1836}
1837
1838/*
1839 * Move the active key to the lame duck key and reinitialize the
1840 * active key.
1841 */
1842static void
1844{
1845 struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
1846 struct key_state *ks_lame = &session->key[KS_LAME_DUCK]; /* retiring key */
1847
1848 ks->must_die = now + session->opt->transition_window; /* remaining lifetime of old key */
1849 key_state_free(ks_lame, false, to_link);
1850 *ks_lame = *ks;
1851
1853 ks->session_id_remote = ks_lame->session_id_remote;
1854 ks->remote_addr = ks_lame->remote_addr;
1855}
1856
1857void
1862
1863/*
1864 * Read/write strings from/to a struct buffer with a u16 length prefix.
1865 */
1866
1867static bool
1869{
1870 if (!buf_write_u16(buf, 0))
1871 {
1872 return false;
1873 }
1874 return true;
1875}
1876
1877static bool
1878write_string(struct buffer *buf, const char *str, const int maxlen)
1879{
1880 const size_t len = strlen(str) + 1;
1881 const size_t real_maxlen = (maxlen >= 0 && maxlen <= UINT16_MAX) ? (size_t)maxlen : UINT16_MAX;
1882 if (len > real_maxlen)
1883 {
1884 return false;
1885 }
1886 if (!buf_write_u16(buf, (uint16_t)len))
1887 {
1888 return false;
1889 }
1890 if (!buf_write(buf, str, len))
1891 {
1892 return false;
1893 }
1894 return true;
1895}
1896
1907static int
1908read_string(struct buffer *buf, char *str, const unsigned int capacity)
1909{
1910 const int len = buf_read_u16(buf);
1911 if (len < 1 || len > (int)capacity)
1912 {
1913 buf_advance(buf, len);
1914
1915 /* will also return 0 for a no string being present */
1916 return -len;
1917 }
1918 if (!buf_read(buf, str, len))
1919 {
1920 return -len;
1921 }
1922 str[len - 1] = '\0';
1923 return len;
1924}
1925
1926static char *
1928{
1929 const int len = buf_read_u16(buf);
1930 char *str;
1931
1932 if (len < 1)
1933 {
1934 return NULL;
1935 }
1936 str = (char *)malloc(len);
1938 if (!buf_read(buf, str, len))
1939 {
1940 free(str);
1941 return NULL;
1942 }
1943 str[len - 1] = '\0';
1944 return str;
1945}
1946
1947static bool
1948push_peer_info_peerid(struct buffer *out, const struct tls_multi *multi,
1949 const struct tls_session *session)
1950{
1951 if (multi->rx_peer_id == MAX_PEER_ID || session->opt->dco_enabled)
1952 {
1953 /* No valid peer id or DCO is enabled. Cannot use this feature */
1954 return true;
1955 }
1956
1957 /* In server mode we only add this when the client has announced its
1958 * support for the feature */
1959 if (session->opt->mode != MODE_SERVER || multi->use_asymmetric_peer_id)
1960 {
1961 return buf_printf(out, "ID=%x\n", multi->rx_peer_id);
1962 }
1963
1964 return true;
1965}
1966
1983static bool
1984push_peer_info(struct buffer *buf, const struct tls_multi *multi, struct tls_session *session)
1985{
1986 struct gc_arena gc = gc_new();
1987 bool ret = false;
1988 struct buffer out = alloc_buf_gc(512 * 3, &gc);
1989
1990 /* The asymmetric peer-id is always written when enabled */
1991 if (!push_peer_info_peerid(&out, multi, session))
1992 {
1993 goto error;
1994 }
1995
1996 if (session->opt->push_peer_info_detail > 1)
1997 {
1998 /* push version */
1999 buf_printf(&out, "IV_VER=%s\n", PACKAGE_VERSION);
2000
2001 /* push platform */
2002#if defined(TARGET_LINUX)
2003 buf_printf(&out, "IV_PLAT=linux\n");
2004#elif defined(TARGET_SOLARIS)
2005 buf_printf(&out, "IV_PLAT=solaris\n");
2006#elif defined(TARGET_OPENBSD)
2007 buf_printf(&out, "IV_PLAT=openbsd\n");
2008#elif defined(TARGET_DARWIN)
2009 buf_printf(&out, "IV_PLAT=mac\n");
2010#elif defined(TARGET_NETBSD)
2011 buf_printf(&out, "IV_PLAT=netbsd\n");
2012#elif defined(TARGET_FREEBSD)
2013 buf_printf(&out, "IV_PLAT=freebsd\n");
2014#elif defined(TARGET_ANDROID)
2015 buf_printf(&out, "IV_PLAT=android\n");
2016#elif defined(_WIN32)
2017 buf_printf(&out, "IV_PLAT=win\n");
2018#endif
2019 /* Announce that we do not require strict sequence numbers with
2020 * TCP. (TCP non-linear) */
2021 buf_printf(&out, "IV_TCPNL=1\n");
2022 }
2023
2024 /* These are the IV variable that are sent to peers in p2p mode */
2025 if (session->opt->push_peer_info_detail > 0)
2026 {
2027 /* support for P_DATA_V2 */
2029
2030 /* support for the latest --dns option */
2032
2033 /* support for exit notify via control channel */
2035
2036 /* currently push-update is not supported when DCO is enabled */
2037 if (!session->opt->dco_enabled)
2038 {
2039 /* support push-updates */
2041 }
2042
2043 if (session->opt->pull)
2044 {
2045 /* support for receiving push_reply before sending
2046 * push request, also signal that the client wants
2047 * to get push-reply messages without requiring a round
2048 * trip for a push request message*/
2050
2051 /* Support keywords in the AUTH_PENDING control message */
2053
2054 /* support for AUTH_FAIL,TEMP control message */
2056
2057 /* support for tun-mtu as part of the push message */
2058 buf_printf(&out, "IV_MTU=%d\n", session->opt->frame.tun_max_mtu);
2059 }
2060
2061 /* support for Negotiable Crypto Parameters */
2062 if (session->opt->mode == MODE_SERVER || session->opt->pull)
2063 {
2064 if (tls_item_in_cipher_list("AES-128-GCM", session->opt->config_ncp_ciphers)
2065 && tls_item_in_cipher_list("AES-256-GCM", session->opt->config_ncp_ciphers))
2066 {
2067 buf_printf(&out, "IV_NCP=2\n");
2068 }
2069 }
2070 else
2071 {
2072 /* We are not using pull or p2mp server, instead do P2P NCP */
2074 }
2075
2076 if (session->opt->data_epoch_supported)
2077 {
2079 }
2080
2081 buf_printf(&out, "IV_CIPHERS=%s\n", session->opt->config_ncp_ciphers);
2082
2085
2086 buf_printf(&out, "IV_PROTO=%d\n", iv_proto);
2087
2088 if (session->opt->push_peer_info_detail > 1)
2089 {
2090 /* push compression status */
2091#ifdef USE_COMP
2092 comp_generate_peer_info_string(&session->opt->comp_options, &out);
2093#endif
2094 }
2095
2096 if (session->opt->push_peer_info_detail > 2)
2097 {
2098 /* push mac addr */
2099 struct route_gateway_info rgi;
2100 get_default_gateway(&rgi, 0, session->opt->net_ctx);
2101 if (rgi.flags & RGI_HWADDR_DEFINED)
2102 {
2103 buf_printf(&out, "IV_HWADDR=%s\n", format_hex_ex(rgi.hwaddr, 6, 0, 1, ":", &gc));
2104 }
2105 buf_printf(&out, "IV_SSL=%s\n", get_ssl_library_version());
2106#if defined(_WIN32)
2107 buf_printf(&out, "IV_PLAT_VER=%s\n", win32_version_string(&gc));
2108#else
2109 struct utsname u;
2110 uname(&u);
2111 buf_printf(&out, "IV_PLAT_VER=%s\n", u.release);
2112#endif
2113 }
2114
2115 if (session->opt->acc_protocols)
2116 {
2117 buf_printf(&out, "IV_ACC=%d,A:6,%s\n", ACC_MAX_MSG_LEN, session->opt->acc_protocols);
2118 }
2119
2120 if (session->opt->push_peer_info_detail > 1)
2121 {
2122 struct env_set *es = session->opt->es;
2123 /* push env vars that begin with UV_, IV_PLAT_VER and IV_GUI_VER */
2124 for (struct env_item *e = es->list; e != NULL; e = e->next)
2125 {
2126 if (e->string)
2127 {
2128 if ((((strncmp(e->string, "UV_", 3) == 0
2129 || strncmp(e->string, "IV_PLAT_VER=", sizeof("IV_PLAT_VER=") - 1) == 0)
2130 && session->opt->push_peer_info_detail > 2)
2131 || (strncmp(e->string, "IV_GUI_VER=", sizeof("IV_GUI_VER=") - 1) == 0)
2132 || (strncmp(e->string, "IV_SSO=", sizeof("IV_SSO=") - 1) == 0))
2133 && buf_safe(&out, strlen(e->string) + 1))
2134 {
2135 buf_printf(&out, "%s\n", e->string);
2136 }
2137 }
2138 }
2139 }
2140 }
2141
2142 /* write peer info string if there is anything in it, empty string otherwise */
2143 if (BLEN(&out) > 0)
2144 {
2145 if (!write_string(buf, BSTR(&out), -1))
2146 {
2147 goto error;
2148 }
2149 }
2150 else
2151 {
2152 if (!write_empty_string(buf))
2153 {
2154 goto error;
2155 }
2156 }
2157 ret = true;
2158
2159error:
2160 gc_free(&gc);
2161 return ret;
2162}
2163
2164#ifdef USE_COMP
2165static bool
2166write_compat_local_options(struct buffer *buf, const char *options)
2167{
2168 struct gc_arena gc = gc_new();
2169 const char *local_options = options_string_compat_lzo(options, &gc);
2170 bool ret = write_string(buf, local_options, TLS_OPTIONS_LEN);
2171 gc_free(&gc);
2172 return ret;
2173}
2174#endif
2175
2180static bool
2181key_method_2_write(struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
2182{
2183 struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
2184
2185 ASSERT(buf_init(buf, 0));
2186
2187 /* write a uint32 0 */
2188 if (!buf_write_u32(buf, 0))
2189 {
2190 goto error;
2191 }
2192
2193 /* write key_method + flags */
2194 if (!buf_write_u8(buf, KEY_METHOD_2))
2195 {
2196 goto error;
2197 }
2198
2199 /* write key source material */
2200 if (!key_source2_randomize_write(ks->key_src, buf, session->opt->server))
2201 {
2202 goto error;
2203 }
2204
2205 /* write options string */
2206 {
2207#ifdef USE_COMP
2208 if (multi->remote_usescomp && session->opt->mode == MODE_SERVER
2209 && multi->opt.comp_options.flags & COMP_F_MIGRATE)
2210 {
2211 if (!write_compat_local_options(buf, session->opt->local_options))
2212 {
2213 goto error;
2214 }
2215 }
2216 else
2217#endif
2218 if (!write_string(buf, session->opt->local_options, TLS_OPTIONS_LEN))
2219 {
2220 goto error;
2221 }
2222 }
2223
2224 /* write username/password if specified or we are using a auth-token */
2226 {
2227#ifdef ENABLE_MANAGEMENT
2228 auth_user_pass_setup(session->opt->auth_user_pass_file,
2229 session->opt->auth_user_pass_file_inline,
2230 session->opt->auth_user_pass_username_only, session->opt->sci);
2231#else
2232 auth_user_pass_setup(session->opt->auth_user_pass_file,
2233 session->opt->auth_user_pass_file_inline,
2234 session->opt->auth_user_pass_username_only, NULL);
2235#endif
2236 struct user_pass *up = &auth_user_pass;
2237
2238 /*
2239 * If we have a valid auth-token, send that instead of real
2240 * username/password
2241 */
2243 {
2244 up = &auth_token;
2245 }
2247
2248 if (!write_string(buf, up->username, -1))
2249 {
2250 msg(M_WARN, "WARNING: Failed to write auth username to TLS buffer");
2251 goto error;
2252 }
2253 else if (!write_string(buf, up->password, -1))
2254 {
2255 msg(M_WARN, "WARNING: Failed to write auth password to TLS buffer");
2256 goto error;
2257 }
2258 /* save username for auth-token which may get pushed later */
2259 if (session->opt->pull && up != &auth_token)
2260 {
2264 }
2266 /* respect auth-nocache */
2268 }
2269 else
2270 {
2271 if (!write_empty_string(buf)) /* no username */
2272 {
2273 goto error;
2274 }
2275 if (!write_empty_string(buf)) /* no password */
2276 {
2277 goto error;
2278 }
2279 }
2280
2281 if (!push_peer_info(buf, multi, session))
2282 {
2283 goto error;
2284 }
2285
2286 if (session->opt->server && session->opt->mode != MODE_SERVER && ks->key_id == 0)
2287 {
2288 /* tls-server option set and not P2MP server, so we
2289 * are a P2P client running in tls-server mode */
2290 p2p_mode_ncp(multi, session);
2291 }
2292
2293 return true;
2294
2295error:
2296 msg(D_TLS_ERRORS, "TLS Error: Key Method #2 write failed");
2297 secure_memzero(ks->key_src, sizeof(*ks->key_src));
2298 return false;
2299}
2300
2301static void
2303{
2304 if (session->opt->ekm_size > 0)
2305 {
2306 const size_t size = session->opt->ekm_size;
2307 struct gc_arena gc = gc_new();
2308
2309 unsigned char *ekm = gc_malloc(size, true, &gc);
2311 session->opt->ekm_label_size, ekm,
2312 session->opt->ekm_size))
2313 {
2314 const size_t len = (size * 2) + 2;
2315
2316 const char *key = format_hex_ex(ekm, size, len, 0, NULL, &gc);
2317 setenv_str(session->opt->es, "exported_keying_material", key);
2318
2319 dmsg(D_TLS_DEBUG_MED, "%s: exported keying material: %s", __func__, key);
2320 secure_memzero(ekm, size);
2321 }
2322 else
2323 {
2324 msg(M_WARN, "WARNING: Export keying material failed!");
2325 setenv_del(session->opt->es, "exported_keying_material");
2326 }
2327 gc_free(&gc);
2328 }
2329}
2330
2335static bool
2336key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
2337{
2338 struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
2339
2340 struct gc_arena gc = gc_new();
2341 char *options;
2342 struct user_pass *up = NULL;
2343
2344 /* allocate temporary objects */
2346
2347 /* discard leading uint32 */
2348 if (!buf_advance(buf, 4))
2349 {
2350 msg(D_TLS_ERRORS, "TLS ERROR: Plaintext buffer too short (%d bytes).", buf->len);
2351 goto error;
2352 }
2353
2354 /* get key method */
2355 int key_method_flags = buf_read_u8(buf);
2356 if ((key_method_flags & KEY_METHOD_MASK) != 2)
2357 {
2358 msg(D_TLS_ERRORS, "TLS ERROR: Unknown key_method/flags=%d received from remote host",
2359 key_method_flags);
2360 goto error;
2361 }
2362
2363 /* get key source material (not actual keys yet) */
2364 if (!key_source2_read(ks->key_src, buf, session->opt->server))
2365 {
2367 "TLS Error: Error reading remote data channel key source entropy from plaintext buffer");
2368 goto error;
2369 }
2370
2371 /* get options */
2372 if (read_string(buf, options, TLS_OPTIONS_LEN) < 0)
2373 {
2374 msg(D_TLS_ERRORS, "TLS Error: Failed to read required OCC options string");
2375 goto error;
2376 }
2377
2379
2380 /* always extract username + password fields from buf, even if not
2381 * authenticating for it, because otherwise we can't get at the
2382 * peer_info data which follows behind
2383 */
2384 ALLOC_OBJ_CLEAR_GC(up, struct user_pass, &gc);
2385 int username_len = read_string(buf, up->username, USER_PASS_LEN);
2386 int password_len = read_string(buf, up->password, USER_PASS_LEN);
2387
2388 /* get peer info from control channel */
2389 free(multi->peer_info);
2390 multi->peer_info = read_string_alloc(buf);
2391 if (multi->peer_info)
2392 {
2393 output_peer_info_env(session->opt->es, multi->peer_info);
2394 uint32_t peer_id = extract_asymmetric_peer_id(multi->peer_info);
2395 if (peer_id != MAX_PEER_ID && !session->opt->dco_enabled)
2396 {
2397 multi->tx_peer_id = peer_id;
2398 multi->use_asymmetric_peer_id = true;
2399 multi->use_peer_id = true;
2400 }
2401 else
2402 {
2403 /* Peer has no support for asymmetric peer-id, and DCO currently
2404 * can only handle symmetric peer IDs */
2405 multi->tx_peer_id = multi->rx_peer_id;
2406 }
2407 }
2408
2409 free(multi->remote_ciphername);
2411 multi->remote_usescomp = strstr(options, ",comp-lzo,");
2412
2413 /* In OCC we send '[null-cipher]' instead 'none' */
2414 if (multi->remote_ciphername && strcmp(multi->remote_ciphername, "[null-cipher]") == 0)
2415 {
2416 free(multi->remote_ciphername);
2417 multi->remote_ciphername = string_alloc("none", NULL);
2418 }
2419
2421
2422 if (username_len < 0 || password_len < 0)
2423 {
2424 msg(D_TLS_ERRORS, "TLS Error: Username (%d) or password (%d) too long", abs(username_len),
2425 abs(password_len));
2426 auth_set_client_reason(multi, "Username or password is too long. "
2427 "Maximum length is 128 bytes");
2428
2429 /* treat the same as failed username/password and do not error
2430 * out (goto error) to sent an AUTH_FAILED back to the client */
2432 }
2434 {
2435 /* Perform username/password authentication */
2436 if (!username_len || !password_len)
2437 {
2438 CLEAR(*up);
2439 if (!(session->opt->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL))
2440 {
2441 msg(D_TLS_ERRORS, "TLS Error: Auth Username/Password was not provided by peer");
2442 goto error;
2443 }
2444 }
2445
2446 verify_user_pass(up, multi, session);
2447 }
2448 else
2449 {
2450 /* Session verification should have occurred during TLS negotiation*/
2451 if (!session->verified)
2452 {
2453 msg(D_TLS_ERRORS, "TLS Error: Certificate verification failed (key-method 2)");
2454 goto error;
2455 }
2457 }
2458
2459 /* clear username and password from memory */
2460 secure_memzero(up, sizeof(*up));
2461
2462 /* Perform final authentication checks */
2463 if (ks->authenticated > KS_AUTH_FALSE)
2464 {
2466 }
2467
2468 /* check options consistency */
2469 if (!options_cmp_equal(options, session->opt->remote_options))
2470 {
2471 const char *remote_options = session->opt->remote_options;
2472#ifdef USE_COMP
2473 if (multi->opt.comp_options.flags & COMP_F_MIGRATE && multi->remote_usescomp)
2474 {
2475 msg(D_PUSH, "Note: 'compress migrate' detected remote peer "
2476 "with compression enabled.");
2477 remote_options = options_string_compat_lzo(remote_options, &gc);
2478 }
2479#endif
2480
2481 options_warning(options, remote_options);
2482 }
2483
2484 buf_clear(buf);
2485
2486 /*
2487 * Call OPENVPN_PLUGIN_TLS_FINAL plugin if defined, for final
2488 * veto opportunity over authentication decision.
2489 */
2490 if ((ks->authenticated > KS_AUTH_FALSE)
2492 {
2494
2495 if (plugin_call(session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL, NULL, NULL,
2496 session->opt->es)
2498 {
2500 }
2501
2502 setenv_del(session->opt->es, "exported_keying_material");
2503 }
2504
2505 if (!session->opt->server && !session->opt->pull && ks->key_id == 0)
2506 {
2507 /* We are a p2p tls-client without pull, enable common
2508 * protocol options */
2509 p2p_mode_ncp(multi, session);
2510 }
2511
2512 gc_free(&gc);
2513 return true;
2514
2515error:
2517 secure_memzero(ks->key_src, sizeof(*ks->key_src));
2518 if (up)
2519 {
2520 secure_memzero(up, sizeof(*up));
2521 }
2522 buf_clear(buf);
2523 gc_free(&gc);
2524 return false;
2525}
2526
2527static int
2529{
2530 int ret = o->handshake_window;
2531 const int r2 = o->renegotiate_seconds / 2;
2532
2533 if (o->renegotiate_seconds && r2 < ret)
2534 {
2535 ret = r2;
2536 }
2537 return ret;
2538}
2539
2546static bool
2548 bool skip_initial_send)
2549{
2551 if (!buf)
2552 {
2553 return false;
2554 }
2555
2556 ks->initial = now;
2557 ks->must_negotiate = now + session->opt->handshake_window;
2559
2560 /* null buffer */
2562
2563 /* If we want to skip sending the initial handshake packet we still generate
2564 * it to increase internal counters etc. but immediately mark it as done */
2566 {
2568 }
2570
2572
2573 struct gc_arena gc = gc_new();
2574 dmsg(D_TLS_DEBUG, "TLS: Initial Handshake, sid=%s",
2575 session_id_print(&session->session_id, &gc));
2576 gc_free(&gc);
2577
2578#ifdef ENABLE_MANAGEMENT
2580 {
2581 management_set_state(management, OPENVPN_STATE_WAIT, NULL, NULL, NULL, NULL, NULL);
2582 }
2583#endif
2584 return true;
2585}
2586
2591static void
2593 struct link_socket_info *to_link_socket_info, struct key_state *ks)
2594{
2595 dmsg(D_TLS_DEBUG_MED, "STATE S_ACTIVE");
2596
2597 ks->established = now;
2599 {
2600 print_details(&ks->ks_ssl, "Control Channel:");
2601 }
2602 ks->state = S_ACTIVE;
2603 /* Cancel negotiation timeout */
2604 ks->must_negotiate = 0;
2606
2607 /* Set outgoing address for data channel packets */
2608 link_socket_set_outgoing_addr(to_link_socket_info, &ks->remote_addr, session->common_name,
2609 session->opt->es);
2610
2611 /* Check if we need to advance the tls_multi state machine */
2612 if (multi->multi_state == CAS_NOT_CONNECTED)
2613 {
2614 if (session->opt->mode == MODE_SERVER)
2615 {
2616 /* On a server we continue with running connect scripts next */
2618 }
2619 else
2620 {
2621 /* Skip the connect script related states */
2623 }
2624 }
2625
2626 /* Flush any payload packets that were buffered before our state transitioned to S_ACTIVE */
2628
2629#ifdef MEASURE_TLS_HANDSHAKE_STATS
2630 show_tls_performance_stats();
2631#endif
2632}
2633
2634bool
2636 const struct link_socket_actual *from)
2637{
2638 struct key_state *ks = &session->key[KS_PRIMARY];
2639 ks->session_id_remote = state->peer_session_id;
2640 ks->remote_addr = *from;
2641 session->session_id = state->server_session_id;
2642 session->untrusted_addr = *from;
2643 session->burst = true;
2644
2645 /* The OpenVPN protocol implicitly mandates that packet id always start
2646 * from 0 in the RESET packets as OpenVPN 2.x will not allow gaps in the
2647 * ids and starts always from 0. Since we skip/ignore one (RESET) packet
2648 * in each direction, we need to set the ids to 1 */
2649 ks->rec_reliable->packet_id = 1;
2650 /* for ks->send_reliable->packet_id, session_move_pre_start moves the
2651 * counter to 1 */
2652 session->tls_wrap.opt.packet_id.send.id = 1;
2653 return session_move_pre_start(session, ks, true);
2654}
2655
2659static bool
2661 struct key_state *ks)
2662{
2663 while (buf->len > 0)
2664 {
2665 if (buf_len(buf) < 4)
2666 {
2667 goto error;
2668 }
2669 /* read type */
2670 int type = buf_read_u16(buf);
2671 int len = buf_read_u16(buf);
2672 if (type < 0 || len < 0 || buf_len(buf) < len)
2673 {
2674 goto error;
2675 }
2676
2677 switch (type)
2678 {
2680 if (len != sizeof(uint16_t))
2681 {
2682 goto error;
2683 }
2684 int flags = buf_read_u16(buf);
2685
2686 if (flags & EARLY_NEG_FLAG_RESEND_WKC)
2687 {
2688 /* Only accept the EARLY_NEG_FLAG_RESEND_WKC flag
2689 * from the server if we are configured with tls-crypt-v2 */
2690 if (session->tls_wrap.tls_crypt_v2_wkc)
2691 {
2693 }
2694 else
2695 {
2696 msg(D_TLS_ERRORS, "TLS Error: peer asked us to resend the wrapped "
2697 "client key, but this is not a tls-crypt-v2 client");
2698 }
2699 }
2700 break;
2701
2702 default:
2703 /* Skip types we do not parse */
2704 buf_advance(buf, len);
2705 }
2706 }
2708
2709 return true;
2710error:
2711 msg(D_TLS_ERRORS, "TLS Error: Early negotiation malformed packet");
2712 return false;
2713}
2714
2719static bool
2720read_incoming_tls_ciphertext(struct buffer *buf, struct key_state *ks, bool *continue_tls_process)
2721{
2722 int status = 0;
2723 if (buf->len)
2724 {
2726 if (status == -1)
2727 {
2728 msg(D_TLS_ERRORS, "TLS Error: Incoming Ciphertext -> TLS object write error");
2729 return false;
2730 }
2731 }
2732 else
2733 {
2734 status = 1;
2735 }
2736 if (status == 1)
2737 {
2739 *continue_tls_process = true;
2740 dmsg(D_TLS_DEBUG, "Incoming Ciphertext -> TLS");
2741 }
2742 return true;
2743}
2744
2745static bool
2747{
2748 return (ks->crypto_options.flags & CO_RESEND_WKC) && (ks->send_reliable->packet_id == 1);
2749}
2750
2751
2752static bool
2754 bool *continue_tls_process)
2755{
2756 ASSERT(buf_init(buf, 0));
2757
2758 int status = key_state_read_plaintext(&ks->ks_ssl, buf);
2759
2760 update_time();
2761 if (status == -1)
2762 {
2763 msg(D_TLS_ERRORS, "TLS Error: TLS object -> incoming plaintext read error");
2764 return false;
2765 }
2766 if (status == 1)
2767 {
2768 *continue_tls_process = true;
2769 dmsg(D_TLS_DEBUG, "TLS -> Incoming Plaintext");
2770
2771 /* More data may be available, wake up again asap to check. */
2772 *wakeup = 0;
2773 }
2774 return true;
2775}
2776
2777static bool
2778write_outgoing_tls_ciphertext(struct tls_session *session, bool *continue_tls_process)
2779{
2780 struct key_state *ks = &session->key[KS_PRIMARY];
2781
2783 if (rel_avail == 0)
2784 {
2785 return true;
2786 }
2787
2788 /* We need to determine how much space is actually available in the control
2789 * channel frame */
2790 int max_pkt_len = min_int(TLS_CHANNEL_BUF_SIZE, session->opt->frame.tun_mtu);
2791
2792 /* Subtract overhead */
2793 max_pkt_len -= (int)calc_control_channel_frame_overhead(session);
2794
2795 /* calculate total available length for outgoing tls ciphertext */
2796 int maxlen = max_pkt_len * rel_avail;
2797
2798 /* Is first packet one that will have a WKC appended? */
2800 {
2801 maxlen -= buf_len(session->tls_wrap.tls_crypt_v2_wkc);
2802 }
2803
2804 /* If we end up with a size that leaves no room for payload, ignore the
2805 * constraints to still be to send a packet. This might have gone negative
2806 * if we have a large wrapped client key. */
2807 if (maxlen < 16)
2808 {
2810 "Warning: --max-packet-size (%d) setting too low. "
2811 "Sending minimum sized packet.",
2812 session->opt->frame.tun_mtu);
2813 maxlen = 16;
2814 /* We set the maximum length here to ensure a packet with a wrapped
2815 * key can actually carry the 16 byte of payload */
2816 max_pkt_len = TLS_CHANNEL_BUF_SIZE;
2817 }
2818
2819 /* This seems a bit wasteful to allocate every time */
2820 struct gc_arena gc = gc_new();
2821 struct buffer tmp = alloc_buf_gc(maxlen, &gc);
2822
2824
2825 if (status == -1)
2826 {
2827 msg(D_TLS_ERRORS, "TLS Error: Ciphertext -> reliable TCP/UDP transport read error");
2828 gc_free(&gc);
2829 return false;
2830 }
2831 if (status == 1)
2832 {
2833 /* Split the TLS ciphertext (TLS record) into multiple small packets
2834 * that respect tls_mtu */
2835 while (tmp.len > 0)
2836 {
2837 int len = max_pkt_len;
2838 int opcode = P_CONTROL_V1;
2840 {
2841 opcode = P_CONTROL_WKC_V1;
2842 len = max_int(0, len - buf_len(session->tls_wrap.tls_crypt_v2_wkc));
2843 }
2844 /* do not send more than available */
2845 len = min_int(len, tmp.len);
2846
2848 /* we assert here since we checked for its availability before */
2849 ASSERT(buf);
2850 buf_copy_n(buf, &tmp, len);
2851
2854 *continue_tls_process = true;
2855 }
2856 dmsg(D_TLS_DEBUG, "Outgoing Ciphertext -> Reliable");
2857 }
2858
2859 gc_free(&gc);
2860 return true;
2861}
2862
2863static bool
2865 const struct buffer *to_link, bool *continue_tls_process)
2866{
2867 if (to_link->len)
2868 {
2870 "Deferring outgoing ciphertext, previous packet not written out yet");
2871 return true;
2872 }
2873
2874 /* Outgoing Ciphertext to reliable buffer */
2875 if (ks->state >= S_START)
2876 {
2878 if (buf)
2879 {
2881 {
2882 return false;
2883 }
2884 }
2885 }
2886 return true;
2887}
2888
2889static bool
2890tls_process_state(struct tls_multi *multi, struct tls_session *session, struct buffer *to_link,
2891 struct link_socket_actual **to_link_addr,
2893{
2894 /* This variable indicates if we should call this method
2895 * again to process more incoming/outgoing TLS state/data
2896 * We want to repeat this until we either determined that there
2897 * is nothing more to process or that further processing
2898 * should only be done after the outer loop (sending packets etc.)
2899 * has run once more */
2900 bool continue_tls_process = false;
2901 struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
2902
2903 /* Initial handshake */
2904 if (ks->state == S_INITIAL)
2905 {
2906 continue_tls_process = session_move_pre_start(session, ks, false);
2907 }
2908
2909 /* Are we timed out on receive? */
2910 if (now >= ks->must_negotiate && ks->state >= S_UNDEF && ks->state < S_ACTIVE)
2911 {
2913 "TLS Error: TLS key negotiation failed to occur within %d seconds (check your network connectivity)",
2914 session->opt->handshake_window);
2915 goto error;
2916 }
2917
2918 /* Check if the initial three-way Handshake is complete.
2919 * We consider the handshake to be complete when our own initial
2920 * packet has been successfully ACKed. */
2921 if (ks->state == S_PRE_START && reliable_empty(ks->send_reliable))
2922 {
2923 ks->state = S_START;
2924 continue_tls_process = true;
2925
2926 /* New connection, remove any old X509 env variables */
2927 tls_x509_clear_env(session->opt->es);
2928 dmsg(D_TLS_DEBUG_MED, "STATE S_START");
2929 }
2930
2931 /* Wait for ACK */
2932 if (((ks->state == S_GOT_KEY && !session->opt->server)
2933 || (ks->state == S_SENT_KEY && session->opt->server))
2935 {
2936 session_move_active(multi, session, to_link_socket_info, ks);
2937 continue_tls_process = true;
2938 }
2939
2940 /* Reliable buffer to outgoing TCP/UDP (send up to CONTROL_SEND_ACK_MAX ACKs
2941 * for previously received packets) */
2942 if (!to_link->len && reliable_can_send(ks->send_reliable))
2943 {
2944 int opcode;
2945
2946 const struct buffer *buf = reliable_send(ks->send_reliable, &opcode);
2947 ASSERT(buf);
2948 struct buffer b = *buf;
2949 INCR_SENT;
2950
2951 write_control_auth(session, ks, &b, to_link_addr, opcode, CONTROL_SEND_ACK_MAX, true);
2952 *to_link = b;
2953 dmsg(D_TLS_DEBUG, "Reliable -> TCP/UDP");
2954
2955 /* This changed the state of the outgoing buffer. In order to avoid
2956 * running this function again/further and invalidating the key_state
2957 * buffer and accessing the buffer that is now in to_link after it being
2958 * freed for a potential error, we shortcircuit exiting of the outer
2959 * process here. */
2960 return false;
2961 }
2962
2963 if (ks->state == S_ERROR_PRE)
2964 {
2965 /* When we end up here, we had one last chance to send an outstanding
2966 * packet that contained an alert. We do not ensure that this packet
2967 * has been successfully delivered (ie wait for the ACK etc)
2968 * but rather stop processing now */
2969 ks->state = S_ERROR;
2970 return false;
2971 }
2972
2973 /* Write incoming ciphertext to TLS object */
2975 if (entry)
2976 {
2977 /* The first packet from the peer (the reset packet) is special and
2978 * contains early protocol negotiation */
2979 if (entry->packet_id == 0 && is_hard_reset_method2(entry->opcode))
2980 {
2981 if (!parse_early_negotiation_tlvs(&entry->buf, session, ks))
2982 {
2983 goto error;
2984 }
2985 }
2986 else
2987 {
2988 if (!read_incoming_tls_ciphertext(&entry->buf, ks, &continue_tls_process))
2989 {
2990 goto error;
2991 }
2992 }
2993 }
2994
2995 /* Read incoming plaintext from TLS object */
2996 struct buffer *buf = &ks->plaintext_read_buf;
2997 if (!buf->len)
2998 {
2999 if (!read_incoming_tls_plaintext(ks, buf, wakeup, &continue_tls_process))
3000 {
3001 goto error;
3002 }
3003 }
3004
3005 /* Send Key */
3006 buf = &ks->plaintext_write_buf;
3007 if (!buf->len
3008 && ((ks->state == S_START && !session->opt->server)
3009 || (ks->state == S_GOT_KEY && session->opt->server)))
3010 {
3011 if (!key_method_2_write(buf, multi, session))
3012 {
3013 goto error;
3014 }
3015
3016 continue_tls_process = true;
3017 dmsg(D_TLS_DEBUG_MED, "STATE S_SENT_KEY");
3018 ks->state = S_SENT_KEY;
3019 }
3020
3021 /* Receive Key */
3022 buf = &ks->plaintext_read_buf;
3023 if (buf->len
3024 && ((ks->state == S_SENT_KEY && !session->opt->server)
3025 || (ks->state == S_START && session->opt->server)))
3026 {
3027 if (!key_method_2_read(buf, multi, session))
3028 {
3029 goto error;
3030 }
3031
3032 continue_tls_process = true;
3033 dmsg(D_TLS_DEBUG_MED, "STATE S_GOT_KEY");
3034 ks->state = S_GOT_KEY;
3035 }
3036
3037 /* Write outgoing plaintext to TLS object */
3038 buf = &ks->plaintext_write_buf;
3039 if (buf->len)
3040 {
3041 int status = key_state_write_plaintext(&ks->ks_ssl, buf);
3042 if (status == -1)
3043 {
3044 msg(D_TLS_ERRORS, "TLS ERROR: Outgoing Plaintext -> TLS object write error");
3045 goto error;
3046 }
3047 if (status == 1)
3048 {
3049 continue_tls_process = true;
3050 dmsg(D_TLS_DEBUG, "Outgoing Plaintext -> TLS");
3051 }
3052 }
3054 {
3055 goto error;
3056 }
3057
3058 return continue_tls_process;
3059error:
3061
3062 /* Shut down the TLS session but do a last read from the TLS
3063 * object to be able to read potential TLS alerts */
3066
3067 /* Put ourselves in the pre error state that will only send out the
3068 * control channel packets but nothing else */
3069 ks->state = S_ERROR_PRE;
3070
3071 msg(D_TLS_ERRORS, "TLS Error: TLS handshake failed");
3072 INCR_ERROR;
3073 return true;
3074}
3075
3076#if defined(__GNUC__) || defined(__clang__)
3077#pragma GCC diagnostic push
3078#pragma GCC diagnostic ignored "-Wsign-compare"
3079#endif
3080
3085static bool
3087{
3088 /* Time limit */
3089 if (session->opt->renegotiate_seconds
3090 && now >= ks->established + session->opt->renegotiate_seconds)
3091 {
3092 return true;
3093 }
3094
3095 /* Byte limit */
3096 if (session->opt->renegotiate_bytes > 0 && ks->n_bytes >= session->opt->renegotiate_bytes)
3097 {
3098 return true;
3099 }
3100
3101 /* Packet limit */
3102 if (session->opt->renegotiate_packets && ks->n_packets >= session->opt->renegotiate_packets)
3103 {
3104 return true;
3105 }
3106
3107 /* epoch key id approaching the 16 bit limit */
3109 {
3110 /* We only need to check the send key as we always keep send
3111 * key epoch >= recv key epoch in \c epoch_replace_update_recv_key */
3112 if (ks->crypto_options.epoch_key_send.epoch >= 0xF000)
3113 {
3114 return true;
3115 }
3116 else
3117 {
3118 return false;
3119 }
3120 }
3121
3122
3123 /* Packet id approach the limit of the packet id */
3125 {
3126 return true;
3127 }
3128
3129 /* Check the AEAD usage limit of cleartext blocks + packets.
3130 *
3131 * Contrary to when epoch data mode is active, where only the sender side
3132 * checks the limit, here we check both receive and send limit since
3133 * we assume that only one side is aware of the limit.
3134 *
3135 * Since if both sides were aware, then both sides will probably also
3136 * switch to use epoch data channel instead, so this code is not
3137 * in effect then.
3138 *
3139 * When epoch are in use the crypto layer will handle this internally
3140 * with new epochs instead of triggering a renegotiation */
3141 const struct key_ctx_bi *key_ctx_bi = &ks->crypto_options.key_ctx_bi;
3142 const uint64_t usage_limit = session->opt->aead_usage_limit;
3143
3144 if (aead_usage_limit_reached(usage_limit, &key_ctx_bi->encrypt,
3148 {
3149 return true;
3150 }
3151
3153 {
3154 return true;
3155 }
3156
3157 return false;
3158}
3159
3160#if defined(__GNUC__) || defined(__clang__)
3161#pragma GCC diagnostic pop
3162#endif
3163
3164/*
3165 * This is the primary routine for processing TLS stuff inside the
3166 * the main event loop. When this routine exits
3167 * with non-error status, it will set *wakeup to the number of seconds
3168 * when it wants to be called again.
3169 *
3170 * Return value is true if we have placed a packet in *to_link which we
3171 * want to send to our peer.
3172 */
3173static bool
3174tls_process(struct tls_multi *multi, struct tls_session *session, struct buffer *to_link,
3175 struct link_socket_actual **to_link_addr, struct link_socket_info *to_link_socket_info,
3176 interval_t *wakeup)
3177{
3178 struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
3179 struct key_state *ks_lame = &session->key[KS_LAME_DUCK]; /* retiring key */
3180
3181 /* Make sure we were initialized and that we're not in an error state */
3182 ASSERT(ks->state != S_UNDEF);
3183 ASSERT(ks->state != S_ERROR);
3184 ASSERT(session_id_defined(&session->session_id));
3185
3186 /* Should we trigger a soft reset? -- new key, keeps old key for a while */
3188 {
3190 "TLS: soft reset sec=%d/%d bytes=" counter_format "/%" PRIi64 " pkts=" counter_format
3191 "/%" PRIi64 " aead_limit_send=%" PRIu64 "/%" PRIu64 " aead_limit_recv=%" PRIu64
3192 "/%" PRIu64,
3193 (int)(now - ks->established), session->opt->renegotiate_seconds, ks->n_bytes,
3194 session->opt->renegotiate_bytes, ks->n_packets, session->opt->renegotiate_packets,
3196 session->opt->aead_usage_limit,
3198 session->opt->aead_usage_limit);
3199 key_state_soft_reset(session, to_link);
3200 }
3201
3202 /* Kill lame duck key transition_window seconds after primary key negotiation */
3203 if (lame_duck_must_die(session, wakeup))
3204 {
3205 key_state_free(ks_lame, true, to_link);
3206 msg(D_TLS_DEBUG_LOW, "TLS: tls_process: killed expiring key");
3207 }
3208
3209 bool continue_tls_process = true;
3210 while (continue_tls_process)
3211 {
3212 update_time();
3213
3214 dmsg(D_TLS_DEBUG, "TLS: tls_process: chg=%d ks=%s lame=%s to_link->len=%d wakeup=%d",
3215 continue_tls_process, state_name(ks->state), state_name(ks_lame->state), to_link->len,
3216 *wakeup);
3217 continue_tls_process =
3218 tls_process_state(multi, session, to_link, to_link_addr, to_link_socket_info, wakeup);
3219
3220 if (ks->state == S_ERROR)
3221 {
3222 return false;
3223 }
3224 }
3225
3226 update_time();
3227
3228 /* We often send acks back to back to a following control packet. This
3229 * normally does not create a problem (apart from an extra packet).
3230 * However, with the P_CONTROL_WKC_V1 we need to ensure that the packet
3231 * gets resent if not received by remote, so instead we use an empty
3232 * control packet in this special case */
3233
3234 /* Send 1 or more ACKs (each received control packet gets one ACK) */
3235 if (!to_link->len && !reliable_ack_empty(ks->rec_ack))
3236 {
3238 {
3240 if (!buf)
3241 {
3242 return false;
3243 }
3244
3245 /* We do not write anything to the buffer, this way this will be
3246 * an empty control packet that gets the ack piggybacked and
3247 * also appended the wrapped client key since it has a WCK opcode */
3249 }
3250 else
3251 {
3252 struct buffer buf = ks->ack_write_buf;
3253 ASSERT(buf_init(&buf, multi->opt.frame.buf.headroom));
3254 write_control_auth(session, ks, &buf, to_link_addr, P_ACK_V1, RELIABLE_ACK_SIZE, false);
3255 *to_link = buf;
3256 dmsg(D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP");
3257 }
3258 }
3259
3260 /* When should we wake up again? */
3261 if (ks->state >= S_INITIAL || ks->state == S_ERROR_PRE)
3262 {
3264
3265 if (ks->must_negotiate)
3266 {
3268 }
3269 }
3270
3271 if (ks->established && session->opt->renegotiate_seconds)
3272 {
3273 compute_earliest_wakeup(wakeup, ks->established + session->opt->renegotiate_seconds - now);
3274 }
3275
3276 dmsg(D_TLS_DEBUG, "TLS: tls_process: timeout set to %d", *wakeup);
3277
3278 /* prevent event-loop spinning by setting minimum wakeup of 1 second */
3279 if (*wakeup <= 0)
3280 {
3281 *wakeup = 1;
3282
3283 /* if we had something to send to remote, but to_link was busy,
3284 * let caller know we need to be called again soon */
3285 return true;
3286 }
3287
3288 /* If any of the state changes resulted in the to_link buffer being
3289 * set, we are also active */
3290 if (to_link->len)
3291 {
3292 return true;
3293 }
3294
3295 return false;
3296}
3297
3298static void
3299check_keystate_buf_not_used(struct buffer *to_link, const struct key_state *ks)
3300{
3301 if (ks->state == S_UNDEF || !to_link || !to_link->data)
3302 {
3303 return;
3304 }
3305
3306 const uint8_t *dataptr = to_link->data;
3307
3308 /* we don't expect send_reliable to be NULL when state is
3309 * not S_UNDEF, but people have reported crashes nonetheless,
3310 * therefore we better catch this event, report and exit.
3311 */
3312 if (!ks->send_reliable)
3313 {
3314 msg(M_FATAL,
3315 "ERROR: ks.send_reliable (key-id %d), is NULL "
3316 "while key state is %s. Exiting.",
3317 ks->key_id, state_name(ks->state));
3318 }
3319
3320 for (int j = 0; j < ks->send_reliable->size; j++)
3321 {
3322 if (ks->send_reliable->array[j].buf.data == dataptr)
3323 {
3324 msg(M_INFO,
3325 "Warning buffer of freed TLS session is still in"
3326 " use (key-id %d, ks.send_reliable->array[%d])",
3327 ks->key_id, j);
3328
3329 goto used;
3330 }
3331 }
3332
3333 if (ks->ack_write_buf.data == dataptr)
3334 {
3335 msg(M_INFO, "Warning buffer of freed TLS session is still in use "
3336 "(ks.ack_write_buf, key-id %d)",
3337 ks->key_id);
3338
3339 goto used;
3340 }
3341 return;
3342
3343used:
3344 to_link->len = 0;
3345 to_link->data = 0;
3346}
3347
3355static void
3357{
3358 if (!to_link || !to_link->data)
3359 {
3360 return;
3361 }
3362 const uint8_t *dataptr = to_link->data;
3363
3364 /* Checks buffers in tls_wrap */
3365 if (session->tls_wrap.work.data == dataptr)
3366 {
3367 msg(M_INFO, "Warning buffer of freed TLS session is "
3368 "still in use (tls_wrap.work.data)");
3369 goto used;
3370 }
3371 if (session->tls_wrap_reneg.work.data == dataptr)
3372 {
3373 msg(M_INFO, "Warning buffer of freed TLS session is "
3374 "still in use (tls_wrap_reneg.work.data)");
3375 goto used;
3376 }
3377
3378 for (int i = 0; i < KS_SIZE; i++)
3379 {
3380 const struct key_state *ks = &session->key[i];
3381 check_keystate_buf_not_used(to_link, ks);
3382 }
3383 return;
3384
3385used:
3386 to_link->len = 0;
3387 to_link->data = 0;
3388 /* for debugging, you can add an ASSERT(0); here to trigger an abort */
3389}
3390/*
3391 * Called by the top-level event loop.
3392 *
3393 * Basically decides if we should call tls_process for
3394 * the active or untrusted sessions.
3395 */
3396
3397int
3398tls_multi_process(struct tls_multi *multi, struct buffer *to_link,
3399 struct link_socket_actual **to_link_addr,
3400 struct link_socket_info *to_link_socket_info, interval_t *wakeup)
3401{
3402 struct gc_arena gc = gc_new();
3403 int active = TLSMP_INACTIVE;
3404 bool error = false;
3405 /* kept separate from 'active' on purpose: a restart request must not be
3406 * overwritten by a later TLSMP_ACTIVE/TLSMP_RECONNECT assignment */
3407 bool restart = false;
3408
3410
3411 /*
3412 * Process each session object having state of S_INITIAL or greater,
3413 * and which has a defined remote IP addr.
3414 */
3415
3416 for (int i = 0; i < TM_SIZE; ++i)
3417 {
3418 struct tls_session *session = &multi->session[i];
3419 struct key_state *ks = &session->key[KS_PRIMARY];
3420 const struct key_state *ks_lame = &session->key[KS_LAME_DUCK];
3421
3422 /* set initial remote address. This triggers connecting with that
3423 * session. So we only do that if the TM_ACTIVE session is not
3424 * established */
3425 if (i == TM_INITIAL && ks->state == S_INITIAL && get_primary_key(multi)->state <= S_INITIAL
3426 && link_socket_actual_defined(&to_link_socket_info->lsa->actual))
3427 {
3428 ks->remote_addr = to_link_socket_info->lsa->actual;
3429 }
3430
3432 "TLS: tls_multi_process: i=%d state=%s, mysid=%s, stored-sid=%s, stored-ip=%s", i,
3433 state_name(ks->state), session_id_print(&session->session_id, &gc),
3436
3437 if ((ks->state >= S_INITIAL || ks->state == S_ERROR_PRE)
3439 {
3440 struct link_socket_actual *tla = NULL;
3441
3442 update_time();
3443
3444 if (tls_process(multi, session, to_link, &tla, to_link_socket_info, wakeup))
3445 {
3446 active = TLSMP_ACTIVE;
3447 }
3448
3449 /*
3450 * If tls_process produced an outgoing packet,
3451 * return the link_socket_actual object (which
3452 * contains the outgoing address).
3453 */
3454 if (tla)
3455 {
3456 multi->to_link_addr = *tla;
3457 *to_link_addr = &multi->to_link_addr;
3458 }
3459
3460 /*
3461 * If tls_process hits an error:
3462 * (1) If the session has an unexpired lame duck key, preserve it.
3463 * (2) Reinitialize the session.
3464 * (3) Increment soft error count
3465 */
3466 if (ks->state == S_ERROR)
3467 {
3468 ++multi->n_soft_errors;
3469
3470 if (i == TM_ACTIVE || (i == TM_INITIAL && get_primary_key(multi)->state < S_ACTIVE))
3471 {
3472 error = true;
3473 }
3474
3475 if (i == TM_ACTIVE && ks_lame->state >= S_GENERATED_KEYS
3476 && !multi->opt.single_session)
3477 {
3478 move_session(multi, TM_LAME_DUCK, TM_ACTIVE, true, to_link);
3479 }
3480 else
3481 {
3482 reset_session(multi, session, to_link);
3483 }
3484 }
3485 }
3486 }
3487
3488 update_time();
3489
3491
3492 /* If we have successfully authenticated and are still waiting for the authentication to finish
3493 * move the state machine for the multi context forward */
3494
3495 if (multi->multi_state >= CAS_CONNECT_DONE)
3496 {
3497 /* Only generate keys for the TM_ACTIVE session. We defer generating
3498 * keys for TM_INITIAL until we actually trust it.
3499 * For TM_LAME_DUCK it makes no sense to generate new keys. */
3500 struct tls_session *session = &multi->session[TM_ACTIVE];
3501 struct key_state *ks = &session->key[KS_PRIMARY];
3502
3503 if (ks->state == S_ACTIVE && ks->authenticated == KS_AUTH_TRUE)
3504 {
3505 /* Session is now fully authenticated.
3506 * tls_session_generate_data_channel_keys will move ks->state
3507 * from S_ACTIVE to S_GENERATED_KEYS */
3509 if (status != KEY_GEN_OK)
3510 {
3511 msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
3514 ks->state = S_ERROR_PRE;
3515
3516 /* Invalidating the key state is not enough to recover from a
3517 * DCO desync: the kernel peer has to be re-created, and the
3518 * key state we just invalidated will never be retried, so ask
3519 * for a restart right away */
3521 {
3522 restart = true;
3523 }
3524 }
3525
3526 /* Update auth token on the client if needed on renegotiation
3527 * (key id !=0) */
3528 if (session->key[KS_PRIMARY].key_id != 0)
3529 {
3531 }
3532 }
3533 }
3534
3536 {
3537 multi->multi_state = CAS_PENDING;
3538 }
3539
3540 /*
3541 * If lame duck session expires, kill it.
3542 */
3543 if (lame_duck_must_die(&multi->session[TM_LAME_DUCK], wakeup))
3544 {
3545 tls_session_free(&multi->session[TM_LAME_DUCK], true, to_link);
3546 msg(D_TLS_DEBUG_LOW, "TLS: tls_multi_process: killed expiring key");
3547 }
3548
3549 /*
3550 * If untrusted session achieves TLS authentication,
3551 * move it to active session, usurping any prior session.
3552 *
3553 * A semi-trusted session is one in which the certificate authentication
3554 * succeeded (if cert verification is enabled) but the username/password
3555 * verification failed. A semi-trusted session can forward data on the
3556 * TLS control channel but not on the tunnel channel.
3557 */
3558 if (TLS_AUTHENTICATED(multi, &multi->session[TM_INITIAL].key[KS_PRIMARY]))
3559 {
3560 move_session(multi, TM_ACTIVE, TM_INITIAL, true, to_link);
3561 tas = tls_authentication_status(multi);
3563 "TLS: tls_multi_process: initial untrusted "
3564 "session promoted to %strusted",
3565 tas == TLS_AUTHENTICATION_SUCCEEDED ? "" : "semi-");
3566
3567 if (multi->multi_state == CAS_CONNECT_DONE)
3568 {
3570 active = TLSMP_RECONNECT;
3571 }
3572 }
3573
3574 /*
3575 * A hard error means that TM_ACTIVE hit an S_ERROR state and that no
3576 * other key state objects are S_ACTIVE or higher.
3577 */
3578 if (error)
3579 {
3580 for (int i = 0; i < KEY_SCAN_SIZE; ++i)
3581 {
3582 if (get_key_scan(multi, i)->state >= S_ACTIVE)
3583 {
3584 goto nohard;
3585 }
3586 }
3587 ++multi->n_hard_errors;
3588 }
3589nohard:
3590
3591#ifdef ENABLE_DEBUG
3592 /* DEBUGGING -- flood peer with repeating connection attempts */
3593 {
3594 const int throw_level = GREMLIN_CONNECTION_FLOOD_LEVEL(multi->opt.gremlin);
3595 if (throw_level)
3596 {
3597 for (int i = 0; i < KEY_SCAN_SIZE; ++i)
3598 {
3599 if (get_key_scan(multi, i)->state >= throw_level)
3600 {
3601 ++multi->n_hard_errors;
3602 ++multi->n_soft_errors;
3603 }
3604 }
3605 }
3606 }
3607#endif
3608
3609 gc_free(&gc);
3610
3611 /* strongest outcome wins: killing the session supersedes restarting it,
3612 * and restarting supersedes whatever 'active' ended up being */
3613 if (tas == TLS_AUTHENTICATION_FAILED)
3614 {
3615 return TLSMP_KILL;
3616 }
3617 if (restart)
3618 {
3619 return TLSMP_RESTART;
3620 }
3621 return active;
3622}
3623
3628static void
3630 int key_id)
3631{
3632 struct gc_arena gc = gc_new();
3633 const char *source = print_link_socket_actual(from, &gc);
3634
3635
3636 for (int i = 0; i < KEY_SCAN_SIZE; ++i)
3637 {
3638 const struct key_state *ks = get_key_scan(multi, i);
3639 if (ks->key_id != key_id)
3640 {
3641 continue;
3642 }
3643
3644 /* Our key state has been progressed far enough to be part of a valid
3645 * session but has not generated keys. */
3646 if (ks->state >= S_INITIAL && ks->state < S_GENERATED_KEYS)
3647 {
3648 msg(D_MULTI_DROPPED, "Key %s [%d] not initialized (yet), dropping packet.", source,
3649 key_id);
3650 gc_free(&gc);
3651 return;
3652 }
3653 if (ks->state >= S_ACTIVE && ks->authenticated != KS_AUTH_TRUE)
3654 {
3655 msg(D_MULTI_DROPPED, "Key %s [%d] not authorized%s, dropping packet.", source, key_id,
3656 (ks->authenticated == KS_AUTH_DEFERRED) ? " (deferred)" : "");
3657 gc_free(&gc);
3658 return;
3659 }
3660 }
3661
3663 "TLS Error: local/remote TLS keys are out of sync: %s "
3664 "(received key id: %d, known key ids: %s)",
3665 source, key_id, print_key_id(multi, &gc));
3666 gc_free(&gc);
3667}
3668
3676static inline void
3678 struct buffer *buf, struct crypto_options **opt, bool floated,
3679 const uint8_t **ad_start)
3680{
3681 struct gc_arena gc = gc_new();
3682
3683 uint8_t c = *BPTR(buf);
3684 int op = c >> P_OPCODE_SHIFT;
3685 int key_id = c & P_KEY_ID_MASK;
3686
3687 for (int i = 0; i < KEY_SCAN_SIZE; ++i)
3688 {
3689 struct key_state *ks = get_key_scan(multi, i);
3690
3691 /*
3692 * This is the basic test of TLS state compatibility between a local OpenVPN
3693 * instance and its remote peer.
3694 *
3695 * If the test fails, it tells us that we are getting a packet from a source
3696 * which claims reference to a prior negotiated TLS session, but the local
3697 * OpenVPN instance has no memory of such a negotiation.
3698 *
3699 * It almost always occurs on UDP sessions when the passive side of the
3700 * connection is restarted without the active side restarting as well (the
3701 * passive side is the server which only listens for the connections, the
3702 * active side is the client which initiates connections).
3703 */
3704 if (ks->state >= S_GENERATED_KEYS && key_id == ks->key_id
3705 && ks->authenticated == KS_AUTH_TRUE
3706 && (floated || link_socket_actual_match(from, &ks->remote_addr)))
3707 {
3709 /* return appropriate data channel decrypt key in opt */
3710 *opt = &ks->crypto_options;
3711 if (op == P_DATA_V2)
3712 {
3713 *ad_start = BPTR(buf);
3714 }
3715 ASSERT(buf_advance(buf, 1));
3716 if (op == P_DATA_V1)
3717 {
3718 *ad_start = BPTR(buf);
3719 }
3720 else if (op == P_DATA_V2)
3721 {
3722 if (buf->len < 4)
3723 {
3725 "Protocol error: received P_DATA_V2 from %s but length is < 4",
3727 ++multi->n_soft_errors;
3728 goto done;
3729 }
3730 ASSERT(buf_advance(buf, 3));
3731 }
3732
3733 ++ks->n_packets;
3734 ks->n_bytes += buf->len;
3735 dmsg(D_TLS_KEYSELECT, "TLS: tls_pre_decrypt, key_id=%d, IP=%s", key_id,
3737 gc_free(&gc);
3738 return;
3739 }
3740 }
3741
3743
3744done:
3745 gc_free(&gc);
3747 buf->len = 0;
3748 *opt = NULL;
3749}
3750
3756static bool
3757tls_pre_decrypt_verify_opcode(int op, bool server, const struct link_socket_actual *from)
3758{
3759 if (op < P_FIRST_OPCODE || op > P_LAST_OPCODE)
3760 {
3762 {
3763 msg(D_TLS_ERRORS, "Peer tried unsupported key-method 1");
3764 }
3765 struct gc_arena gc = gc_new();
3766 msg(D_TLS_ERRORS, "TLS Error: unknown opcode received from %s op=%d",
3767 print_link_socket_actual(from, &gc), op);
3768 gc_free(&gc);
3769 return false;
3770 }
3771
3772 /* hard reset ? */
3773 if (is_hard_reset_method2(op))
3774 {
3775 /* verify client -> server or server -> client connection */
3777 && !server)
3778 || ((op == P_CONTROL_HARD_RESET_SERVER_V2) && server))
3779 {
3780 struct gc_arena gc = gc_new();
3782 "TLS Error: client->client or server->server connection attempted from %s",
3784 gc_free(&gc);
3785 return false;
3786 }
3787 }
3788 return true;
3789}
3790
3797static bool
3799 struct buffer buf, struct session_id *sid)
3800{
3801 /* skip op code */
3802 buf_advance(&buf, 1);
3803 if (!session_id_read(sid, &buf) || !session_id_defined(sid))
3804 {
3805 struct gc_arena gc = gc_new();
3806 msg(D_TLS_ERRORS, "TLS Error: session-id not found in packet from %s",
3808 gc_free(&gc);
3809 return false;
3810 }
3811 return true;
3812}
3813
3820static int
3822 const struct session_id *sid)
3823{
3824 struct gc_arena gc = gc_new();
3825 int i;
3826 /* use session ID to match up packet with appropriate tls_session object */
3827 for (i = 0; i < TM_SIZE; ++i)
3828 {
3829 struct tls_session *session = &multi->session[i];
3830 struct key_state *ks = &session->key[KS_PRIMARY];
3831
3832 dmsg(
3834 "TLS: initial packet test, i=%d state=%s, mysid=%s, rec-sid=%s, rec-ip=%s, stored-sid=%s, stored-ip=%s",
3835 i, state_name(ks->state), session_id_print(&session->session_id, &gc),
3839
3840 if (session_id_equal(&ks->session_id_remote, sid))
3841 /* found a match */
3842 {
3843 if (i == TM_LAME_DUCK)
3844 {
3845 msg(D_TLS_ERRORS, "TLS ERROR: received control packet with stale session-id=%s",
3846 session_id_print(sid, &gc));
3847 i = -1;
3848 goto done;
3849 }
3850 dmsg(D_TLS_DEBUG, "TLS: found match, session[%d], sid=%s", i,
3851 session_id_print(sid, &gc));
3852 break;
3853 }
3854 }
3855
3856done:
3857 gc_free(&gc);
3858 return i;
3859}
3860
3861/*
3862 *
3863 * When we are in TLS mode, this is the first routine which sees
3864 * an incoming packet.
3865 *
3866 * If it's a data packet, we set opt so that our caller can
3867 * decrypt it. We also give our caller the appropriate decryption key.
3868 *
3869 * If it's a control packet, we authenticate it and process it,
3870 * possibly creating a new tls_session if it represents the
3871 * first packet of a new session. For control packets, we will
3872 * also zero the size of *buf so that our caller ignores the
3873 * packet on our return.
3874 *
3875 * Note that openvpn only allows one active session at a time,
3876 * so a new session (once authenticated) will always usurp
3877 * an old session.
3878 *
3879 * Return true if input was an authenticated control channel
3880 * packet.
3881 *
3882 * If we are running in TLS thread mode, all public routines
3883 * below this point must be called with the L_TLS lock held.
3884 */
3885
3886bool
3887tls_pre_decrypt(struct tls_multi *multi, const struct link_socket_actual *from, struct buffer *buf,
3888 struct crypto_options **opt, bool floated, const uint8_t **ad_start)
3889{
3890 if (buf->len <= 0)
3891 {
3892 buf->len = 0;
3893 *opt = NULL;
3894 return false;
3895 }
3896
3897 struct gc_arena gc = gc_new();
3898 bool ret = false;
3899
3900 /* get opcode */
3901 uint8_t pkt_firstbyte = *BPTR(buf);
3902 int op = pkt_firstbyte >> P_OPCODE_SHIFT;
3903
3904 if ((op == P_DATA_V1) || (op == P_DATA_V2))
3905 {
3906 handle_data_channel_packet(multi, from, buf, opt, floated, ad_start);
3907 return false;
3908 }
3909
3910 /* get key_id */
3911 int key_id = pkt_firstbyte & P_KEY_ID_MASK;
3912
3913 /* control channel packet */
3914 bool do_burst = false;
3915 bool new_link = false;
3916
3917 /* verify legal opcode */
3918 if (!tls_pre_decrypt_verify_opcode(op, multi->opt.server, from))
3919 {
3920 goto error;
3921 }
3922
3923 /*
3924 * Authenticate Packet
3925 */
3926 dmsg(D_TLS_DEBUG, "TLS: control channel, op=%s, IP=%s", packet_opcode_name(op),
3928
3929 struct session_id sid; /* remote session ID */
3930 if (!tls_pre_decrypt_extract_session_id(from, *buf, &sid))
3931 {
3932 goto error;
3933 }
3934
3935 int i = tls_pre_decrypt_find_session(multi, from, &sid);
3936 if (i == -1)
3937 {
3938 goto error;
3939 }
3940
3941 /*
3942 * Hard reset and session id does not match any session in
3943 * multi->session: Possible initial packet. New sessions always start
3944 * as TM_INITIAL
3945 */
3946 if (i == TM_SIZE && is_hard_reset_method2(op))
3947 {
3948 /*
3949 * No match with existing sessions,
3950 * probably a new session.
3951 */
3952 struct tls_session *session = &multi->session[TM_INITIAL];
3953
3954 /*
3955 * If --single-session, don't allow any hard-reset connection request
3956 * unless it is the first packet of the session.
3957 */
3958 if (multi->opt.single_session && multi->n_sessions)
3959 {
3961 "TLS Error: Cannot accept new session request from %s due "
3962 "to session context expire or --single-session",
3964 goto error;
3965 }
3966
3968 {
3969 goto error;
3970 }
3971
3972#ifdef ENABLE_MANAGEMENT
3973 if (management)
3974 {
3975 management_set_state(management, OPENVPN_STATE_AUTH, NULL, NULL, NULL, NULL, NULL);
3976 }
3977#endif
3978
3979 /*
3980 * New session-initiating control packet is authenticated at this point,
3981 * assuming that the --tls-auth command line option was used.
3982 *
3983 * Without --tls-auth, we leave authentication entirely up to TLS.
3984 */
3985 msg(D_TLS_DEBUG_LOW, "TLS: Initial packet from %s, sid=%s",
3987
3988 do_burst = true;
3989 new_link = true;
3990 i = TM_INITIAL;
3991 session->untrusted_addr = *from;
3992 }
3993 else
3994 {
3995 /*
3996 * Packet must belong to an existing session.
3997 */
3998 if (i != TM_ACTIVE && i != TM_INITIAL)
3999 {
4000 msg(D_TLS_ERRORS, "TLS Error: Unroutable control packet received from %s (si=%d op=%s)",
4002 goto error;
4003 }
4004
4005 struct tls_session *session = &multi->session[i];
4006 struct key_state *ks = &session->key[KS_PRIMARY];
4007 /*
4008 * Verify remote IP address
4009 */
4010 if (!new_link && !link_socket_actual_match(&ks->remote_addr, from))
4011 {
4012 msg(D_TLS_ERRORS, "TLS Error: Received control packet from unexpected IP addr: %s",
4014 goto error;
4015 }
4016
4017 /*
4018 * Remote is requesting a key renegotiation. We only allow renegotiation
4019 * when the previous session is fully established to avoid weird corner
4020 * cases.
4021 */
4023 {
4025 session->opt))
4026 {
4027 goto error;
4028 }
4029
4030 /*
4031 * Do not allow incoming renegotiation unless our primary key is
4032 * fully authenticated and past the deferred-auth/transition gate.
4033 */
4034 time_t auth_deferred_left = ks->auth_deferred_expire - now;
4035 if (ks->authenticated != KS_AUTH_TRUE || auth_deferred_left > 0)
4036 {
4038 "TLS: refusing premature incoming renegotiation request for key-id %d: "
4039 "auth=%s, auth_deferred_expire in %d seconds",
4041 auth_deferred_left > 0 ? (int)auth_deferred_left : 0);
4042 goto done;
4043 }
4044
4046
4047 dmsg(D_TLS_DEBUG, "TLS: received P_CONTROL_SOFT_RESET_V1 s=%d sid=%s", i,
4048 session_id_print(&sid, &gc));
4049 }
4050 else
4051 {
4052 bool initial_packet = false;
4053 if (ks->state == S_PRE_START_SKIP)
4054 {
4055 /* When we are coming from the session_skip_to_pre_start
4056 * method, we allow this initial packet to setup the
4057 * tls-crypt-v2 peer specific key */
4058 initial_packet = true;
4059 ks->state = S_PRE_START;
4060 }
4061 /*
4062 * Remote responding to our key renegotiation request?
4063 */
4064 if (op == P_CONTROL_SOFT_RESET_V1)
4065 {
4066 do_burst = true;
4067 }
4068
4070 from, session->opt))
4071 {
4072 /* if an initial packet in read_control_auth, we rather
4073 * error out than anything else */
4074 if (initial_packet)
4075 {
4076 multi->n_hard_errors++;
4077 }
4078 goto error;
4079 }
4080
4081 dmsg(D_TLS_DEBUG, "TLS: received control channel packet s#=%d sid=%s", i,
4082 session_id_print(&sid, &gc));
4083 }
4084 }
4085
4086 /*
4087 * We have an authenticated control channel packet (if --tls-auth/tls-crypt
4088 * or tls-crypt-v2 was set).
4089 * Now pass to our reliability layer which deals with
4090 * packet acknowledgements, retransmits, sequencing, etc.
4091 */
4092 struct tls_session *session = &multi->session[i];
4093 struct key_state *ks = &session->key[KS_PRIMARY];
4094
4095 /* Make sure we were initialized and that we're not in an error state */
4096 ASSERT(ks->state != S_UNDEF);
4097 ASSERT(ks->state != S_ERROR);
4098 ASSERT(session_id_defined(&session->session_id));
4099
4100 /* Let our caller know we processed a control channel packet */
4101 ret = true;
4102
4103 /*
4104 * Set our remote address and remote session_id
4105 */
4106 if (new_link)
4107 {
4108 ks->session_id_remote = sid;
4109 ks->remote_addr = *from;
4110 ++multi->n_sessions;
4111 }
4112 else if (!link_socket_actual_match(&ks->remote_addr, from))
4113 {
4115 "TLS Error: Existing session control channel packet from unknown IP address: %s",
4117 goto error;
4118 }
4119
4120 /*
4121 * Should we do a retransmit of all unacknowledged packets in
4122 * the send buffer? This improves the start-up efficiency of the
4123 * initial key negotiation after the 2nd peer comes online.
4124 */
4125 if (do_burst && !session->burst)
4126 {
4128 session->burst = true;
4129 }
4130
4131 /* Check key_id */
4132 if (ks->key_id != key_id)
4133 {
4134 msg(D_TLS_ERRORS, "TLS ERROR: local/remote key IDs out of sync (%d/%d) ID: %s", ks->key_id,
4135 key_id, print_key_id(multi, &gc));
4136 goto error;
4137 }
4138
4139 /*
4140 * Process incoming ACKs for packets we can now
4141 * delete from reliable send buffer
4142 */
4143 {
4144 /* buffers all packet IDs to delete from send_reliable */
4145 struct reliable_ack send_ack;
4146
4147 if (!reliable_ack_read(&send_ack, buf, &session->session_id))
4148 {
4149 msg(D_TLS_ERRORS, "TLS Error: reading acknowledgement record from packet");
4150 goto error;
4151 }
4153 }
4154
4155 if (op != P_ACK_V1 && reliable_can_get(ks->rec_reliable))
4156 {
4157 packet_id_type id;
4158
4159 /* Extract the packet ID from the packet */
4160 if (reliable_ack_read_packet_id(buf, &id))
4161 {
4162 /* A hard reset always is the first packet of a session, so it
4163 * always must use packet id 0. Ignore it if it claims another id.
4164 * In a specific existing bug these packets were replays of an
4165 * already handled reset, so ignoring it is better than aborting
4166 * the connection attempt.
4167 */
4168 if (is_hard_reset_method2(op) && id != 0)
4169 {
4171 "TLS Error: received %s with packet id " packet_id_format
4172 " from %s -- 0 was expected, ignoring packet",
4175 }
4176 /* Avoid deadlock by rejecting packet that would de-sequentialize receive buffer */
4178 {
4179 if (reliable_not_replay(ks->rec_reliable, id))
4180 {
4181 /* Save incoming ciphertext packet to reliable buffer */
4182 struct buffer *in = reliable_get_buf(ks->rec_reliable);
4183 ASSERT(in);
4184 if (!buf_copy(in, buf))
4185 {
4186 msg(D_MULTI_DROPPED, "Incoming control channel packet too big, dropping.");
4187 goto error;
4188 }
4190 }
4191
4192 /* Process outgoing acknowledgment for packet just received, even if it's a replay
4193 */
4195 }
4196 }
4197 }
4198 /* Remember that we received a valid control channel packet */
4199 ks->peer_last_packet = now;
4200
4201done:
4202 buf->len = 0;
4203 *opt = NULL;
4204 gc_free(&gc);
4205 return ret;
4206
4207error:
4208 ++multi->n_soft_errors;
4210 goto done;
4211}
4212
4213
4214struct key_state *
4216{
4217 struct key_state *ks_select = NULL;
4218 for (int i = 0; i < KEY_SCAN_SIZE; ++i)
4219 {
4220 struct key_state *ks = get_key_scan(multi, i);
4221 if (ks->state >= S_GENERATED_KEYS && ks->authenticated == KS_AUTH_TRUE)
4222 {
4224
4225 if (!ks_select)
4226 {
4227 ks_select = ks;
4228 }
4229 if (now >= ks->auth_deferred_expire)
4230 {
4231 ks_select = ks;
4232 break;
4233 }
4234 }
4235 }
4236 return ks_select;
4237}
4238
4239
4240/* Choose the key with which to encrypt a data packet */
4241void
4242tls_pre_encrypt(struct tls_multi *multi, struct buffer *buf, struct crypto_options **opt)
4243{
4244 multi->save_ks = NULL;
4245 if (buf->len <= 0)
4246 {
4247 buf->len = 0;
4248 *opt = NULL;
4249 return;
4250 }
4251
4252 struct key_state *ks_select = tls_select_encryption_key(multi);
4253
4254 if (ks_select)
4255 {
4256 *opt = &ks_select->crypto_options;
4257 multi->save_ks = ks_select;
4258 dmsg(D_TLS_KEYSELECT, "TLS: tls_pre_encrypt: key_id=%d", ks_select->key_id);
4259 return;
4260 }
4261 else
4262 {
4263 struct gc_arena gc = gc_new();
4264 dmsg(D_TLS_KEYSELECT, "TLS Warning: no data channel send key available: %s",
4265 print_key_id(multi, &gc));
4266 gc_free(&gc);
4267
4268 *opt = NULL;
4269 buf->len = 0;
4270 }
4271}
4272
4273void
4274tls_prepend_opcode_v1(const struct tls_multi *multi, struct buffer *buf)
4275{
4276 const struct key_state *ks = multi->save_ks;
4277
4278 msg(D_TLS_DEBUG, __func__);
4279
4280 ASSERT(ks);
4281 ASSERT(ks->key_id <= P_KEY_ID_MASK);
4282
4283 uint8_t op = (P_DATA_V1 << P_OPCODE_SHIFT) | (uint8_t)ks->key_id;
4284 ASSERT(buf_write_prepend(buf, &op, 1));
4285}
4286
4287void
4288tls_prepend_opcode_v2(const struct tls_multi *multi, struct buffer *buf)
4289{
4290 const struct key_state *ks = multi->save_ks;
4291 uint32_t peer;
4292
4293 msg(D_TLS_DEBUG, __func__);
4294
4295 ASSERT(ks);
4296 peer = htonl(((P_DATA_V2 << P_OPCODE_SHIFT) | ks->key_id) << 24
4297 | (multi->tx_peer_id & 0xFFFFFF));
4298 ASSERT(buf_write_prepend(buf, &peer, 4));
4299}
4300
4301void
4302tls_post_encrypt(struct tls_multi *multi, const struct buffer *buf)
4303{
4304 struct key_state *ks = multi->save_ks;
4305 multi->save_ks = NULL;
4306
4307 if (buf->len > 0)
4308 {
4309 ASSERT(ks);
4310
4311 ++ks->n_packets;
4312 ks->n_bytes += buf->len;
4313 }
4314}
4315
4316/*
4317 * Send a payload over the TLS control channel.
4318 * Called externally.
4319 */
4320
4321bool
4322tls_send_payload(struct key_state *ks, const uint8_t *data, size_t size)
4323{
4324 bool ret = false;
4325
4327
4328 ASSERT(ks);
4329
4330 if (ks->state >= S_ACTIVE)
4331 {
4332 ASSERT(size <= INT_MAX);
4333 if (key_state_write_plaintext_const(&ks->ks_ssl, data, (int)size) == 1)
4334 {
4335 ret = true;
4336 }
4337 }
4338 else
4339 {
4340 if (!ks->paybuf)
4341 {
4342 ks->paybuf = buffer_list_new();
4343 }
4344 buffer_list_push_data(ks->paybuf, data, size);
4345 ret = true;
4346 }
4347
4348
4350
4351 return ret;
4352}
4353
4354bool
4355tls_rec_payload(struct tls_multi *multi, struct buffer *buf)
4356{
4357 bool ret = false;
4358
4360
4361 ASSERT(multi);
4362
4363 struct key_state *ks = get_key_scan(multi, 0);
4364
4365 if (ks->state >= S_ACTIVE && BLEN(&ks->plaintext_read_buf))
4366 {
4367 if (buf_copy(buf, &ks->plaintext_read_buf))
4368 {
4369 ret = true;
4370 }
4371 ks->plaintext_read_buf.len = 0;
4372 }
4373
4375
4376 return ret;
4377}
4378
4379void
4380tls_update_remote_addr(struct tls_multi *multi, const struct link_socket_actual *addr)
4381{
4382 struct gc_arena gc = gc_new();
4383 for (int i = 0; i < TM_SIZE; ++i)
4384 {
4385 struct tls_session *session = &multi->session[i];
4386
4387 for (int j = 0; j < KS_SIZE; ++j)
4388 {
4389 struct key_state *ks = &session->key[j];
4390
4393 {
4394 continue;
4395 }
4396
4397 dmsg(D_TLS_KEYSELECT, "TLS: tls_update_remote_addr from IP=%s to IP=%s",
4400
4401 ks->remote_addr = *addr;
4402 }
4403 }
4404 gc_free(&gc);
4405}
4406
4407void
4408show_available_tls_ciphers(const char *cipher_list, const char *cipher_list_tls13,
4409 const char *tls_cert_profile)
4410{
4411 printf("Available TLS Ciphers, listed in order of preference:\n");
4412
4414 {
4415 printf("\nFor TLS 1.3 and newer (--tls-ciphersuites):\n\n");
4416 show_available_tls_ciphers_list(cipher_list_tls13, tls_cert_profile, true);
4417 }
4418
4419 printf("\nFor TLS 1.2 and older (--tls-cipher):\n\n");
4420 show_available_tls_ciphers_list(cipher_list, tls_cert_profile, false);
4421
4422 printf("\n"
4423 "Note: Whether a cipher suite in this list can actually work depends\n"
4424 "on the specific setup of both peers. See the man page entries of\n"
4425 "--tls-cipher and --show-tls for more details.\n\n");
4426}
4427
4428/*
4429 * Dump a human-readable rendition of an openvpn packet
4430 * into a garbage collectable string which is returned.
4431 */
4432const char *
4433protocol_dump(const struct buffer *buffer, unsigned int flags, struct gc_arena *gc)
4434{
4435 struct buffer out = alloc_buf_gc(256, gc);
4436 struct buffer buf = *buffer;
4437
4438 uint8_t c;
4439 int op;
4440 int key_id;
4441
4443
4444 if (buf.len <= 0)
4445 {
4446 buf_printf(&out, "DATA UNDEF len=%d", buf.len);
4447 goto done;
4448 }
4449
4450 if (!(flags & PD_TLS))
4451 {
4452 goto print_data;
4453 }
4454
4455 /*
4456 * Initial byte (opcode)
4457 */
4458 if (!buf_read(&buf, &c, sizeof(c)))
4459 {
4460 goto done;
4461 }
4462 op = (c >> P_OPCODE_SHIFT);
4463 key_id = c & P_KEY_ID_MASK;
4464 buf_printf(&out, "%s kid=%d", packet_opcode_name(op), key_id);
4465
4466 if ((op == P_DATA_V1) || (op == P_DATA_V2))
4467 {
4468 goto print_data;
4469 }
4470
4471 /*
4472 * Session ID
4473 */
4474 {
4475 struct session_id sid;
4476
4477 if (!session_id_read(&sid, &buf))
4478 {
4479 goto done;
4480 }
4481 if (flags & PD_VERBOSE)
4482 {
4483 buf_printf(&out, " sid=%s", session_id_print(&sid, gc));
4484 }
4485 }
4486
4487 /*
4488 * tls-auth hmac + packet_id
4489 */
4490 if (tls_auth_hmac_size)
4491 {
4492 struct packet_id_net pin;
4493 uint8_t tls_auth_hmac[MAX_HMAC_KEY_LENGTH];
4494
4495 ASSERT(tls_auth_hmac_size <= MAX_HMAC_KEY_LENGTH);
4496
4497 if (!buf_read(&buf, tls_auth_hmac, tls_auth_hmac_size))
4498 {
4499 goto done;
4500 }
4501 if (flags & PD_VERBOSE)
4502 {
4503 buf_printf(&out, " tls_hmac=%s", format_hex(tls_auth_hmac, tls_auth_hmac_size, 0, gc));
4504 }
4505
4506 if (!packet_id_read(&pin, &buf, true))
4507 {
4508 goto done;
4509 }
4510 buf_printf(&out, " pid=%s", packet_id_net_print(&pin, (flags & PD_VERBOSE), gc));
4511 }
4512 /*
4513 * packet_id + tls-crypt hmac
4514 */
4515 if (flags & PD_TLS_CRYPT)
4516 {
4517 struct packet_id_net pin;
4518 uint8_t tls_crypt_hmac[TLS_CRYPT_TAG_SIZE];
4519
4520 if (!packet_id_read(&pin, &buf, true))
4521 {
4522 goto done;
4523 }
4524 buf_printf(&out, " pid=%s", packet_id_net_print(&pin, (flags & PD_VERBOSE), gc));
4525 if (!buf_read(&buf, tls_crypt_hmac, TLS_CRYPT_TAG_SIZE))
4526 {
4527 goto done;
4528 }
4529 if (flags & PD_VERBOSE)
4530 {
4531 buf_printf(&out, " tls_crypt_hmac=%s",
4532 format_hex(tls_crypt_hmac, TLS_CRYPT_TAG_SIZE, 0, gc));
4533 }
4534 /*
4535 * Remainder is encrypted and optional wKc
4536 */
4537 goto done;
4538 }
4539
4540 /*
4541 * ACK list
4542 */
4543 buf_printf(&out, " %s", reliable_ack_print(&buf, (flags & PD_VERBOSE), gc));
4544
4545 if (op == P_ACK_V1)
4546 {
4547 goto print_data;
4548 }
4549
4550 /*
4551 * Packet ID
4552 */
4553 {
4555 if (!buf_read(&buf, &l, sizeof(l)))
4556 {
4557 goto done;
4558 }
4559 l = ntohpid(l);
4561 }
4562
4563print_data:
4564 if (flags & PD_SHOW_DATA)
4565 {
4566 buf_printf(&out, " DATA %s", format_hex(BPTR(&buf), BLEN(&buf), 80, gc));
4567 }
4568 else
4569 {
4570 buf_printf(&out, " DATA len=%d", buf.len);
4571 }
4572
4573done:
4574 return BSTR(&out);
4575}
4576
4577#if defined(__GNUC__) || defined(__clang__)
4578#pragma GCC diagnostic pop
4579#endif
void determine_common_acc_protocols(struct tls_multi *multi, struct tls_session *session)
Parses the IV_ACC of the peer and sets multi.acc_negotiated_protocols to the common protocols of serv...
Definition acc.c:381
#define ACC_MAX_MSG_LEN
Definition acc.h:34
void wipe_auth_token(struct tls_multi *multi)
Wipes the authentication token out of the memory, frees and cleans up related buffers and flags.
Definition auth_token.c:417
void resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_session *session)
Checks if a client should be sent a new auth token to update its current auth-token.
Definition auth_token.c:476
struct buffer_entry * buffer_list_push_data(struct buffer_list *ol, const void *data, size_t size)
Allocates and appends a new buffer containing data of length size.
Definition buffer.c:1239
void free_buf(struct buffer *buf)
Free the memory allocated for a buffer.
Definition buffer.c:174
void buf_clear(struct buffer *buf)
Zeroise and reset a buffer.
Definition buffer.c:153
void buffer_list_pop(struct buffer_list *ol)
Remove and free the head buffer of the list.
Definition buffer.c:1340
bool buf_printf(struct buffer *buf, const char *format,...)
printf-style append to a buffer with overflow check.
Definition buffer.c:231
struct buffer_list * buffer_list_new(void)
Allocate an empty buffer list of capacity max_size.
Definition buffer.c:1185
struct buffer * buffer_list_peek(struct buffer_list *ol)
Retrieve the head buffer.
Definition buffer.c:1267
void buffer_list_free(struct buffer_list *ol)
Frees a buffer list and all the buffers in it.
Definition buffer.c:1194
void * gc_malloc(size_t size, bool clear, struct gc_arena *a)
Allocate memory and, optionally, zero it.
Definition buffer.c:321
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Allocate a buffer of the given size under garbage collection.
Definition buffer.c:77
char * format_hex_ex(const uint8_t *data, size_t size, size_t maxoutput, unsigned int space_break_flags, const char *separator, struct gc_arena *gc)
Format a binary buffer as a hex string.
Definition buffer.c:460
struct buffer alloc_buf(size_t size)
Allocate a buffer of the given size.
Definition buffer.c:60
char * string_alloc(const char *str, struct gc_arena *gc)
Duplicate a string, allocating memory under garbage collection.
Definition buffer.c:618
static bool buf_write_u16(struct buffer *dest, uint16_t data)
Append a uint16_t to a buffer in network byte order.
Definition buffer.h:1302
#define BSTR(buf)
Return the buffer content pointer cast to char *.
Definition buffer.h:157
static bool buf_copy(struct buffer *dest, const struct buffer *src)
Copy the content of one buffer to the end of another.
Definition buffer.h:1347
#define BPTR(buf)
Return a pointer to the start of the buffer content.
Definition buffer.h:139
static bool buf_write_u32(struct buffer *dest, uint32_t data)
Append a uint32_t to a buffer in network byte order.
Definition buffer.h:1317
static bool buf_write_prepend(struct buffer *dest, const void *src, int size)
Prepend data to a buffer.
Definition buffer.h:1268
static int buf_read_u16(struct buffer *buf)
Read and consume a uint16_t from the front of a buffer.
Definition buffer.h:1516
static bool buf_copy_n(struct buffer *dest, struct buffer *src, int n)
Read n bytes from src and append them to dest.
Definition buffer.h:1365
#define ALLOC_ARRAY_CLEAR_GC(dptr, type, n, gc)
Allocate and zero-initialise a garbage-collected array of n elements.
Definition buffer.h:2091
static bool buf_safe(const struct buffer *buf, size_t len)
Check whether len bytes can be appended to a buffer.
Definition buffer.h:994
static bool buf_read(struct buffer *src, void *dest, int size)
Read bytes from the front of a buffer into a caller-supplied destination.
Definition buffer.h:1456
static int buf_len(const struct buffer *buf)
Return the length of the buffer content.
Definition buffer.h:462
static void secure_memzero(void *data, size_t len)
Securely zeroise memory.
Definition buffer.h:748
static bool buf_advance(struct buffer *buf, ssize_t size)
Advance the content start of a buffer, consuming bytes from the front.
Definition buffer.h:1165
static bool buf_write(struct buffer *dest, const void *src, size_t size)
Append data to a buffer.
Definition buffer.h:1239
static bool buf_write_u8(struct buffer *dest, uint8_t data)
Append a uint8_t to a buffer.
Definition buffer.h:1288
#define ALLOC_OBJ_CLEAR_GC(dptr, type, gc)
Allocate and zero-initialise a garbage-collected object of the given type.
Definition buffer.h:2132
static int buf_read_u8(struct buffer *buf)
Read and consume a uint8_t from the front of a buffer.
Definition buffer.h:1495
#define BLEN(buf)
Return the length of the buffer content in bytes.
Definition buffer.h:151
static char * format_hex(const uint8_t *data, size_t size, size_t maxoutput, struct gc_arena *gc)
Format a binary buffer as a hex string with spaces every 4 bytes.
Definition buffer.h:960
#define BLENZ(buf)
Return the length of the buffer content as a size_t.
Definition buffer.h:153
static void check_malloc_return(void *p)
Abort if a memory allocation returned NULL.
Definition buffer.h:2144
static void gc_free(struct gc_arena *a)
Free all allocations in a garbage collection arena.
Definition buffer.h:1974
#define ALLOC_OBJ_CLEAR(dptr, type)
Allocate and zero-initialise memory for a single object of the given type.
Definition buffer.h:2036
#define buf_init(buf, offset)
Definition buffer.h:364
static struct gc_arena gc_new(void)
Allocate and return a new, empty garbage collection arena.
Definition buffer.h:1958
int interval_t
Definition common.h:37
#define TLS_CHANNEL_BUF_SIZE
Definition common.h:70
#define counter_format
Definition common.h:32
#define TLS_CHANNEL_MTU_MIN
Definition common.h:83
#define COMP_F_MIGRATE
push stub-v2 or comp-lzo no when we see a client with comp-lzo in occ
Definition comp.h:47
size_t strlcpy(char *dest, const char *src, size_t maxlen)
#define PACKAGE_VERSION
Definition config.h:504
#define ENABLE_MANAGEMENT
Definition config.h:53
void free_key_ctx_bi(struct key_ctx_bi *ctx)
Definition crypto.c:1098
void init_key_type(struct key_type *kt, const char *ciphername, const char *authname, bool warn)
Initialize a key_type structure with.
Definition crypto.c:872
void check_key2(struct key2 *key2)
Definition crypto.c:1678
void key2_print(const struct key2 *k, const struct key_type *kt, const char *prefix0, const char *prefix1)
Prints the keys in a key2 structure.
Definition crypto.c:1143
uint64_t cipher_get_aead_limits(const char *ciphername)
Check if the cipher is an AEAD cipher and needs to be limited to a certain number of number of blocks...
Definition crypto.c:349
void init_key_ctx_bi(struct key_ctx_bi *ctx, const struct key2 *key2, int key_direction, const struct key_type *kt, const char *name)
Definition crypto.c:1057
void key_direction_state_init(struct key_direction_state *kds, int key_direction)
Definition crypto.c:1649
int64_t get_random(void)
an analogue to the random() function, but use prng_bytes and also int64_t instead of long to avoid LL...
Definition crypto.c:1703
#define KEY_DIRECTION_NORMAL
Definition crypto.h:225
#define CO_PACKET_ID_LONG_FORM
Bit-flag indicating whether to use OpenVPN's long packet ID format.
Definition crypto.h:335
#define CO_USE_TLS_KEY_MATERIAL_EXPORT
Bit-flag indicating that data channel key derivation is done using TLS keying material export [RFC570...
Definition crypto.h:347
#define CO_USE_DYNAMIC_TLS_CRYPT
Bit-flag indicating that renegotiations are using tls-crypt with a TLS-EKM derived key.
Definition crypto.h:363
#define CO_IGNORE_PACKET_ID
Bit-flag indicating whether to ignore the packet ID of a received packet.
Definition crypto.h:338
#define CO_RESEND_WKC
Bit-flag indicating that the client is expected to resend the wrapped client key with the 2nd packet ...
Definition crypto.h:351
#define CO_EPOCH_DATA_KEY_FORMAT
Bit-flag indicating the epoch the data format.
Definition crypto.h:367
static bool aead_usage_limit_reached(const uint64_t limit, const struct key_ctx *key_ctx, uint64_t higest_pid)
Checks if the usage limit for an AEAD cipher is reached.
Definition crypto.h:749
static bool cipher_decrypt_verify_fail_warn(const struct key_ctx *ctx)
Check if the number of failed decryption is approaching the limit and we should try to move to a new ...
Definition crypto.h:720
#define KEY_DIRECTION_INVERSE
Definition crypto.h:226
bool ssl_tls1_PRF(const uint8_t *seed, size_t seed_len, const uint8_t *secret, size_t secret_len, uint8_t *output, size_t output_len)
Calculates the TLS 1.0-1.1 PRF function.
void crypto_uninit_lib(void)
bool cipher_kt_mode_aead(const char *ciphername)
Check if the supplied cipher is a supported AEAD mode cipher.
void crypto_init_lib(void)
bool cipher_kt_mode_ofb_cfb(const char *ciphername)
Check if the supplied cipher is a supported OFB or CFB mode cipher.
int hmac_ctx_size(hmac_ctx_t *ctx)
bool cipher_kt_insecure(const char *ciphername)
Returns true if we consider this cipher to be insecure.
int rand_bytes(uint8_t *output, int len)
Wrapper for secure random number generator.
const char * cipher_kt_name(const char *ciphername)
Retrieve a normalised string describing the cipher (e.g.
#define MAX_HMAC_KEY_LENGTH
#define OPENVPN_MAX_HMAC_SIZE
void free_epoch_key_ctx(struct crypto_options *co)
Frees the extra data structures used by epoch keys in crypto_options.
void epoch_init_key_ctx(struct crypto_options *co, const struct key_type *key_type, const struct epoch_key *e1_send, const struct epoch_key *e1_recv, uint16_t future_key_count)
Initialises data channel keys and internal structures for epoch data keys using the provided E0 epoch...
static int dco_set_peer(dco_context_t *dco, unsigned int peerid, int keepalive_interval, int keepalive_timeout, int mss)
Definition dco.h:341
void * dco_context_t
Definition dco.h:259
static int init_key_dco_bi(struct tls_multi *multi, struct key_state *ks, const struct key2 *key2, int key_direction, const char *ciphername, bool server)
Definition dco.h:321
void setenv_str(struct env_set *es, const char *name, const char *value)
Definition env_set.c:305
void setenv_del(struct env_set *es, const char *name)
Definition env_set.c:350
#define D_TLS_DEBUG_LOW
Definition errlevel.h:75
#define D_PUSH
Definition errlevel.h:81
#define D_TLS_DEBUG_MED
Definition errlevel.h:153
#define D_DCO
Definition errlevel.h:92
#define D_SHOW_KEYS
Definition errlevel.h:118
#define D_MULTI_DROPPED
Definition errlevel.h:98
#define D_HANDSHAKE
Definition errlevel.h:70
#define D_SHOW_KEY_SOURCE
Definition errlevel.h:119
#define D_TLS_KEYSELECT
Definition errlevel.h:142
#define D_MTU_INFO
Definition errlevel.h:102
#define D_TLS_ERRORS
Definition errlevel.h:58
#define M_INFO
Definition errlevel.h:54
#define D_TLS_DEBUG
Definition errlevel.h:161
#define S_ACTIVE
Operational key_state state immediately after negotiation has completed while still within the handsh...
Definition ssl_common.h:100
#define TM_INITIAL
As yet un-trusted tls_session \ being negotiated.
Definition ssl_common.h:553
#define KS_SIZE
Size of the tls_session.key array.
Definition ssl_common.h:476
static void tls_session_free(struct tls_session *session, bool clear, struct buffer *to_link)
Clean up a tls_session structure.
Definition ssl.c:1082
struct tls_multi * tls_multi_init(const struct tls_options *tls_options)
Allocate and initialize a tls_multi structure.
Definition ssl.c:1192
void tls_init_control_channel_frame_parameters(struct frame *frame, int tls_mtu)
Definition ssl.c:161
void tls_multi_free(struct tls_multi *multi, bool clear)
Cleanup a tls_multi structure and free associated memory allocations.
Definition ssl.c:1285
#define S_ERROR_PRE
Error state but try to send out alerts before killing the keystore and moving it to S_ERROR.
Definition ssl_common.h:79
#define KS_PRIMARY
Primary key state index.
Definition ssl_common.h:472
#define S_PRE_START_SKIP
Waiting for the remote OpenVPN peer to acknowledge during the initial three-way handshake.
Definition ssl_common.h:87
#define S_UNDEF
Undefined state, used after a key_state is cleaned up.
Definition ssl_common.h:82
#define S_START
Three-way handshake is complete, start of key exchange.
Definition ssl_common.h:93
#define S_GOT_KEY
Local OpenVPN process has received the remote's part of the key material.
Definition ssl_common.h:97
#define S_PRE_START
Waiting for the remote OpenVPN peer to acknowledge during the initial three-way handshake.
Definition ssl_common.h:90
void tls_multi_init_finalize(struct tls_multi *multi, int tls_mtu)
Finalize initialization of a tls_multi structure.
Definition ssl.c:1210
#define TM_LAME_DUCK
Old tls_session.
Definition ssl_common.h:556
static void tls_session_init(struct tls_multi *multi, struct tls_session *session)
Initialize a tls_session structure.
Definition ssl.c:1008
#define TM_SIZE
Size of the tls_multi.session \ array.
Definition ssl_common.h:557
struct tls_auth_standalone * tls_auth_standalone_init(const struct tls_options *tls_options, struct gc_arena *gc)
Definition ssl.c:1233
static void key_state_free(struct key_state *ks, bool clear, struct buffer *to_link)
Cleanup a key_state structure.
Definition ssl.c:925
void tls_auth_standalone_free(struct tls_auth_standalone *tas)
Frees a standalone tls-auth verification object.
Definition ssl.c:1258
#define TM_ACTIVE
Active tls_session.
Definition ssl_common.h:552
#define S_GENERATED_KEYS
The data channel keys have been generated The TLS session is fully authenticated when reaching this s...
Definition ssl_common.h:105
#define KS_LAME_DUCK
Key state index that will retire \ soon.
Definition ssl_common.h:473
#define S_SENT_KEY
Local OpenVPN process has sent its part of the key material.
Definition ssl_common.h:95
#define S_ERROR
Error state.
Definition ssl_common.h:78
#define S_INITIAL
Initial key_state state after initialization by key_state_init() before start of three-way handshake.
Definition ssl_common.h:84
static void key_state_init(struct tls_session *session, struct key_state *ks)
Initialize a key_state structure.
Definition ssl.c:838
void tls_multi_init_set_options(struct tls_multi *multi, const char *local, const char *remote)
Definition ssl.c:1274
int key_state_read_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Extract plaintext data from the TLS module.
int key_state_write_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Insert a ciphertext buffer into the TLS module.
int key_state_read_ciphertext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Extract ciphertext data from the TLS module.
int key_state_write_plaintext_const(struct key_state_ssl *ks_ssl, const uint8_t *data, int len)
Insert plaintext data into the TLS module.
int key_state_write_plaintext(struct key_state_ssl *ks_ssl, struct buffer *buf)
Insert a plaintext buffer into the TLS module.
void tls_post_encrypt(struct tls_multi *multi, const struct buffer *buf)
Perform some accounting for the key state used.
Definition ssl.c:4302
struct key_state * tls_select_encryption_key(struct tls_multi *multi)
Selects the primary encryption that should be used to encrypt data of an outgoing packet.
Definition ssl.c:4215
#define TLS_AUTHENTICATED(multi, ks)
Check whether the ks key_state has finished the key exchange part of the OpenVPN hand shake.
Definition ssl_verify.h:113
void tls_prepend_opcode_v1(const struct tls_multi *multi, struct buffer *buf)
Prepend a one-byte OpenVPN data channel P_DATA_V1 opcode to the packet.
Definition ssl.c:4274
void tls_pre_encrypt(struct tls_multi *multi, struct buffer *buf, struct crypto_options **opt)
Choose the appropriate security parameters with which to process an outgoing packet.
Definition ssl.c:4242
void tls_prepend_opcode_v2(const struct tls_multi *multi, struct buffer *buf)
Prepend an OpenVPN data channel P_DATA_V2 header to the packet.
Definition ssl.c:4288
bool tls_pre_decrypt(struct tls_multi *multi, const struct link_socket_actual *from, struct buffer *buf, struct crypto_options **opt, bool floated, const uint8_t **ad_start)
Determine whether an incoming packet is a data channel or control channel packet, and process accordi...
Definition ssl.c:3887
void reliable_mark_deleted(struct reliable *rel, const struct buffer *buf)
Remove an entry from a reliable structure.
Definition reliable.c:824
void reliable_free(struct reliable *rel)
Free allocated memory associated with a reliable structure and the pointer itself.
Definition reliable.c:336
bool reliable_ack_read(struct reliable_ack *ack, struct buffer *buf, const struct session_id *sid)
Read an acknowledgment record from a received packet.
Definition reliable.c:111
struct buffer * reliable_get_buf_output_sequenced(struct reliable *rel)
Get the buffer of free reliable entry and check whether the outgoing acknowledgment sequence is still...
Definition reliable.c:581
void reliable_schedule_now(struct reliable *rel)
Reschedule all entries of a reliable structure to be ready for (re)sending immediately.
Definition reliable.c:708
int reliable_get_num_output_sequenced_available(const struct reliable *rel)
Counts the number of free buffers in output that can be potentially used for sending.
Definition reliable.c:574
bool reliable_ack_read_packet_id(struct buffer *buf, packet_id_type *pid)
Read the packet ID of a received packet.
Definition reliable.c:76
void reliable_mark_active_outgoing(struct reliable *rel, struct buffer *buf, int opcode)
Mark the reliable entry associated with the given buffer as active outgoing.
Definition reliable.c:797
const char * reliable_ack_print(struct buffer *buf, bool verbose, struct gc_arena *gc)
Definition reliable.c:272
bool reliable_ack_acknowledge_packet_id(struct reliable_ack *ack, packet_id_type pid)
Record a packet ID for later acknowledgment.
Definition reliable.c:94
static void reliable_set_timeout(struct reliable *rel, interval_t timeout)
Definition reliable.h:559
void reliable_mark_active_incoming(struct reliable *rel, const struct buffer *buf, packet_id_type pid, int opcode)
Mark the reliable entry associated with the given buffer as active incoming.
Definition reliable.c:760
bool reliable_can_get(const struct reliable *rel)
Check whether a reliable structure has any free buffers available for use.
Definition reliable.c:462
void reliable_send_purge(struct reliable *rel, const struct reliable_ack *ack)
Remove acknowledged packets from a reliable structure.
Definition reliable.c:374
struct buffer * reliable_get_buf(struct reliable *rel)
Get the buffer of a free reliable entry in which to store a packet.
Definition reliable.c:533
struct buffer * reliable_send(struct reliable *rel, int *opcode)
Get the next packet to send to the remote peer.
Definition reliable.c:642
bool reliable_can_send(const struct reliable *rel)
Check whether a reliable structure has any active entries ready to be (re)sent.
Definition reliable.c:616
bool reliable_empty(const struct reliable *rel)
Check whether a reliable structure is empty.
Definition reliable.c:352
static int reliable_ack_outstanding(const struct reliable_ack *ack)
Returns the number of packets that need to be acked.
Definition reliable.h:216
bool reliable_not_replay(const struct reliable *rel, packet_id_type id)
Check that a received packet's ID is not a replay and is inside the receive window.
Definition reliable.c:480
#define RELIABLE_ACK_SIZE
The maximum number of packet IDs waiting to be acknowledged which can be stored in one reliable_ack s...
Definition reliable.h:43
interval_t reliable_send_timeout(const struct reliable *rel)
Determined how many seconds until the earliest resend should be attempted.
Definition reliable.c:726
struct reliable_entry * reliable_get_entry_sequenced(struct reliable *rel)
Get the buffer of the next sequential and active entry.
Definition reliable.c:601
void reliable_init(struct reliable *rel, int buf_size, int offset, int array_size, bool hold)
Initialize a reliable structure.
Definition reliable.c:320
static bool reliable_ack_empty(const struct reliable_ack *ack)
Check whether an acknowledgment structure contains any packet IDs to be acknowledged.
Definition reliable.h:187
bool reliable_wont_break_sequentiality(const struct reliable *rel, packet_id_type id)
Check that a received packet's ID can safely be stored in the reliable structure's processing window.
Definition reliable.c:509
#define ACK_SIZE(n)
Definition reliable.h:81
#define TLS_CRYPT_TAG_SIZE
Definition tls_crypt.h:88
unsigned int tls_crypt_buf_overhead(void)
Returns the maximum overhead (in bytes) added to the destination buffer by tls_crypt_wrap().
Definition tls_crypt.c:56
bool tls_session_generate_dynamic_tls_crypt_key(struct tls_session *session)
Generates a TLS-Crypt key to be used with dynamic tls-crypt using the TLS EKM exporter function.
Definition tls_crypt.c:102
static int min_int(int x, int y)
Definition integer.h:105
static int max_int(int x, int y)
Definition integer.h:92
static SERVICE_STATUS status
Definition interactive.c:52
char * management_query_cert(struct management *man, const char *cert_name)
Definition manage.c:4000
void management_set_state(struct management *man, const int state, const char *detail, const in_addr_t *tun_local_ip, const struct in6_addr *tun_local_ip6, const struct openvpn_sockaddr *local, const struct openvpn_sockaddr *remote)
Definition manage.c:2948
#define MF_EXTERNAL_KEY
Definition manage.h:36
#define OPENVPN_STATE_AUTH
Definition manage.h:469
#define OPENVPN_STATE_WAIT
Definition manage.h:468
#define MF_EXTERNAL_CERT
Definition manage.h:42
static bool management_enable_def_auth(const struct management *man)
Definition manage.h:449
#define VALGRIND_MAKE_READABLE(addr, len)
Definition memdbg.h:49
void unprotect_user_pass(struct user_pass *up)
Decrypt username and password buffers in user_pass.
Definition misc.c:829
bool get_user_pass_cr(struct user_pass *up, const char *auth_file, const char *prefix, const unsigned int flags, const char *auth_challenge)
Retrieves the user credentials from various sources depending on the flags.
Definition misc.c:201
void purge_user_pass(struct user_pass *up, const bool force)
Definition misc.c:485
void set_auth_token_user(struct user_pass *tk, const char *username)
Sets the auth-token username by base64 decoding the passed username.
Definition misc.c:533
void output_peer_info_env(struct env_set *es, const char *peer_info)
Definition misc.c:775
struct buffer prepend_dir(const char *dir, const char *path, struct gc_arena *gc)
Prepend a directory to a path.
Definition misc.c:798
void protect_user_pass(struct user_pass *up)
Encrypt username and password buffers in user_pass.
Definition misc.c:809
void set_auth_token(struct user_pass *tk, const char *token)
Sets the auth-token to token.
Definition misc.c:513
#define USER_PASS_LEN
Definition misc.h:67
#define GET_USER_PASS_STATIC_CHALLENGE_CONCAT
indicates password and response should be concatenated
Definition misc.h:128
#define GET_USER_PASS_MANAGEMENT
Definition misc.h:113
#define GET_USER_PASS_PASSWORD_ONLY
Definition misc.h:115
#define GET_USER_PASS_USERNAME_ONLY
indicate that only username should be prompted for auth-user-pass
Definition misc.h:130
#define GET_USER_PASS_STATIC_CHALLENGE_ECHO
SCRV1 protocol – echo response.
Definition misc.h:123
#define GET_USER_PASS_INLINE_CREDS
indicates that auth_file is actually inline creds
Definition misc.h:126
#define GET_USER_PASS_STATIC_CHALLENGE
SCRV1 protocol – static challenge.
Definition misc.h:122
#define SC_CONCAT
Definition misc.h:95
#define SC_ECHO
Definition misc.h:94
static bool get_user_pass(struct user_pass *up, const char *auth_file, const char *prefix, const unsigned int flags)
Retrieves the user credentials from various sources depending on the flags.
Definition misc.h:155
#define GET_USER_PASS_DYNAMIC_CHALLENGE
CRV1 protocol – dynamic challenge.
Definition misc.h:121
void frame_calculate_dynamic(struct frame *frame, const struct key_type *kt, const struct options *options, const struct link_socket_info *lsi)
Set the –mssfix option.
Definition mss.c:326
void frame_print(const struct frame *frame, msglvl_t msglevel, const char *prefix)
Definition mtu.c:188
#define BUF_SIZE(f)
Definition mtu.h:188
#define OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY
#define OPENVPN_PLUGIN_TLS_FINAL
#define OPENVPN_PLUGIN_FUNC_SUCCESS
#define CLEAR(x)
Definition basic.h:32
static bool check_debug_level(msglvl_t level)
Definition error.h:253
#define M_FATAL
Definition error.h:90
#define dmsg(flags,...)
Definition error.h:164
#define msg(flags,...)
Definition error.h:152
#define ASSERT(x)
Definition error.h:221
#define M_WARN
Definition error.h:92
#define MAX_PEER_ID
Definition openvpn.h:526
bool key_is_external(const struct options *options)
Definition options.c:4054
#define MODE_SERVER
Definition options.h:265
static bool dco_enabled(const struct options *o)
Returns whether the current configuration has dco enabled.
Definition options.h:981
bool options_cmp_equal(char *actual, const char *expected)
char * options_string_extract_option(const char *option_string, const char *opt_name, struct gc_arena *gc)
Given an OpenVPN options string, extract the value of an option.
void options_warning(char *actual, const char *expected)
time_t now
Definition otime.c:33
static void update_time(void)
Definition otime.h:84
void packet_id_init(struct packet_id *p, int seq_backtrack, int time_backtrack, const char *name, int unit)
Definition packet_id.c:96
void packet_id_free(struct packet_id *p)
Definition packet_id.c:126
bool packet_id_read(struct packet_id_net *pin, struct buffer *buf, bool long_form)
Definition packet_id.c:319
const char * packet_id_net_print(const struct packet_id_net *pin, bool print_timestamp, struct gc_arena *gc)
Definition packet_id.c:423
#define packet_id_format
Definition packet_id.h:76
uint64_t packet_id_print_type
Definition packet_id.h:77
uint32_t packet_id_type
Definition packet_id.h:45
static bool packet_id_close_to_wrapping(const struct packet_id_send *p)
Definition packet_id.h:259
static unsigned int packet_id_size(bool long_form)
Definition packet_id.h:253
#define ntohpid(x)
Definition packet_id.h:64
int platform_stat(const char *path, platform_stat_t *buf)
Definition platform.c:531
struct _stat platform_stat_t
Definition platform.h:118
bool plugin_defined(const struct plugin_list *pl, const int type)
Definition plugin.c:919
static int plugin_call(const struct plugin_list *pl, const int type, const struct argv *av, struct plugin_return *pr, struct env_set *es)
Definition plugin.h:195
void get_default_gateway(struct route_gateway_info *rgi, in_addr_t dest, openvpn_net_ctx_t *ctx)
Retrieves the best gateway for a given destination based on the routing table.
Definition route.c:2514
#define RGI_HWADDR_DEFINED
Definition route.h:161
void session_id_random(struct session_id *sid)
Definition session_id.c:48
const char * session_id_print(const struct session_id *sid, struct gc_arena *gc)
Definition session_id.c:54
static bool session_id_equal(const struct session_id *sid1, const struct session_id *sid2)
Definition session_id.h:47
static bool session_id_defined(const struct session_id *sid1)
Definition session_id.h:53
static bool session_id_read(struct session_id *sid, struct buffer *buf)
Definition session_id.h:59
#define SID_SIZE
Definition session_id.h:44
static void link_socket_set_outgoing_addr(struct link_socket_info *info, const struct link_socket_actual *act, const char *common_name, struct env_set *es)
Definition socket.h:551
const char * print_link_socket_actual(const struct link_socket_actual *act, struct gc_arena *gc)
static bool link_socket_actual_defined(const struct link_socket_actual *act)
static int datagram_overhead(sa_family_t af, int proto)
Overhead added to packets by various protocols.
static bool link_socket_actual_match(const struct link_socket_actual *a1, const struct link_socket_actual *a2)
@ PROTO_UDP
void ssl_purge_auth(const bool auth_user_pass_only)
Definition ssl.c:410
static enum key_gen_status tls_session_generate_data_channel_keys(struct tls_multi *multi, struct tls_session *session)
Generate data channel keys for the supplied TLS session.
Definition ssl.c:1625
void ssl_set_auth_token_user(const char *username)
Definition ssl.c:390
struct tls_root_ctx * init_ssl(const struct options *options, bool in_chroot)
Build master SSL context object that serves for the whole of OpenVPN instantiation.
Definition ssl.c:540
static bool tls_process(struct tls_multi *multi, struct tls_session *session, struct buffer *to_link, struct link_socket_actual **to_link_addr, struct link_socket_info *to_link_socket_info, interval_t *wakeup)
Definition ssl.c:3174
static bool tls_session_user_pass_enabled(struct tls_session *session)
Returns whether or not the server should check for username/password.
Definition ssl.c:976
static int auth_deferred_expire_window(const struct tls_options *o)
Definition ssl.c:2528
static uint64_t tls_get_limit_aead(const char *ciphername, uint64_t override)
Definition ssl.c:130
static struct user_pass passbuf
Definition ssl.c:269
static bool check_outgoing_ciphertext(struct key_state *ks, struct tls_session *session, const struct buffer *to_link, bool *continue_tls_process)
Definition ssl.c:2864
static const char * print_key_id(struct tls_multi *multi, struct gc_arena *gc)
Definition ssl.c:782
#define INCR_GENERATED
Definition ssl.c:94
static struct user_pass auth_token
Definition ssl.c:304
static void compute_earliest_wakeup(interval_t *earliest, time_t seconds_from_now)
Definition ssl.c:1148
static bool lame_duck_must_die(const struct tls_session *session, interval_t *wakeup)
Definition ssl.c:1165
void ssl_set_auth_nocache(void)
Definition ssl.c:365
static enum key_gen_status init_key_contexts(struct key_state *ks, struct tls_multi *multi, const struct key_type *key_type, bool server, const struct key2 *key2, bool dco)
Definition ssl.c:1449
static const char * ks_auth_name(enum ks_auth_state auth)
Definition ssl.c:741
static int key_source2_read(struct key_source2 *k2, struct buffer *buf, bool server)
Definition ssl.c:1795
static void handle_data_channel_packet(struct tls_multi *multi, const struct link_socket_actual *from, struct buffer *buf, struct crypto_options **opt, bool floated, const uint8_t **ad_start)
Check the keyid of the an incoming data channel packet and return the matching crypto parameters in o...
Definition ssl.c:3677
bool tls_send_payload(struct key_state *ks, const uint8_t *data, size_t size)
Definition ssl.c:4322
static void reset_session(struct tls_multi *multi, struct tls_session *session, struct buffer *to_link)
Definition ssl.c:1137
static void export_user_keying_material(struct tls_session *session)
Definition ssl.c:2302
void ssl_put_auth_challenge(const char *cr_str)
Definition ssl.c:435
#define INCR_SUCCESS
Definition ssl.c:95
int pem_password_callback(char *buf, int size, int rwflag, void *u)
Callback to retrieve the user's password.
Definition ssl.c:283
static bool control_packet_needs_wkc(const struct key_state *ks)
Definition ssl.c:2746
void tls_update_remote_addr(struct tls_multi *multi, const struct link_socket_actual *addr)
Updates remote address in TLS sessions.
Definition ssl.c:4380
static bool read_incoming_tls_ciphertext(struct buffer *buf, struct key_state *ks, bool *continue_tls_process)
Read incoming ciphertext and passes it to the buffer of the SSL library.
Definition ssl.c:2720
static bool tls_pre_decrypt_verify_opcode(int op, bool server, const struct link_socket_actual *from)
Does a very coarse check on the received opcode.
Definition ssl.c:3757
bool tls_session_update_crypto_params(struct tls_multi *multi, struct tls_session *session, struct options *options, struct frame *frame, struct frame *frame_fragment, const struct link_socket_info *lsi, dco_context_t *dco)
Update TLS session crypto parameters (cipher and auth) and derive data channel keys based on the supp...
Definition ssl.c:1730
static bool push_peer_info_peerid(struct buffer *out, const struct tls_multi *multi, const struct tls_session *session)
Definition ssl.c:1948
static void key_source2_print(const struct key_source2 *k)
Definition ssl.c:1340
static struct user_pass auth_user_pass
Definition ssl.c:303
bool tls_rec_payload(struct tls_multi *multi, struct buffer *buf)
Definition ssl.c:4355
static bool write_outgoing_tls_ciphertext(struct tls_session *session, bool *continue_tls_process)
Definition ssl.c:2778
static bool tls_pre_decrypt_extract_session_id(const struct link_socket_actual *from, struct buffer buf, struct session_id *sid)
Read the session form the packet buffer buf and puts it into the parameter sid.
Definition ssl.c:3798
static void check_session_buf_not_used(struct buffer *to_link, struct tls_session *session)
This is a safe guard function to double check that a buffer from a session is not used in a session t...
Definition ssl.c:3356
static void check_keystate_buf_not_used(struct buffer *to_link, const struct key_state *ks)
Definition ssl.c:3299
bool session_skip_to_pre_start(struct tls_session *session, const struct tls_pre_decrypt_state *state, const struct link_socket_actual *from)
Definition ssl.c:2635
static void flush_payload_buffer(struct key_state *ks)
Definition ssl.c:1827
static void print_key_id_not_found_reason(struct tls_multi *multi, const struct link_socket_actual *from, int key_id)
We have not found a matching key to decrypt data channel packet, try to generate a sensible error mes...
Definition ssl.c:3629
void tls_session_soft_reset(struct tls_multi *tls_multi)
Definition ssl.c:1858
void auth_user_pass_setup(const char *auth_file, bool is_inline, bool username_only, const struct static_challenge_info *sci)
Definition ssl.c:317
bool is_hard_reset_method2(int op)
Given a key_method, return true if opcode represents the one of the hard_reset op codes for key-metho...
Definition ssl.c:798
static char * read_string_alloc(struct buffer *buf)
Definition ssl.c:1927
key_gen_status
Outcome of generating the data channel keys of a session.
Definition ssl.c:1442
@ KEY_GEN_DCO_DESYNC
the DCO peer is gone from the kernel
Definition ssl.c:1445
@ KEY_GEN_FAILED
generation failed, invalidate the key state
Definition ssl.c:1444
@ KEY_GEN_OK
keys were generated and installed
Definition ssl.c:1443
static bool should_trigger_renegotiation(const struct tls_session *session, const struct key_state *ks)
Determines if a renegotiation should be triggerred based on the various factors that can trigger one.
Definition ssl.c:3086
int tls_version_parse(const char *vstr, const char *extra)
Definition ssl.c:449
static int read_string(struct buffer *buf, char *str, const unsigned int capacity)
Read a string that is encoded as a 2 byte header with the length from the buffer buf.
Definition ssl.c:1908
const char * protocol_dump(const struct buffer *buffer, unsigned int flags, struct gc_arena *gc)
Definition ssl.c:4433
static const char * session_index_name(int index)
Definition ssl.c:760
static void session_move_active(struct tls_multi *multi, struct tls_session *session, struct link_socket_info *to_link_socket_info, struct key_state *ks)
Moves the key to state to S_ACTIVE and also advances the multi_state state machine if this is the ini...
Definition ssl.c:2592
static bool random_bytes_to_buf(struct buffer *buf, uint8_t *out, int outlen)
Definition ssl.c:1749
static void move_session(struct tls_multi *multi, int dest, int src, bool reinit_src, struct buffer *to_link)
Definition ssl.c:1112
void ssl_set_auth_token(const char *token)
Definition ssl.c:384
static bool openvpn_PRF(const uint8_t *secret, size_t secret_len, const char *label, const uint8_t *client_seed, size_t client_seed_len, const uint8_t *server_seed, size_t server_seed_len, const struct session_id *client_sid, const struct session_id *server_sid, uint8_t *output, size_t output_len)
Definition ssl.c:1352
#define INCR_SENT
Definition ssl.c:93
static void init_epoch_keys(struct key_state *ks, struct tls_multi *multi, const struct key_type *key_type, bool server, const struct key2 *key2)
Definition ssl.c:1386
static enum key_gen_status generate_key_expansion(struct tls_multi *multi, struct key_state *ks, struct tls_session *session)
Definition ssl.c:1569
int tls_multi_process(struct tls_multi *multi, struct buffer *to_link, struct link_socket_actual **to_link_addr, struct link_socket_info *to_link_socket_info, interval_t *wakeup)
Definition ssl.c:3398
static bool tls_process_state(struct tls_multi *multi, struct tls_session *session, struct buffer *to_link, struct link_socket_actual **to_link_addr, struct link_socket_info *to_link_socket_info, interval_t *wakeup)
Definition ssl.c:2890
static void key_state_soft_reset(struct tls_session *session, struct buffer *to_link)
Definition ssl.c:1843
bool ssl_get_auth_nocache(void)
Definition ssl.c:375
static bool key_method_2_write(struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
Handle the writing of key data, peer-info, username/password, OCC to the TLS control channel (clearte...
Definition ssl.c:2181
void pem_password_setup(const char *auth_file)
Definition ssl.c:272
void init_ssl_lib(void)
Definition ssl.c:249
static void key_source_print(const struct key_source *k, const char *prefix)
Definition ssl.c:1321
static bool write_empty_string(struct buffer *buf)
Definition ssl.c:1868
static void tls_limit_reneg_bytes(const char *ciphername, int64_t *reneg_bytes)
Limit the reneg_bytes value when using a small-block (<128 bytes) cipher.
Definition ssl.c:116
void free_ssl_lib(void)
Definition ssl.c:257
static bool parse_early_negotiation_tlvs(struct buffer *buf, const struct tls_session *session, struct key_state *ks)
Parses the TLVs (type, length, value) in the early negotiation.
Definition ssl.c:2660
static int tls_pre_decrypt_find_session(struct tls_multi *multi, const struct link_socket_actual *from, const struct session_id *sid)
Find session matching the session id in sid in multi.session array.
Definition ssl.c:3821
static bool push_peer_info(struct buffer *buf, const struct tls_multi *multi, struct tls_session *session)
Prepares the IV_ and UV_ variables that are part of the exchange to signal the peer's capabilities.
Definition ssl.c:1984
static bool auth_user_pass_enabled
Definition ssl.c:302
static char * auth_challenge
Definition ssl.c:307
static bool key_source2_randomize_write(struct key_source2 *k2, struct buffer *buf, bool server)
Definition ssl.c:1764
static const char * state_name(int state)
Definition ssl.c:698
bool tls_session_update_crypto_params_do_work(struct tls_multi *multi, struct tls_session *session, const struct options *options, struct frame *frame, struct frame *frame_fragment, const struct link_socket_info *lsi, dco_context_t *dco)
Definition ssl.c:1657
static bool generate_key_expansion_openvpn_prf(const struct tls_session *session, struct key2 *key2)
Definition ssl.c:1522
#define INCR_ERROR
Definition ssl.c:96
static void tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file, bool crl_file_inline)
Load (or possibly reload) the CRL file into the SSL context.
Definition ssl.c:490
static size_t calc_control_channel_frame_overhead(const struct tls_session *session)
calculate the maximum overhead that control channel frames have This includes header,...
Definition ssl.c:208
static bool generate_key_expansion_tls_export(struct tls_session *session, struct key2 *key2)
Definition ssl.c:1508
bool ssl_clean_auth_token(void)
Definition ssl.c:399
static bool write_string(struct buffer *buf, const char *str, const int maxlen)
Definition ssl.c:1878
void enable_auth_user_pass(void)
Definition ssl.c:311
void ssl_purge_auth_challenge(void)
Definition ssl.c:428
void show_available_tls_ciphers(const char *cipher_list, const char *cipher_list_tls13, const char *tls_cert_profile)
Definition ssl.c:4408
static bool read_incoming_tls_plaintext(struct key_state *ks, struct buffer *buf, interval_t *wakeup, bool *continue_tls_process)
Definition ssl.c:2753
static bool key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
Handle reading key data, peer-info, username/password, OCC from the TLS control channel (cleartext).
Definition ssl.c:2336
static bool session_move_pre_start(const struct tls_session *session, struct key_state *ks, bool skip_initial_send)
Move the session from S_INITIAL to S_PRE_START.
Definition ssl.c:2547
Control Channel SSL/Data channel negotiation module.
#define IV_PROTO_CC_EXIT_NOTIFY
Support for explicit exit notify via control channel This also includes support for the protocol-flag...
Definition ssl.h:102
#define TLSMP_RECONNECT
Definition ssl.h:232
#define IV_PROTO_DATA_EPOCH
Support the extended packet id and epoch format for data channel packets.
Definition ssl.h:111
void load_xkey_provider(void)
Load ovpn.xkey provider used for external key signing.
static void tls_wrap_free(struct tls_wrap_ctx *tls_wrap)
Free the elements of a tls_wrap_ctx structure.
Definition ssl.h:475
#define IV_PROTO_AUTH_FAIL_TEMP
Support for AUTH_FAIL,TEMP messages.
Definition ssl.h:105
#define IV_PROTO_DATA_V2
Support P_DATA_V2.
Definition ssl.h:80
#define KEY_METHOD_2
Definition ssl.h:122
#define CONTROL_SEND_ACK_MAX
Definition ssl.h:55
#define TLSMP_ACTIVE
Definition ssl.h:230
#define KEY_EXPANSION_ID
Definition ssl.h:49
#define IV_PROTO_TLS_KEY_EXPORT
Supports key derivation via TLS key material exporter [RFC5705].
Definition ssl.h:87
#define PD_TLS_CRYPT
Definition ssl.h:528
#define PD_TLS
Definition ssl.h:526
#define IV_PROTO_PUSH_UPDATE
Supports push-update.
Definition ssl.h:117
#define IV_PROTO_AUTH_PENDING_KW
Supports signaling keywords with AUTH_PENDING, e.g.
Definition ssl.h:90
#define PD_VERBOSE
Definition ssl.h:527
#define TLSMP_RESTART
the session cannot recover on its own and has to be restarted
Definition ssl.h:234
#define IV_PROTO_DYN_TLS_CRYPT
Support to dynamic tls-crypt (renegotiation with TLS-EKM derived tls-crypt key)
Definition ssl.h:108
#define TLSMP_KILL
Definition ssl.h:231
#define PD_SHOW_DATA
Definition ssl.h:525
#define IV_PROTO_REQUEST_PUSH
Assume client will send a push request and server does not need to wait for a push-request to send a ...
Definition ssl.h:84
#define KEY_METHOD_MASK
Definition ssl.h:125
#define IV_PROTO_DNS_OPTION_V2
Supports the –dns option after all the incompatible changes.
Definition ssl.h:114
#define PD_TLS_AUTH_HMAC_SIZE_MASK
Definition ssl.h:524
#define IV_PROTO_NCP_P2P
Support doing NCP in P2P mode.
Definition ssl.h:95
#define TLSMP_INACTIVE
Definition ssl.h:229
#define TLS_OPTIONS_LEN
Definition ssl.h:69
Control Channel SSL library backend module.
void tls_ctx_set_tls_groups(struct tls_root_ctx *ctx, const char *groups)
Set the (elliptic curve) group allowed for signatures and key exchange.
void tls_ctx_free(struct tls_root_ctx *ctx)
Frees the library-specific TLSv1 context.
const char * get_ssl_library_version(void)
return a pointer to a static memory area containing the name and version number of the SSL library in...
void tls_clear_error(void)
Clear the underlying SSL library's error state.
bool key_state_export_keying_material(struct tls_session *session, const char *label, size_t label_size, void *ekm, size_t ekm_size)
Keying Material Exporters [RFC 5705] allows additional keying material to be derived from existing TL...
#define TLS_VER_BAD
Parse a TLS version specifier.
void show_available_tls_ciphers_list(const char *cipher_list, const char *tls_cert_profile, bool tls13)
Show the TLS ciphers that are available for us to use in the library depending on the TLS version.
#define TLS_VER_1_0
#define EXPORT_KEY_DATA_LABEL
void key_state_ssl_free(struct key_state_ssl *ks_ssl)
Free the SSL channel part of the given key state.
#define TLS_VER_1_2
int tls_ctx_load_priv_file(struct tls_root_ctx *ctx, const char *priv_key_file, bool priv_key_file_inline)
Load private key file into the given TLS context.
void key_state_ssl_shutdown(struct key_state_ssl *ks_ssl)
Sets a TLS session to be shutdown state, so the TLS library will generate a shutdown alert.
void tls_ctx_load_extra_certs(struct tls_root_ctx *ctx, const char *extra_certs_file, bool extra_certs_file_inline)
Load extra certificate authority certificates from the given file or path.
void tls_ctx_check_cert_time(const struct tls_root_ctx *ctx)
Check our certificate notBefore and notAfter fields, and warn if the cert is either not yet valid or ...
void tls_ctx_restrict_ciphers_tls13(struct tls_root_ctx *ctx, const char *ciphers)
Restrict the list of ciphers that can be used within the TLS context for TLS 1.3 and higher.
int tls_ctx_load_pkcs12(struct tls_root_ctx *ctx, const char *pkcs12_file, bool pkcs12_file_inline, bool load_ca_file)
Load PKCS #12 file for key, cert and (optionally) CA certs, and add to library-specific TLS context.
void key_state_ssl_init(struct key_state_ssl *ks_ssl, const struct tls_root_ctx *ssl_ctx, bool is_server, struct tls_session *session)
Initialise the SSL channel part of the given key state.
void tls_free_lib(void)
Free any global SSL library-specific data structures.
Definition ssl_openssl.c:98
void tls_ctx_load_ecdh_params(struct tls_root_ctx *ctx, const char *curve_name)
Load Elliptic Curve Parameters, and load them into the library-specific TLS context.
#define TLS_VER_1_3
#define TLS_VER_1_1
void tls_init_lib(void)
Perform any static initialisation necessary by the library.
Definition ssl_openssl.c:91
void print_details(struct key_state_ssl *ks_ssl, const char *prefix)
Print a one line summary of SSL/TLS session handshake.
int tls_version_max(void)
Return the maximum TLS version (as a TLS_VER_x constant) supported by current SSL implementation.
void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file, bool crl_inline)
Reload the Certificate Revocation List for the SSL channel.
void tls_ctx_restrict_ciphers(struct tls_root_ctx *ctx, const char *ciphers)
Restrict the list of ciphers that can be used within the TLS context for TLS 1.2 and below.
void tls_ctx_load_ca(struct tls_root_ctx *ctx, const char *ca_file, bool ca_file_inline, const char *ca_path, bool tls_server)
Load certificate authority certificates from the given file or path.
void tls_ctx_set_cert_profile(struct tls_root_ctx *ctx, const char *profile)
Set the TLS certificate profile.
int tls_ctx_use_management_external_key(struct tls_root_ctx *ctx)
Tell the management interface to load the given certificate and the external private key matching the...
void tls_ctx_load_cryptoapi(struct tls_root_ctx *ctx, const char *cryptoapi_cert)
Use Windows cryptoapi for key and cert, and add to library-specific TLS context.
bool tls_ctx_set_options(struct tls_root_ctx *ctx, unsigned int ssl_flags)
Set any library specific options.
void tls_ctx_load_dh_params(struct tls_root_ctx *ctx, const char *dh_file, bool dh_file_inline)
Load Diffie Hellman Parameters, and load them into the library-specific TLS context.
void tls_ctx_new(struct tls_root_ctx *ctx)
Initialise a library-specific TLS context.
void tls_ctx_load_cert_file(struct tls_root_ctx *ctx, const char *cert_file, bool cert_file_inline)
Load certificate file into the given TLS context.
#define KEY_SCAN_SIZE
Definition ssl_common.h:574
static struct key_state * get_key_scan(struct tls_multi *multi, int index)
gets an item of key_state objects in the order they should be scanned by data channel modules.
Definition ssl_common.h:748
#define UP_TYPE_PRIVATE_KEY
Definition ssl_common.h:42
#define SSLF_AUTH_USER_PASS_OPTIONAL
Definition ssl_common.h:431
@ CAS_CONNECT_DONE
Definition ssl_common.h:601
@ CAS_WAITING_AUTH
Initial TLS connection established but deferred auth is not yet finished.
Definition ssl_common.h:589
@ CAS_PENDING
Options import (Connect script/plugin, ccd,...)
Definition ssl_common.h:590
@ CAS_WAITING_OPTIONS_IMPORT
client with pull or p2p waiting for first time options import
Definition ssl_common.h:594
@ CAS_NOT_CONNECTED
Definition ssl_common.h:588
@ CAS_RECONNECT_PENDING
session has already successful established (CAS_CONNECT_DONE) but has a reconnect and needs to redo s...
Definition ssl_common.h:600
ks_auth_state
This reflects the (server side) authentication state after the TLS session has been established and k...
Definition ssl_common.h:153
@ KS_AUTH_TRUE
Key state is authenticated.
Definition ssl_common.h:157
@ KS_AUTH_FALSE
Key state is not authenticated
Definition ssl_common.h:154
@ KS_AUTH_DEFERRED
Key state authentication is being deferred, by async auth.
Definition ssl_common.h:155
#define SSLF_CRL_VERIFY_DIR
Definition ssl_common.h:433
#define UP_TYPE_AUTH
Definition ssl_common.h:41
static const struct key_state * get_primary_key(const struct tls_multi *multi)
gets an item of key_state objects in the order they should be scanned by data channel modules.
Definition ssl_common.h:771
bool check_session_cipher(struct tls_session *session, struct options *options)
Checks if the cipher is allowed, otherwise returns false and reset the cipher to the config cipher.
Definition ssl_ncp.c:529
void p2p_mode_ncp(struct tls_multi *multi, struct tls_session *session)
Determines if there is common cipher of both peer by looking at the IV_CIPHER peer info.
Definition ssl_ncp.c:484
bool tls_item_in_cipher_list(const char *item, const char *list)
Return true iff item is present in the colon-separated zero-terminated cipher list.
Definition ssl_ncp.c:197
Control Channel SSL/Data dynamic negotiation Module This file is split from ssl.h to be able to unit ...
void write_control_auth(struct tls_session *session, struct key_state *ks, struct buffer *buf, struct link_socket_actual **to_link_addr, int opcode, int max_ack, bool prepend_ack)
Definition ssl_pkt.c:171
bool read_control_auth(struct buffer *buf, struct tls_wrap_ctx *ctx, const struct link_socket_actual *from, const struct tls_options *opt)
Read a control channel authentication record.
Definition ssl_pkt.c:201
#define EARLY_NEG_FLAG_RESEND_WKC
Definition ssl_pkt.h:314
#define P_DATA_V1
Definition ssl_pkt.h:47
#define P_DATA_V2
Definition ssl_pkt.h:48
#define P_OPCODE_SHIFT
Definition ssl_pkt.h:39
#define TLV_TYPE_EARLY_NEG_FLAGS
Definition ssl_pkt.h:313
#define P_ACK_V1
Definition ssl_pkt.h:46
#define P_CONTROL_WKC_V1
Definition ssl_pkt.h:59
#define P_CONTROL_HARD_RESET_CLIENT_V1
Definition ssl_pkt.h:42
#define P_KEY_ID_MASK
Definition ssl_pkt.h:38
#define TLS_RELIABLE_N_REC_BUFFERS
Definition ssl_pkt.h:71
static const char * packet_opcode_name(int op)
Definition ssl_pkt.h:232
#define P_CONTROL_HARD_RESET_SERVER_V2
Definition ssl_pkt.h:52
#define P_CONTROL_SOFT_RESET_V1
Definition ssl_pkt.h:44
#define P_CONTROL_V1
Definition ssl_pkt.h:45
#define P_LAST_OPCODE
Definition ssl_pkt.h:65
#define EARLY_NEG_START
Definition ssl_pkt.h:306
#define P_CONTROL_HARD_RESET_CLIENT_V2
Definition ssl_pkt.h:51
#define P_CONTROL_HARD_RESET_SERVER_V1
Definition ssl_pkt.h:43
static struct tls_wrap_ctx * tls_session_get_tls_wrap(struct tls_session *session, int key_id)
Determines if the current session should use the renegotiation tls wrap struct instead the normal one...
Definition ssl_pkt.h:283
#define P_CONTROL_HARD_RESET_CLIENT_V3
Definition ssl_pkt.h:55
#define TLS_RELIABLE_N_SEND_BUFFERS
Definition ssl_pkt.h:70
const char * options_string_compat_lzo(const char *options, struct gc_arena *gc)
Takes a locally produced OCC string for TLS server mode and modifies as if the option comp-lzo was en...
Definition ssl_util.c:131
uint32_t extract_asymmetric_peer_id(const char *peer_info)
Extracts the ID variable and returns its value or MAX_PEER_ID if it cannot be extracted.
Definition ssl_util.c:119
SSL utility functions.
void key_state_rm_auth_control_files(struct auth_deferred_status *ads)
Removes auth_pending and auth_control files from file system and key_state structure.
Definition ssl_verify.c:991
void tls_x509_clear_env(struct env_set *es)
Remove any X509_ env variables from env_set es.
void verify_final_auth_checks(struct tls_multi *multi, struct tls_session *session)
Perform final authentication checks, including locking of the cn, the allowed certificate hashes,...
void auth_set_client_reason(struct tls_multi *multi, const char *client_reason)
Sets the reason why authentication of a client failed.
Definition ssl_verify.c:828
enum tls_auth_status tls_authentication_status(struct tls_multi *multi)
Return current session authentication state of the tls_multi structure This will return TLS_AUTHENTIC...
void verify_user_pass(struct user_pass *up, struct tls_multi *multi, struct tls_session *session)
Main username/password verification entry point.
void cert_hash_free(struct cert_hash_set *chs)
Frees the given set of certificate hashes.
Definition ssl_verify.c:215
Control Channel Verification Module.
tls_auth_status
Definition ssl_verify.h:74
@ TLS_AUTHENTICATION_SUCCEEDED
Definition ssl_verify.h:75
@ TLS_AUTHENTICATION_FAILED
Definition ssl_verify.h:76
Wrapper structure for dynamically allocated memory.
Definition buffer.h:71
uint8_t * data
Pointer to the allocated memory.
Definition buffer.h:78
int len
Length in bytes of the actual content within the allocated memory.
Definition buffer.h:76
Security parameter state for processing data channel packets.
Definition crypto.h:286
struct epoch_key epoch_key_send
last epoch_key used for generation of the current send data keys.
Definition crypto.h:296
uint64_t aead_usage_limit
The limit for AEAD cipher, this is the sum of packets + blocks that are allowed to be used.
Definition crypto.h:308
unsigned int flags
Bit-flags determining behavior of security operation functions.
Definition crypto.h:374
struct key_ctx_bi key_ctx_bi
OpenSSL cipher and HMAC contexts for both sending and receiving directions.
Definition crypto.h:287
struct packet_id packet_id
Current packet ID state for both sending and receiving directions.
Definition crypto.h:326
struct env_item * list
Definition env_set.h:45
uint8_t epoch_key[SHA256_DIGEST_LENGTH]
Definition crypto.h:186
uint16_t epoch
Definition crypto.h:187
Packet geometry parameters.
Definition mtu.h:113
int tun_mtu
the (user) configured tun-mtu.
Definition mtu.h:147
int payload_size
the maximum size that a payload that our buffers can hold from either tun device or network link.
Definition mtu.h:118
int headroom
the headroom in the buffer, this is choosen to allow all potential header to be added before the pack...
Definition mtu.h:124
uint16_t mss_fix
The actual MSS value that should be written to the payload packets.
Definition mtu.h:134
struct frame::@8 buf
int tailroom
the tailroom in the buffer.
Definition mtu.h:128
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:127
Container for bidirectional cipher and HMAC key material.
Definition crypto.h:233
int n
The number of key objects stored in the key2.keys array.
Definition crypto.h:234
struct key keys[2]
Two unidirectional sets of key material.
Definition crypto.h:236
Container for two sets of OpenSSL cipher and/or HMAC contexts for both sending and receiving directio...
Definition crypto.h:273
bool initialized
Definition crypto.h:278
struct key_ctx decrypt
cipher and/or HMAC contexts for receiving direction.
Definition crypto.h:276
struct key_ctx encrypt
Cipher and/or HMAC contexts for sending direction.
Definition crypto.h:274
uint64_t plaintext_blocks
Counter for the number of plaintext block encrypted using this cipher with the current key in number ...
Definition crypto.h:215
Key ordering of the key2.keys array.
Definition crypto.h:252
int in_key
Index into the key2.keys array for the receiving direction.
Definition crypto.h:255
int out_key
Index into the key2.keys array for the sending direction.
Definition crypto.h:253
Container for both halves of random material to be used in key method 2 data channel key generation.
Definition ssl_common.h:139
struct key_source client
Random provided by client.
Definition ssl_common.h:140
struct key_source server
Random provided by server.
Definition ssl_common.h:141
Container for one half of random material to be used in key method 2 data channel key generation.
Definition ssl_common.h:121
uint8_t random1[32]
Seed used for master secret generation, provided by both client and server.
Definition ssl_common.h:125
uint8_t pre_master[48]
Random used for master secret generation, provided only by client OpenVPN peer.
Definition ssl_common.h:122
uint8_t random2[32]
Seed used for key expansion, provided by both client and server.
Definition ssl_common.h:128
Security parameter state of one TLS and data channel key session.
Definition ssl_common.h:208
struct buffer_list * paybuf
Holds outgoing message for the control channel until ks->state reaches S_ACTIVE.
Definition ssl_common.h:252
struct crypto_options crypto_options
Definition ssl_common.h:237
struct buffer ack_write_buf
Definition ssl_common.h:243
struct buffer plaintext_read_buf
Definition ssl_common.h:241
struct auth_deferred_status plugin_auth
Definition ssl_common.h:268
time_t must_die
Definition ssl_common.h:230
struct buffer plaintext_write_buf
Definition ssl_common.h:242
struct link_socket_actual remote_addr
Definition ssl_common.h:235
time_t established
Definition ssl_common.h:228
struct key_state_ssl ks_ssl
Definition ssl_common.h:225
time_t must_negotiate
Definition ssl_common.h:229
struct reliable_ack * rec_ack
Definition ssl_common.h:247
struct reliable * rec_reliable
Definition ssl_common.h:246
struct session_id session_id_remote
Definition ssl_common.h:234
unsigned int mda_key_id
Definition ssl_common.h:263
struct auth_deferred_status script_auth
Definition ssl_common.h:269
time_t initial
Definition ssl_common.h:227
enum ks_auth_state authenticated
Definition ssl_common.h:259
int key_id
Key id for this key_state, inherited from struct tls_session.
Definition ssl_common.h:217
time_t peer_last_packet
Definition ssl_common.h:231
struct reliable * send_reliable
Definition ssl_common.h:245
time_t auth_deferred_expire
Definition ssl_common.h:260
int initial_opcode
Definition ssl_common.h:233
struct reliable_ack * lru_acks
Definition ssl_common.h:248
struct key_source2 * key_src
Definition ssl_common.h:239
counter_type n_bytes
Definition ssl_common.h:253
counter_type n_packets
Definition ssl_common.h:254
const char * cipher
const name of the cipher
Definition crypto.h:135
Container for unidirectional cipher and HMAC key material.
Definition crypto.h:145
uint8_t cipher[MAX_CIPHER_KEY_LENGTH]
Key material for cipher operations.
Definition crypto.h:146
uint8_t hmac[MAX_HMAC_KEY_LENGTH]
Key material for HMAC operations.
Definition crypto.h:148
unsigned int imported_protocol_flags
Definition options.h:735
bool crl_file_inline
Definition options.h:613
const char * cryptoapi_cert
Definition options.h:635
bool pkcs12_file_inline
Definition options.h:602
const char * ca_file
Definition options.h:590
unsigned int ssl_flags
Definition options.h:622
const char * authname
Definition options.h:579
bool dh_file_inline
Definition options.h:594
const char * pkcs12_file
Definition options.h:601
const char * tls_groups
Definition options.h:605
const char * tls_cert_profile
Definition options.h:606
unsigned int management_flags
Definition options.h:459
const char * ciphername
Definition options.h:573
bool tls_server
Definition options.h:588
const char * extra_certs_file
Definition options.h:597
bool priv_key_file_inline
Definition options.h:600
const char * crl_file
Definition options.h:612
const char * dh_file
Definition options.h:593
bool ca_file_inline
Definition options.h:591
bool extra_certs_file_inline
Definition options.h:598
const char * cipher_list_tls13
Definition options.h:604
const char * ecdh_curve
Definition options.h:607
const char * cipher_list
Definition options.h:603
const char * management_certificate
Definition options.h:456
const char * chroot_dir
Definition options.h:379
const char * ca_path
Definition options.h:592
int ping_rec_timeout
Definition options.h:351
int ping_send_timeout
Definition options.h:350
const char * priv_key_file
Definition options.h:599
const char * cert_file
Definition options.h:595
bool cert_file_inline
Definition options.h:596
Data structure for describing the packet id that is received/send to the network.
Definition packet_id.h:171
uint64_t id
Definition packet_id.h:117
uint64_t id
Definition packet_id.h:133
struct packet_id_send send
Definition packet_id.h:180
struct packet_id_rec rec
Definition packet_id.h:181
The acknowledgment structure in which packet IDs are stored for later acknowledgment.
Definition reliable.h:75
The structure in which the reliability layer stores a single incoming or outgoing packet.
Definition reliable.h:88
struct buffer buf
Definition reliable.h:97
int opcode
Definition reliable.h:96
packet_id_type packet_id
Definition reliable.h:92
The reliability layer storage structure for one VPN tunnel's control channel in one direction.
Definition reliable.h:105
struct reliable_entry array[RELIABLE_CAPACITY]
Definition reliable.h:111
int size
Definition reliable.h:106
packet_id_type packet_id
Packet ID for the next packet to be sent out.
Definition reliable.h:108
uint8_t hwaddr[6]
Definition route.h:177
unsigned int flags
Definition route.h:165
unsigned int flags
Definition misc.h:96
const char * challenge_text
Definition misc.h:98
struct frame frame
Definition ssl_pkt.h:81
struct tls_wrap_ctx tls_wrap
Definition ssl_pkt.h:79
Security parameter state for a single VPN tunnel.
Definition ssl_common.h:619
int n_hard_errors
Definition ssl_common.h:645
bool remote_usescomp
remote announced comp-lzo in OCC string
Definition ssl_common.h:713
struct link_socket_actual to_link_addr
Definition ssl_common.h:636
char * peer_info
A multi-line string of general-purpose info received from peer over control channel.
Definition ssl_common.h:680
struct key_state * save_ks
Definition ssl_common.h:630
char * remote_ciphername
cipher specified in peer's config file
Definition ssl_common.h:712
char * locked_username
The locked username is the username we assume the client is using.
Definition ssl_common.h:657
enum multi_status multi_state
Definition ssl_common.h:640
struct tls_options opt
Definition ssl_common.h:624
struct tls_session session[TM_SIZE]
Array of tls_session objects representing control channel sessions with the remote peer.
Definition ssl_common.h:721
struct cert_hash_set * locked_cert_hash_set
Definition ssl_common.h:663
char * locked_cn
Our locked common name, username, and cert hashes (cannot change during the life of this tls_multi ob...
Definition ssl_common.h:652
bool use_peer_id
Definition ssl_common.h:709
bool use_asymmetric_peer_id
Definition ssl_common.h:710
uint32_t tx_peer_id
Definition ssl_common.h:708
char * acc_negotiated_protocols
the protocols that are negotiated with the peer.
Definition ssl_common.h:738
char * locked_original_username
The username that client initially used before being overridden by –override-user.
Definition ssl_common.h:661
int n_sessions
Number of sessions negotiated thus far.
Definition ssl_common.h:638
uint32_t rx_peer_id
Definition ssl_common.h:707
int dco_peer_id
This is the handle that DCO uses to identify this session with the kernel.
Definition ssl_common.h:733
int n_soft_errors
Definition ssl_common.h:646
uint64_t aead_usage_limit_override
Debug only option that allows overriding the usage limit This allows testing key rotation by using ve...
Definition ssl_common.h:353
struct tls_wrap_ctx tls_wrap
TLS handshake wrapping state.
Definition ssl_common.h:391
unsigned int crypto_flags
Definition ssl_common.h:372
interval_t renegotiate_seconds
Definition ssl_common.h:354
struct frame frame
Definition ssl_common.h:393
const char * remote_options
Definition ssl_common.h:324
bool single_session
Definition ssl_common.h:327
const char * local_options
Definition ssl_common.h:323
int handshake_window
Definition ssl_common.h:342
bool dco_enabled
Whether keys have to be installed in DCO or not.
Definition ssl_common.h:459
int replay_window
Definition ssl_common.h:374
struct that stores the temporary data for the tls lite decrypt functions
Definition ssl_pkt.h:106
Structure that wraps the TLS context.
Definition ssl_mbedtls.h:86
off_t crl_last_size
size of last loaded CRL
Definition ssl_mbedtls.h:94
time_t crl_last_mtime
CRL last modification time.
Definition ssl_mbedtls.h:93
Security parameter state of a single session within a VPN tunnel.
Definition ssl_common.h:497
int key_id
The current active key id, used to keep track of renegotiations.
Definition ssl_common.h:519
struct key_state key[KS_SIZE]
Definition ssl_common.h:532
struct tls_options * opt
Definition ssl_common.h:499
struct crypto_options opt
Crypto state.
Definition ssl_common.h:283
bool token_defined
Definition misc.h:59
bool protected
Definition misc.h:61
bool defined
Definition misc.h:56
char password[USER_PASS_LEN]
Definition misc.h:71
bool nocache
Definition misc.h:60
char username[USER_PASS_LEN]
Definition misc.h:70
static int cleanup(void **state)
struct gc_arena gc
Definition test_ssl.c:138
const char * win32_version_string(struct gc_arena *gc)
Get Windows version string with architecture info.
Definition win32.c:1415