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 "ssl_verify.h"
59#include "ssl_backend.h"
60#include "ssl_ncp.h"
61#include "ssl_util.h"
62#include "auth_token.h"
63#include "mss.h"
64#include "dco.h"
65#include "options_string.h"
66
67#include "memdbg.h"
68#include "openvpn.h"
69
70#ifdef MEASURE_TLS_HANDSHAKE_STATS
71
72static int tls_handshake_success; /* GLOBAL */
73static int tls_handshake_error; /* GLOBAL */
74static int tls_packets_generated; /* GLOBAL */
75static int tls_packets_sent; /* GLOBAL */
76
77#define INCR_SENT ++tls_packets_sent
78#define INCR_GENERATED ++tls_packets_generated
79#define INCR_SUCCESS ++tls_handshake_success
80#define INCR_ERROR ++tls_handshake_error
81
82void
83show_tls_performance_stats(void)
84{
85 msg(D_TLS_DEBUG_LOW, "TLS Handshakes, success=%f%% (good=%d, bad=%d), retransmits=%f%%",
86 (double)tls_handshake_success / (tls_handshake_success + tls_handshake_error) * 100.0,
87 tls_handshake_success, tls_handshake_error,
88 (double)(tls_packets_sent - tls_packets_generated) / tls_packets_generated * 100.0);
89}
90#else /* ifdef MEASURE_TLS_HANDSHAKE_STATS */
91
92#define INCR_SENT
93#define INCR_GENERATED
94#define INCR_SUCCESS
95#define INCR_ERROR
96
97#endif /* ifdef MEASURE_TLS_HANDSHAKE_STATS */
98
99/* forward decleration since tls_process needs this function prototype */
100static void
101check_session_buf_not_used(struct buffer *to_link, struct tls_session *session);
102
103static void
104check_keystate_buf_not_used(struct buffer *to_link, const struct key_state *ks);
105
106
114static void
115tls_limit_reneg_bytes(const char *ciphername, int64_t *reneg_bytes)
116{
117 if (cipher_kt_insecure(ciphername))
118 {
119 if (*reneg_bytes == -1) /* Not user-specified */
120 {
121 msg(M_WARN, "WARNING: cipher with small block size in use, "
122 "reducing reneg-bytes to 64MB to mitigate SWEET32 attacks.");
123 *reneg_bytes = 64 * 1024 * 1024;
124 }
125 }
126}
127
128static uint64_t
129tls_get_limit_aead(const char *ciphername)
130{
131 uint64_t limit = cipher_get_aead_limits(ciphername);
132
133 if (limit == 0)
134 {
135 return 0;
136 }
137
138 /* set limit to 7/8 of the limit so the renegotiation can succeed before
139 * we go over the limit */
140 limit = limit / 8 * 7;
141
143 "Note: AEAD cipher %s will trigger a renegotiation"
144 " at a sum of %" PRIi64 " blocks and packets.",
145 ciphername, limit);
146 return limit;
147}
148
149void
151{
152 /*
153 * frame->extra_frame is already initialized with tls_auth buffer requirements,
154 * if --tls-auth is enabled.
155 */
156
157 /* calculates the maximum overhead that control channel frames can have */
158 int overhead = 0;
159
160 /* Socks */
161 overhead += 10;
162
163 /* tls-auth and tls-crypt */
165
166 /* TCP length field and opcode */
167 overhead += 3;
168
169 /* ACK array and remote SESSION ID (part of the ACK array) */
170 overhead += ACK_SIZE(RELIABLE_ACK_SIZE);
171
172 /* Previous OpenVPN version calculated the maximum size and buffer of a
173 * control frame depending on the overhead of the data channel frame
174 * overhead and limited its maximum size to 1250. Since control frames
175 * also need to fit into data channel buffer we have the same
176 * default of 1500 + 100 as data channel buffers have. Increasing
177 * control channel mtu beyond this limit also increases the data channel
178 * buffers */
179 frame->buf.payload_size = max_int(1500, tls_mtu) + 100;
180
181 frame->buf.headroom = overhead;
182 frame->buf.tailroom = overhead;
183
184 frame->tun_mtu = tls_mtu;
185
186 /* Ensure the tun-mtu stays in a valid range */
189}
190
196static size_t
198{
199 const struct key_state *ks = &session->key[KS_PRIMARY];
200 size_t overhead = 0;
201
202 /* opcode */
203 overhead += 1;
204
205 /* our own session id */
206 overhead += SID_SIZE;
207
208 /* ACK array and remote SESSION ID (part of the ACK array) */
209 int ackstosend = reliable_ack_outstanding(ks->rec_ack) + ks->lru_acks->len;
210 overhead += ACK_SIZE(min_int(ackstosend, CONTROL_SEND_ACK_MAX));
211
212 /* Message packet id */
213 overhead += sizeof(packet_id_type);
214
215 if (session->tls_wrap.mode == TLS_WRAP_CRYPT)
216 {
217 overhead += tls_crypt_buf_overhead();
218 }
219 else if (session->tls_wrap.mode == TLS_WRAP_AUTH)
220 {
221 overhead += hmac_ctx_size(session->tls_wrap.opt.key_ctx_bi.encrypt.hmac);
222 overhead += packet_id_size(true);
223 }
224
225 /* Add the typical UDP overhead for an IPv6 UDP packet. TCP+IPv6 has a
226 * larger overhead but the risk of a TCP connection getting dropped because
227 * we try to send a too large packet is basically zero */
228 overhead += datagram_overhead(session->untrusted_addr.dest.addr.sa.sa_family, PROTO_UDP);
229
230 return overhead;
231}
232
233void
235{
236 tls_init_lib();
237
239}
240
241void
243{
245
246 tls_free_lib();
247}
248
249/*
250 * OpenSSL library calls pem_password_callback if the
251 * private key is protected by a password.
252 */
253
254static struct user_pass passbuf; /* GLOBAL */
255
256void
257pem_password_setup(const char *auth_file)
258{
260 if (!strlen(passbuf.password))
261 {
264 }
265}
266
267int
268pem_password_callback(char *buf, int size, int rwflag, void *u)
269{
270 if (buf)
271 {
272 /* prompt for password even if --askpass wasn't specified */
273 pem_password_setup(NULL);
275 strncpynt(buf, passbuf.password, (size_t)size);
276 purge_user_pass(&passbuf, false);
277
278 return (int)strlen(buf);
279 }
280 return 0;
281}
282
283/*
284 * Auth username/password handling
285 */
286
287static bool auth_user_pass_enabled; /* GLOBAL */
288static struct user_pass auth_user_pass; /* GLOBAL */
289static struct user_pass auth_token; /* GLOBAL */
290
291#ifdef ENABLE_MANAGEMENT
292static char *auth_challenge; /* GLOBAL */
293#endif
294
295void
300
301void
302auth_user_pass_setup(const char *auth_file, bool is_inline, bool username_only,
303 const struct static_challenge_info *sci)
304{
305 unsigned int flags = GET_USER_PASS_MANAGEMENT;
306
307 if (is_inline)
308 {
310 }
311 if (username_only)
312 {
314 }
315
317 {
319#ifdef ENABLE_MANAGEMENT
320 if (auth_challenge) /* dynamic challenge/response */
321 {
324 }
325 else if (sci) /* static challenge response */
326 {
328 if (sci->flags & SC_ECHO)
329 {
331 }
332 if (sci->flags & SC_CONCAT)
333 {
335 }
337 }
338 else
339#endif /* ifdef ENABLE_MANAGEMENT */
340 {
341 get_user_pass(&auth_user_pass, auth_file, UP_TYPE_AUTH, flags);
342 }
343 }
344}
345
346/*
347 * Disable password caching
348 */
349void
351{
352 passbuf.nocache = true;
353 auth_user_pass.nocache = true;
354}
355
356/*
357 * Get the password caching
358 */
359bool
361{
362 return passbuf.nocache;
363}
364
365/*
366 * Set an authentication token
367 */
368void
369ssl_set_auth_token(const char *token)
370{
371 set_auth_token(&auth_token, token);
372}
373
374void
379
380/*
381 * Cleans an auth token and checks if it was active
382 */
383bool
385{
386 bool wasdefined = auth_token.defined;
388 return wasdefined;
389}
390
391/*
392 * Forget private key password AND auth-user-pass username/password.
393 */
394void
395ssl_purge_auth(const bool auth_user_pass_only)
396{
397 if (!auth_user_pass_only)
398 {
399#ifdef ENABLE_PKCS11
400 pkcs11_logout();
401#endif
402 purge_user_pass(&passbuf, true);
403 }
405#ifdef ENABLE_MANAGEMENT
407#endif
408}
409
410#ifdef ENABLE_MANAGEMENT
411
412void
414{
415 free(auth_challenge);
416 auth_challenge = NULL;
417}
418
419void
420ssl_put_auth_challenge(const char *cr_str)
421{
423 auth_challenge = string_alloc(cr_str, NULL);
424}
425
426#endif
427
428/*
429 * Parse a TLS version string, returning a TLS_VER_x constant.
430 * If version string is not recognized and extra == "or-highest",
431 * return tls_version_max().
432 */
433int
434tls_version_parse(const char *vstr, const char *extra)
435{
436 const int max_version = tls_version_max();
437 if (!strcmp(vstr, "1.0") && TLS_VER_1_0 <= max_version)
438 {
439 return TLS_VER_1_0;
440 }
441 else if (!strcmp(vstr, "1.1") && TLS_VER_1_1 <= max_version)
442 {
443 return TLS_VER_1_1;
444 }
445 else if (!strcmp(vstr, "1.2") && TLS_VER_1_2 <= max_version)
446 {
447 return TLS_VER_1_2;
448 }
449 else if (!strcmp(vstr, "1.3") && TLS_VER_1_3 <= max_version)
450 {
451 return TLS_VER_1_3;
452 }
453 else if (extra && !strcmp(extra, "or-highest"))
454 {
455 return max_version;
456 }
457 else
458 {
459 return TLS_VER_BAD;
460 }
461}
462
474static void
475tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx, const char *crl_file, bool crl_file_inline)
476{
477 /* if something goes wrong with stat(), we'll store 0 as mtime */
478 platform_stat_t crl_stat = { 0 };
479
480 /*
481 * an inline CRL can't change at runtime, therefore there is no need to
482 * reload it. It will be reloaded upon config change + SIGHUP.
483 * Use always '1' as dummy timestamp in this case: it will trigger the
484 * first load, but will prevent any future reload.
485 */
486 if (crl_file_inline)
487 {
488 crl_stat.st_mtime = 1;
489 }
490 else if (platform_stat(crl_file, &crl_stat) < 0)
491 {
492 /* If crl_last_mtime is zero, the CRL file has not been read before. */
493 if (ssl_ctx->crl_last_mtime == 0)
494 {
495 msg(M_FATAL, "ERROR: Failed to stat CRL file during initialization, exiting.");
496 }
497 else
498 {
499 msg(M_WARN, "WARNING: Failed to stat CRL file, not reloading CRL.");
500 }
501 return;
502 }
503
504 /*
505 * Store the CRL if this is the first time or if the file was changed since
506 * the last load.
507 * Note: Windows does not support tv_nsec.
508 */
509 if ((ssl_ctx->crl_last_size == crl_stat.st_size)
510 && (ssl_ctx->crl_last_mtime == crl_stat.st_mtime))
511 {
512 return;
513 }
514
515 ssl_ctx->crl_last_mtime = crl_stat.st_mtime;
516 ssl_ctx->crl_last_size = crl_stat.st_size;
517 backend_tls_ctx_reload_crl(ssl_ctx, crl_file, crl_file_inline);
518}
519
520/*
521 * Initialize SSL context.
522 * All files are in PEM format.
523 */
524struct tls_root_ctx *
525init_ssl(const struct options *options, bool in_chroot)
526{
528
530 {
532 }
533
534 struct tls_root_ctx *new_ctx;
535 ALLOC_OBJ_CLEAR(new_ctx, struct tls_root_ctx);
536
537 tls_ctx_new(new_ctx);
538
540 {
542 }
543
544 /* Restrict allowed certificate crypto algorithms */
546
547 /* Allowable ciphers */
548 /* Since @SECLEVEL also influences loading of certificates, set the
549 * cipher restrictions before loading certificates */
552
553 /* Set the allow groups/curves for TLS if we want to override them */
554 if (options->tls_groups)
555 {
557 }
558
559 if (!tls_ctx_set_options(new_ctx, options->ssl_flags))
560 {
561 goto err;
562 }
563
564 if (options->pkcs12_file)
565 {
566 if (0
568 !options->ca_file))
569 {
570 goto err;
571 }
572 }
573#ifdef ENABLE_PKCS11
574 else if (options->pkcs11_providers[0])
575 {
576 if (!tls_ctx_use_pkcs11(new_ctx, options->pkcs11_id_management, options->pkcs11_id))
577 {
578 msg(M_WARN, "Cannot load certificate \"%s\" using PKCS#11 interface",
579 options->pkcs11_id);
580 goto err;
581 }
582 }
583#endif
584#ifdef ENABLE_CRYPTOAPI
585 else if (options->cryptoapi_cert)
586 {
588 }
589#endif
590#ifdef ENABLE_MANAGEMENT
592 {
594 tls_ctx_load_cert_file(new_ctx, cert, true);
595 free(cert);
596 }
597#endif
598 else if (options->cert_file)
599 {
601 }
602
604 {
605 if (0
608 {
609 goto err;
610 }
611 }
612#ifdef ENABLE_MANAGEMENT
614 {
616 {
617 msg(M_WARN, "Cannot initialize mamagement-external-key");
618 goto err;
619 }
620 }
621#endif
622
624 {
627 }
628
629 /* Load extra certificates that are part of our own certificate
630 * chain but shouldn't be included in the verify chain */
632 {
635 }
636
637 /* Check certificate notBefore and notAfter */
639
640 /* Read CRL */
642 {
643 /* If we're running with the chroot option, we may run init_ssl() before
644 * and after chroot-ing. We can use the crl_file path as-is if we're
645 * not going to chroot, or if we already are inside the chroot.
646 *
647 * If we're going to chroot later, we need to prefix the path of the
648 * chroot directory to crl_file.
649 */
650 if (!options->chroot_dir || in_chroot || options->crl_file_inline)
651 {
653 }
654 else
655 {
656 struct gc_arena gc = gc_new();
659 gc_free(&gc);
660 }
661 }
662
663 /* Once keys and cert are loaded, load ECDH parameters */
664 if (options->tls_server)
665 {
667 }
668
669#ifdef ENABLE_CRYPTO_MBEDTLS
670 /* Personalise the random by mixing in the certificate */
672#endif
673
675 return new_ctx;
676
677err:
680 free(new_ctx);
681 return NULL;
682}
683
684/*
685 * Map internal constants to ascii names.
686 */
687static const char *
688state_name(int state)
689{
690 switch (state)
691 {
692 case S_UNDEF:
693 return "S_UNDEF";
694
695 case S_INITIAL:
696 return "S_INITIAL";
697
698 case S_PRE_START_SKIP:
699 return "S_PRE_START_SKIP";
700
701 case S_PRE_START:
702 return "S_PRE_START";
703
704 case S_START:
705 return "S_START";
706
707 case S_SENT_KEY:
708 return "S_SENT_KEY";
709
710 case S_GOT_KEY:
711 return "S_GOT_KEY";
712
713 case S_ACTIVE:
714 return "S_ACTIVE";
715
716 case S_ERROR:
717 return "S_ERROR";
718
719 case S_ERROR_PRE:
720 return "S_ERROR_PRE";
721
722 case S_GENERATED_KEYS:
723 return "S_GENERATED_KEYS";
724
725 default:
726 return "S_???";
727 }
728}
729
730static const char *
732{
733 switch (auth)
734 {
735 case KS_AUTH_TRUE:
736 return "KS_AUTH_TRUE";
737
738 case KS_AUTH_DEFERRED:
739 return "KS_AUTH_DEFERRED";
740
741 case KS_AUTH_FALSE:
742 return "KS_AUTH_FALSE";
743
744 default:
745 return "KS_????";
746 }
747}
748
749static const char *
751{
752 switch (index)
753 {
754 case TM_ACTIVE:
755 return "TM_ACTIVE";
756
757 case TM_INITIAL:
758 return "TM_INITIAL";
759
760 case TM_LAME_DUCK:
761 return "TM_LAME_DUCK";
762
763 default:
764 return "TM_???";
765 }
766}
767
768/*
769 * For debugging.
770 */
771static const char *
772print_key_id(struct tls_multi *multi, struct gc_arena *gc)
773{
774 struct buffer out = alloc_buf_gc(256, gc);
775
776 for (int i = 0; i < KEY_SCAN_SIZE; ++i)
777 {
778 struct key_state *ks = get_key_scan(multi, i);
779 buf_printf(&out, " [key#%d state=%s auth=%s id=%d sid=%s]", i, state_name(ks->state),
782 }
783
784 return BSTR(&out);
785}
786
787bool
789{
792 {
793 return true;
794 }
795
796 return false;
797}
798
822static void
824{
825 update_time();
826
827 CLEAR(*ks);
828
829 /*
830 * Build TLS object that reads/writes ciphertext
831 * to/from memory BIOs.
832 */
833 key_state_ssl_init(&ks->ks_ssl, session->opt->ssl_ctx, session->opt->server, session);
834
835 /* Set control-channel initiation mode */
836 ks->initial_opcode = session->initial_opcode;
837 session->initial_opcode = P_CONTROL_SOFT_RESET_V1;
838 ks->state = S_INITIAL;
839 ks->key_id = session->key_id;
840
841 /*
842 * key_id increments to KEY_ID_MASK then recycles back to 1.
843 * This way you know that if key_id is 0, it is the first key.
844 */
845 ++session->key_id;
846 session->key_id &= P_KEY_ID_MASK;
847 if (!session->key_id)
848 {
849 session->key_id = 1;
850 }
851
852 /* allocate key source material object */
854
855 /* allocate reliability objects */
860
861 /* allocate buffers */
864 ks->ack_write_buf = alloc_buf(BUF_SIZE(&session->opt->frame));
865 reliable_init(ks->send_reliable, BUF_SIZE(&session->opt->frame),
866 session->opt->frame.buf.headroom, TLS_RELIABLE_N_SEND_BUFFERS,
867 ks->key_id ? false : session->opt->xmit_hold);
868 reliable_init(ks->rec_reliable, BUF_SIZE(&session->opt->frame),
869 session->opt->frame.buf.headroom, TLS_RELIABLE_N_REC_BUFFERS, false);
870 reliable_set_timeout(ks->send_reliable, session->opt->packet_timeout);
871
872 /* init packet ID tracker */
873 packet_id_init(&ks->crypto_options.packet_id, session->opt->replay_window,
874 session->opt->replay_time, "SSL", ks->key_id);
875
876 ks->crypto_options.pid_persist = NULL;
877
878#ifdef ENABLE_MANAGEMENT
879 ks->mda_key_id = session->opt->mda_context->mda_key_id_counter++;
880#endif
881
882 /*
883 * Attempt CRL reload before TLS negotiation. Won't be performed if
884 * the file was not modified since the last reload. This affects
885 * all instances (all instances share the same context).
886 */
887 if (session->opt->crl_file && !(session->opt->ssl_flags & SSLF_CRL_VERIFY_DIR))
888 {
889 tls_ctx_reload_crl(session->opt->ssl_ctx, session->opt->crl_file,
890 session->opt->crl_file_inline);
891 }
892}
893
894
911static void
912key_state_free(struct key_state *ks, bool clear, struct buffer *to_link)
913{
914 check_keystate_buf_not_used(to_link, ks);
915
916 ks->state = S_UNDEF;
917
919
926
929
930 free(ks->rec_ack);
931 free(ks->lru_acks);
932 free(ks->key_src);
933
935
938
939 if (clear)
940 {
941 secure_memzero(ks, sizeof(*ks));
942 }
943}
944
958static inline bool
960{
961 return (session->opt->auth_user_pass_verify_script
965#endif
966 );
967}
968
969
990static void
992{
993 struct gc_arena gc = gc_new();
994
995 dmsg(D_TLS_DEBUG, "TLS: tls_session_init: entry");
996
997 CLEAR(*session);
998
999 /* Set options data to point to parent's option structure */
1000 session->opt = &multi->opt;
1001
1002 /* Randomize session # if it is 0 */
1003 while (!session_id_defined(&session->session_id))
1004 {
1005 session_id_random(&session->session_id);
1006 }
1007
1008 /* Are we a TLS server or client? */
1009 if (session->opt->server)
1010 {
1011 session->initial_opcode = P_CONTROL_HARD_RESET_SERVER_V2;
1012 }
1013 else
1014 {
1015 session->initial_opcode = session->opt->tls_crypt_v2 ? P_CONTROL_HARD_RESET_CLIENT_V3
1017 }
1018
1019 /* Initialize control channel authentication parameters */
1020 session->tls_wrap = session->opt->tls_wrap;
1021 session->tls_wrap.work = alloc_buf(BUF_SIZE(&session->opt->frame));
1022
1023 /* initialize packet ID replay window for --tls-auth */
1024 packet_id_init(&session->tls_wrap.opt.packet_id, session->opt->replay_window,
1025 session->opt->replay_time, "TLS_WRAP", session->key_id);
1026
1027 /* If we are using tls-crypt-v2 we manipulate the packet id to be (ab)used
1028 * to indicate early protocol negotiation */
1029 if (session->opt->tls_crypt_v2)
1030 {
1031 session->tls_wrap.opt.packet_id.send.time = now;
1032 session->tls_wrap.opt.packet_id.send.id = EARLY_NEG_START;
1033 }
1034
1035 /* load most recent packet-id to replay protect on --tls-auth */
1036 packet_id_persist_load_obj(session->tls_wrap.opt.pid_persist, &session->tls_wrap.opt.packet_id);
1037
1039
1040 dmsg(D_TLS_DEBUG, "TLS: tls_session_init: new session object, sid=%s",
1041 session_id_print(&session->session_id, &gc));
1042
1043 gc_free(&gc);
1044}
1045
1063static void
1064tls_session_free(struct tls_session *session, bool clear, struct buffer *to_link)
1065{
1067 tls_wrap_free(&session->tls_wrap);
1068 tls_wrap_free(&session->tls_wrap_reneg);
1069
1070 for (size_t i = 0; i < KS_SIZE; ++i)
1071 {
1072 /* we don't need clear=true for this call since
1073 * the structs are part of session and get cleared
1074 * as part of session */
1075 key_state_free(&session->key[i], false, to_link);
1076 }
1077
1078 free(session->common_name);
1079
1080 cert_hash_free(session->cert_hash_set);
1081
1082 if (clear)
1083 {
1084 secure_memzero(session, sizeof(*session));
1085 }
1086}
1087
1093static void
1094move_session(struct tls_multi *multi, int dest, int src, bool reinit_src,
1095 struct buffer *to_link)
1096{
1097 check_session_buf_not_used(to_link, &multi->session[dest]);
1098 msg(D_TLS_DEBUG_LOW, "TLS: move_session: dest=%s src=%s reinit_src=%d",
1099 session_index_name(dest), session_index_name(src), reinit_src);
1100 ASSERT(src != dest);
1101 ASSERT(src >= 0 && src < TM_SIZE);
1102 ASSERT(dest >= 0 && dest < TM_SIZE);
1103 tls_session_free(&multi->session[dest], false, to_link);
1104 multi->session[dest] = multi->session[src];
1105
1106 if (reinit_src)
1107 {
1108 tls_session_init(multi, &multi->session[src]);
1109 }
1110 else
1111 {
1112 secure_memzero(&multi->session[src], sizeof(multi->session[src]));
1113 }
1114
1115 dmsg(D_TLS_DEBUG, "TLS: move_session: exit");
1116}
1117
1118static void
1119reset_session(struct tls_multi *multi, struct tls_session *session, struct buffer *to_link)
1120{
1121 tls_session_free(session, false, to_link);
1122 tls_session_init(multi, session);
1123}
1124
1125/*
1126 * Used to determine in how many seconds we should be
1127 * called again.
1128 */
1129static inline void
1130compute_earliest_wakeup(interval_t *earliest, time_t seconds_from_now)
1131{
1132 if (seconds_from_now < *earliest)
1133 {
1134 *earliest = (interval_t)seconds_from_now;
1135 }
1136 if (*earliest < 0)
1137 {
1138 *earliest = 0;
1139 }
1140}
1141
1142/*
1143 * Return true if "lame duck" or retiring key has expired and can
1144 * no longer be used.
1145 */
1146static inline bool
1148{
1149 const struct key_state *lame = &session->key[KS_LAME_DUCK];
1150 if (lame->state >= S_INITIAL)
1151 {
1152 ASSERT(lame->must_die); /* a lame duck key must always have an expiration */
1153 if (now < lame->must_die)
1154 {
1155 compute_earliest_wakeup(wakeup, lame->must_die - now);
1156 return false;
1157 }
1158 else
1159 {
1160 return true;
1161 }
1162 }
1163 else if (lame->state == S_ERROR)
1164 {
1165 return true;
1166 }
1167 else
1168 {
1169 return false;
1170 }
1171}
1172
1173struct tls_multi *
1175{
1176 struct tls_multi *ret;
1177
1178 ALLOC_OBJ_CLEAR(ret, struct tls_multi);
1179
1180 /* get command line derived options */
1181 ret->opt = *tls_options;
1182 ret->dco_peer_id = -1;
1183 ret->use_asymmetric_peer_id = false;
1184 /* The rx_peer_id is also used to identify DCO clients */
1185 ret->rx_peer_id = MAX_PEER_ID;
1186 ret->tx_peer_id = MAX_PEER_ID;
1187
1188 return ret;
1189}
1190
1191void
1192tls_multi_init_finalize(struct tls_multi *multi, int tls_mtu)
1193{
1195 /* initialize the active and untrusted sessions */
1196
1197 tls_session_init(multi, &multi->session[TM_ACTIVE]);
1198 tls_session_init(multi, &multi->session[TM_INITIAL]);
1199
1200 if (!multi->opt.dco_enabled)
1201 {
1202 /* Calculate the asymmetric peer-id */
1203 if (multi->rx_peer_id == MAX_PEER_ID && multi->session[TM_INITIAL].opt->mode != MODE_SERVER)
1204 {
1205 multi->rx_peer_id = (uint32_t)(get_random() % (MAX_PEER_ID - 1));
1206 }
1207 }
1208}
1209
1210/*
1211 * Initialize and finalize a standalone tls-auth verification object.
1212 */
1213
1214struct tls_auth_standalone *
1216{
1217 struct tls_auth_standalone *tas;
1218
1220
1222
1223 /*
1224 * Standalone tls-auth is in read-only mode with respect to TLS
1225 * control channel state. After we build a new client instance
1226 * object, we will process this session-initiating packet for real.
1227 */
1229
1230 /* get initial frame parms, still need to finalize */
1231 tas->frame = tls_options->frame;
1232
1234 tls_options->replay_time, "TAS", 0);
1235
1236 return tas;
1237}
1238
1239void
1241{
1242 if (!tas)
1243 {
1244 return;
1245 }
1246
1248}
1249
1250/*
1251 * Set local and remote option compatibility strings.
1252 * Used to verify compatibility of local and remote option
1253 * sets.
1254 */
1255void
1256tls_multi_init_set_options(struct tls_multi *multi, const char *local, const char *remote)
1257{
1258 /* initialize options string */
1259 multi->opt.local_options = local;
1260 multi->opt.remote_options = remote;
1261}
1262
1263/*
1264 * Cleanup a tls_multi structure and free associated memory allocations.
1265 */
1266void
1267tls_multi_free(struct tls_multi *multi, bool clear)
1268{
1269 ASSERT(multi);
1270
1271 auth_set_client_reason(multi, NULL);
1272
1273 free(multi->peer_info);
1274 free(multi->locked_cn);
1275 free(multi->locked_username);
1276 free(multi->locked_original_username);
1277
1279
1280 wipe_auth_token(multi);
1281
1282 free(multi->remote_ciphername);
1283
1284 for (int i = 0; i < TM_SIZE; ++i)
1285 {
1286 tls_session_free(&multi->session[i], false, NULL);
1287 }
1288
1289 if (clear)
1290 {
1291 secure_memzero(multi, sizeof(*multi));
1292 }
1293
1294 free(multi);
1295}
1296
1297/*
1298 * For debugging, print contents of key_source2 structure.
1299 */
1300
1301static void
1302key_source_print(const struct key_source *k, const char *prefix)
1303{
1304 struct gc_arena gc = gc_new();
1305
1306 VALGRIND_MAKE_READABLE((void *)k->pre_master, sizeof(k->pre_master));
1307 VALGRIND_MAKE_READABLE((void *)k->random1, sizeof(k->random1));
1308 VALGRIND_MAKE_READABLE((void *)k->random2, sizeof(k->random2));
1309
1310 dmsg(D_SHOW_KEY_SOURCE, "%s pre_master: %s", prefix,
1311 format_hex(k->pre_master, sizeof(k->pre_master), 0, &gc));
1312 dmsg(D_SHOW_KEY_SOURCE, "%s random1: %s", prefix,
1313 format_hex(k->random1, sizeof(k->random1), 0, &gc));
1314 dmsg(D_SHOW_KEY_SOURCE, "%s random2: %s", prefix,
1315 format_hex(k->random2, sizeof(k->random2), 0, &gc));
1316
1317 gc_free(&gc);
1318}
1319
1320static void
1322{
1323 key_source_print(&k->client, "Client");
1324 key_source_print(&k->server, "Server");
1325}
1326
1327static bool
1328openvpn_PRF(const uint8_t *secret, size_t secret_len, const char *label, const uint8_t *client_seed,
1329 size_t client_seed_len, const uint8_t *server_seed, size_t server_seed_len,
1330 const struct session_id *client_sid, const struct session_id *server_sid,
1331 uint8_t *output, size_t output_len)
1332{
1333 /* concatenate seed components */
1334
1335 struct buffer seed =
1337
1341
1342 if (client_sid)
1343 {
1345 }
1346 if (server_sid)
1347 {
1349 }
1350
1351 /* compute PRF */
1353
1354 buf_clear(&seed);
1355 free_buf(&seed);
1356
1358 return ret;
1359}
1360
1361static void
1362init_epoch_keys(struct key_state *ks, struct tls_multi *multi, const struct key_type *key_type,
1363 bool server, const struct key2 *key2)
1364{
1365 /* For now we hardcode this to be 4 for the software based data channel
1366 * DCO based implementations/HW implementation might adjust this number
1367 * based on their expected speed.
1368 *
1369 * One epoch lasts 910 GiB with 128 byte packets or 78s at 100 GBit/s.
1370 * (respectively 1011 GiB and 86s with 1280 byte packets).
1371 */
1372 const uint8_t future_key_count = 4;
1373
1374 int key_direction = server ? KEY_DIRECTION_INVERSE : KEY_DIRECTION_NORMAL;
1375 struct key_direction_state kds;
1376 key_direction_state_init(&kds, key_direction);
1377
1378 struct crypto_options *co = &ks->crypto_options;
1379
1380 /* For the epoch key we use the first 32 bytes of key2 cipher keys
1381 * for the initial secret */
1382 struct epoch_key e1_send = { 0 };
1383 e1_send.epoch = 1;
1384 memcpy(&e1_send.epoch_key, key2->keys[kds.out_key].cipher, sizeof(e1_send.epoch_key));
1385
1386 struct epoch_key e1_recv = { 0 };
1387 e1_recv.epoch = 1;
1388 memcpy(&e1_recv.epoch_key, key2->keys[kds.in_key].cipher, sizeof(e1_recv.epoch_key));
1389
1390 /* DCO implementations have two choices at this point.
1391 *
1392 * a) (more likely) they probably to pass E1 directly to kernel
1393 * space at this point and do all the other key derivation in kernel
1394 *
1395 * b) They let userspace do the key derivation and pass all the individual
1396 * keys to the DCO layer.
1397 * */
1398 epoch_init_key_ctx(co, key_type, &e1_send, &e1_recv, future_key_count);
1399
1400 secure_memzero(&e1_send, sizeof(e1_send));
1401 secure_memzero(&e1_recv, sizeof(e1_recv));
1402}
1403
1418
1419static enum key_gen_status
1420init_key_contexts(struct key_state *ks, struct tls_multi *multi, const struct key_type *key_type,
1421 bool server, const struct key2 *key2, bool dco)
1422{
1423 struct key_ctx_bi *key = &ks->crypto_options.key_ctx_bi;
1424
1425 /* Initialize key contexts */
1426 int key_direction = server ? KEY_DIRECTION_INVERSE : KEY_DIRECTION_NORMAL;
1427
1428 if (dco)
1429 {
1430 if (key->encrypt.hmac)
1431 {
1432 msg(M_FATAL, "FATAL: DCO does not support --auth");
1433 }
1434
1435 int ret = init_key_dco_bi(multi, ks, key2, key_direction, key_type->cipher, server);
1436 if (ret < 0)
1437 {
1438 /* This normally means the DCO peer is gone from the kernel while
1439 * userspace still believes it exists. Do not take the whole
1440 * process down over a single peer: report the desync so that the
1441 * connection is restarted and the peer re-created from scratch */
1442 msg(M_WARN,
1443 "Impossible to install key material in DCO: %s. The underlying "
1444 "DCO peer may have been deleted from the kernel without "
1445 "notifying userspace. Restarting the session.",
1446 strerror(-ret));
1447 return KEY_GEN_DCO_DESYNC;
1448 }
1449
1450 /* encrypt/decrypt context are unused with DCO */
1451 CLEAR(key->encrypt);
1452 CLEAR(key->decrypt);
1453 key->initialized = true;
1454 }
1455 else if (multi->opt.crypto_flags & CO_EPOCH_DATA_KEY_FORMAT)
1456 {
1458 {
1459 /* The pulled options are validated in do_deferred_options(), so
1460 * reaching this point means a code path escaped that check. Fail
1461 * the session instead of the whole process */
1463 "TLS Error: AEAD cipher (currently %s) "
1464 "required for epoch data format.",
1466 return KEY_GEN_FAILED;
1467 }
1468 init_epoch_keys(ks, multi, key_type, server, key2);
1469 }
1470 else
1471 {
1472 init_key_ctx_bi(key, key2, key_direction, key_type, "Data Channel");
1473 }
1474
1475 return KEY_GEN_OK;
1476}
1477
1478static bool
1480{
1483 sizeof(key2->keys)))
1484 {
1485 return false;
1486 }
1487 key2->n = 2;
1488
1489 return true;
1490}
1491
1492static bool
1494{
1495 uint8_t master[48] = { 0 };
1496
1497 const struct key_state *ks = &session->key[KS_PRIMARY];
1498 const struct key_source2 *key_src = ks->key_src;
1499
1500 const struct session_id *client_sid =
1501 session->opt->server ? &ks->session_id_remote : &session->session_id;
1502 const struct session_id *server_sid =
1503 !session->opt->server ? &ks->session_id_remote : &session->session_id;
1504
1505 /* debugging print of source key material */
1506 key_source2_print(key_src);
1507
1508 /* compute master secret */
1509 if (!openvpn_PRF(key_src->client.pre_master, sizeof(key_src->client.pre_master),
1510 KEY_EXPANSION_ID " master secret", key_src->client.random1,
1511 sizeof(key_src->client.random1), key_src->server.random1,
1512 sizeof(key_src->server.random1), NULL, NULL, master, sizeof(master)))
1513 {
1514 return false;
1515 }
1516
1517 /* compute key expansion */
1518 if (!openvpn_PRF(master, sizeof(master), KEY_EXPANSION_ID " key expansion",
1519 key_src->client.random2, sizeof(key_src->client.random2),
1520 key_src->server.random2, sizeof(key_src->server.random2), client_sid,
1521 server_sid, (uint8_t *)key2->keys, sizeof(key2->keys)))
1522 {
1523 return false;
1524 }
1525 secure_memzero(&master, sizeof(master));
1526
1527 key2->n = 2;
1528
1529 return true;
1530}
1531
1532/*
1533 * Using source entropy from local and remote hosts, mix into
1534 * master key.
1535 */
1536static enum key_gen_status
1538{
1539 const struct key_ctx_bi *key = &ks->crypto_options.key_ctx_bi;
1540 enum key_gen_status ret = KEY_GEN_FAILED;
1541 struct key2 key2;
1542
1543 if (key->initialized)
1544 {
1545 msg(D_TLS_ERRORS, "TLS Error: key already initialized");
1546 goto exit;
1547 }
1548
1549 bool server = session->opt->server;
1550
1551 if (session->opt->crypto_flags & CO_USE_TLS_KEY_MATERIAL_EXPORT)
1552 {
1554 {
1555 msg(D_TLS_ERRORS, "TLS Error: Keying material export failed");
1556 goto exit;
1557 }
1558 }
1559 else
1560 {
1562 {
1563 msg(D_TLS_ERRORS, "TLS Error: PRF calculation failed. Your system "
1564 "might not support the old TLS 1.0 PRF calculation anymore or "
1565 "the policy does not allow it (e.g. running in FIPS mode). "
1566 "The peer did not announce support for the modern TLS Export "
1567 "feature that replaces the TLS 1.0 PRF (requires OpenVPN "
1568 "2.6.x or higher)");
1569 goto exit;
1570 }
1571 }
1572
1573 key2_print(&key2, &session->opt->key_type, "Master Encrypt", "Master Decrypt");
1574
1575 /* check for weak keys */
1576 for (int i = 0; i < 2; ++i)
1577 {
1578 if (!check_key(&key2.keys[i], &session->opt->key_type))
1579 {
1580 msg(D_TLS_ERRORS, "TLS Error: Bad dynamic key generated");
1581 goto exit;
1582 }
1583 }
1584
1585 ret = init_key_contexts(ks, multi, &session->opt->key_type, server, &key2,
1586 session->opt->dco_enabled);
1587
1588exit:
1589 secure_memzero(&key2, sizeof(key2));
1590
1591 return ret;
1592}
1593
1600static enum key_gen_status
1602{
1603 enum key_gen_status ret = KEY_GEN_FAILED;
1604 struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
1605
1606 if (ks->authenticated <= KS_AUTH_FALSE)
1607 {
1608 msg(D_TLS_ERRORS, "TLS Error: key_state not authenticated");
1609 goto cleanup;
1610 }
1611
1612 ks->crypto_options.flags = session->opt->crypto_flags;
1613
1614 ret = generate_key_expansion(multi, ks, session);
1615 if (ret != KEY_GEN_OK)
1616 {
1617 msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
1618 goto cleanup;
1619 }
1620 tls_limit_reneg_bytes(session->opt->key_type.cipher, &session->opt->renegotiate_bytes);
1621
1622 session->opt->aead_usage_limit = tls_get_limit_aead(session->opt->key_type.cipher);
1623
1624 /* set the state of the keys for the session to generated */
1625 ks->state = S_GENERATED_KEYS;
1626
1627cleanup:
1628 secure_memzero(ks->key_src, sizeof(*ks->key_src));
1629 return ret;
1630}
1631
1632bool
1634 struct options *options, struct frame *frame,
1635 struct frame *frame_fragment, struct link_socket_info *lsi,
1636 dco_context_t *dco)
1637{
1638 if (session->key[KS_PRIMARY].crypto_options.key_ctx_bi.initialized)
1639 {
1640 /* keys already generated, nothing to do */
1641 return true;
1642 }
1643
1644 init_key_type(&session->opt->key_type, options->ciphername, options->authname, true, true);
1645
1646 bool packet_id_long_form = cipher_kt_mode_ofb_cfb(session->opt->key_type.cipher);
1647 session->opt->crypto_flags &= ~(CO_PACKET_ID_LONG_FORM);
1648 if (packet_id_long_form)
1649 {
1650 session->opt->crypto_flags |= CO_PACKET_ID_LONG_FORM;
1651 }
1652
1653 frame_calculate_dynamic(frame, &session->opt->key_type, options, lsi);
1654
1655 frame_print(frame, D_MTU_INFO, "Data Channel MTU parms");
1656
1657 /*
1658 * mssfix uses data channel framing, which at this point contains
1659 * actual overhead. Fragmentation logic uses frame_fragment, which
1660 * still contains worst case overhead. Replace it with actual overhead
1661 * to prevent unneeded fragmentation.
1662 */
1663
1664 if (frame_fragment)
1665 {
1666 frame_calculate_dynamic(frame_fragment, &session->opt->key_type, options, lsi);
1667 frame_print(frame_fragment, D_MTU_INFO, "Fragmentation MTU parms");
1668 }
1669
1670 if (session->key[KS_PRIMARY].key_id == 0
1671 && session->opt->crypto_flags & CO_USE_DYNAMIC_TLS_CRYPT)
1672 {
1673 /* If dynamic tls-crypt has been negotiated, and we are on the
1674 * first session (key_id = 0), generate a tls-crypt key for the
1675 * following renegotiations */
1677 {
1678 return false;
1679 }
1680 }
1681
1682 if (dco_enabled(options))
1683 {
1684 /* dco_set_peer() must be called if either keepalive, ping, ping-restart,
1685 * ping-exit or mssfix are set to update in-kernel config */
1687 {
1688 int ret = dco_set_peer(dco, multi->dco_peer_id, options->ping_send_timeout,
1690 if (ret < 0)
1691 {
1692 msg(D_DCO, "Cannot set DCO peer parameters for peer (id=%d): %s",
1693 multi->dco_peer_id, strerror(-ret));
1694 return false;
1695 }
1696 }
1697 }
1698 /* A DCO desync is reported as a plain failure here: every caller of this
1699 * function already turns a failure into a SIGUSR1, which is exactly the
1700 * recovery a desync needs */
1702}
1703
1704bool
1706 struct options *options, struct frame *frame,
1707 struct frame *frame_fragment, struct link_socket_info *lsi,
1708 dco_context_t *dco)
1709{
1711 {
1712 return false;
1713 }
1714
1715 /* Import crypto settings that might be set by pull/push */
1716 session->opt->crypto_flags |= options->imported_protocol_flags;
1717
1718 return tls_session_update_crypto_params_do_work(multi, session, options, frame, frame_fragment,
1719 lsi, dco);
1720}
1721
1722
1723static bool
1724random_bytes_to_buf(struct buffer *buf, uint8_t *out, int outlen)
1725{
1726 if (!rand_bytes(out, outlen))
1727 {
1728 msg(M_FATAL,
1729 "ERROR: Random number generator cannot obtain entropy for key generation [SSL]");
1730 }
1731 if (!buf_write(buf, out, outlen))
1732 {
1733 return false;
1734 }
1735 return true;
1736}
1737
1738static bool
1739key_source2_randomize_write(struct key_source2 *k2, struct buffer *buf, bool server)
1740{
1741 struct key_source *k = &k2->client;
1742 if (server)
1743 {
1744 k = &k2->server;
1745 }
1746
1747 CLEAR(*k);
1748
1749 if (!server)
1750 {
1751 if (!random_bytes_to_buf(buf, k->pre_master, sizeof(k->pre_master)))
1752 {
1753 return false;
1754 }
1755 }
1756
1757 if (!random_bytes_to_buf(buf, k->random1, sizeof(k->random1)))
1758 {
1759 return false;
1760 }
1761 if (!random_bytes_to_buf(buf, k->random2, sizeof(k->random2)))
1762 {
1763 return false;
1764 }
1765
1766 return true;
1767}
1768
1769static int
1770key_source2_read(struct key_source2 *k2, struct buffer *buf, bool server)
1771{
1772 struct key_source *k = &k2->client;
1773
1774 if (!server)
1775 {
1776 k = &k2->server;
1777 }
1778
1779 CLEAR(*k);
1780
1781 if (server)
1782 {
1783 if (!buf_read(buf, k->pre_master, sizeof(k->pre_master)))
1784 {
1785 return 0;
1786 }
1787 }
1788
1789 if (!buf_read(buf, k->random1, sizeof(k->random1)))
1790 {
1791 return 0;
1792 }
1793 if (!buf_read(buf, k->random2, sizeof(k->random2)))
1794 {
1795 return 0;
1796 }
1797
1798 return 1;
1799}
1800
1801static void
1803{
1804 const struct buffer *b;
1805
1806 while ((b = buffer_list_peek(ks->paybuf)))
1807 {
1808 key_state_write_plaintext_const(&ks->ks_ssl, b->data, b->len);
1810 }
1811}
1812
1813/*
1814 * Move the active key to the lame duck key and reinitialize the
1815 * active key.
1816 */
1817static void
1819{
1820 struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
1821 struct key_state *ks_lame = &session->key[KS_LAME_DUCK]; /* retiring key */
1822
1823 ks->must_die = now + session->opt->transition_window; /* remaining lifetime of old key */
1824 key_state_free(ks_lame, false, to_link);
1825 *ks_lame = *ks;
1826
1828 ks->session_id_remote = ks_lame->session_id_remote;
1829 ks->remote_addr = ks_lame->remote_addr;
1830}
1831
1832void
1837
1838/*
1839 * Read/write strings from/to a struct buffer with a u16 length prefix.
1840 */
1841
1842static bool
1844{
1845 if (!buf_write_u16(buf, 0))
1846 {
1847 return false;
1848 }
1849 return true;
1850}
1851
1852static bool
1853write_string(struct buffer *buf, const char *str, const int maxlen)
1854{
1855 const size_t len = strlen(str) + 1;
1856 const size_t real_maxlen = (maxlen >= 0 && maxlen <= UINT16_MAX) ? (size_t)maxlen : UINT16_MAX;
1857 if (len > real_maxlen)
1858 {
1859 return false;
1860 }
1861 if (!buf_write_u16(buf, (uint16_t)len))
1862 {
1863 return false;
1864 }
1865 if (!buf_write(buf, str, len))
1866 {
1867 return false;
1868 }
1869 return true;
1870}
1871
1882static int
1883read_string(struct buffer *buf, char *str, const unsigned int capacity)
1884{
1885 const int len = buf_read_u16(buf);
1886 if (len < 1 || len > (int)capacity)
1887 {
1888 buf_advance(buf, len);
1889
1890 /* will also return 0 for a no string being present */
1891 return -len;
1892 }
1893 if (!buf_read(buf, str, len))
1894 {
1895 return -len;
1896 }
1897 str[len - 1] = '\0';
1898 return len;
1899}
1900
1901static char *
1903{
1904 const int len = buf_read_u16(buf);
1905 char *str;
1906
1907 if (len < 1)
1908 {
1909 return NULL;
1910 }
1911 str = (char *)malloc(len);
1913 if (!buf_read(buf, str, len))
1914 {
1915 free(str);
1916 return NULL;
1917 }
1918 str[len - 1] = '\0';
1919 return str;
1920}
1921
1922static bool
1923push_peer_info_peerid(struct buffer *out, struct tls_multi *multi, struct tls_session *session)
1924{
1925 if (multi->rx_peer_id == MAX_PEER_ID || session->opt->dco_enabled)
1926 {
1927 /* No valid peer id or DCO is enabled. Cannot use this feature */
1928 return true;
1929 }
1930
1931 /* In server mode we only add this when the client has announced its
1932 * support for the feature */
1933 if (session->opt->mode != MODE_SERVER || multi->use_asymmetric_peer_id)
1934 {
1935 return buf_printf(out, "ID=%x\n", multi->rx_peer_id);
1936 }
1937
1938 return true;
1939}
1940
1957static bool
1958push_peer_info(struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
1959{
1960 struct gc_arena gc = gc_new();
1961 bool ret = false;
1962 struct buffer out = alloc_buf_gc(512 * 3, &gc);
1963
1964 /* The asymmetric peer-id is always written when enabled */
1965 if (!push_peer_info_peerid(&out, multi, session))
1966 {
1967 goto error;
1968 }
1969
1970 if (session->opt->push_peer_info_detail > 1)
1971 {
1972 /* push version */
1973 buf_printf(&out, "IV_VER=%s\n", PACKAGE_VERSION);
1974
1975 /* push platform */
1976#if defined(TARGET_LINUX)
1977 buf_printf(&out, "IV_PLAT=linux\n");
1978#elif defined(TARGET_SOLARIS)
1979 buf_printf(&out, "IV_PLAT=solaris\n");
1980#elif defined(TARGET_OPENBSD)
1981 buf_printf(&out, "IV_PLAT=openbsd\n");
1982#elif defined(TARGET_DARWIN)
1983 buf_printf(&out, "IV_PLAT=mac\n");
1984#elif defined(TARGET_NETBSD)
1985 buf_printf(&out, "IV_PLAT=netbsd\n");
1986#elif defined(TARGET_FREEBSD)
1987 buf_printf(&out, "IV_PLAT=freebsd\n");
1988#elif defined(TARGET_ANDROID)
1989 buf_printf(&out, "IV_PLAT=android\n");
1990#elif defined(_WIN32)
1991 buf_printf(&out, "IV_PLAT=win\n");
1992#endif
1993 /* Announce that we do not require strict sequence numbers with
1994 * TCP. (TCP non-linear) */
1995 buf_printf(&out, "IV_TCPNL=1\n");
1996 }
1997
1998 /* These are the IV variable that are sent to peers in p2p mode */
1999 if (session->opt->push_peer_info_detail > 0)
2000 {
2001 /* support for P_DATA_V2 */
2003
2004 /* support for the latest --dns option */
2006
2007 /* support for exit notify via control channel */
2009
2010 /* currently push-update is not supported when DCO is enabled */
2011 if (!session->opt->dco_enabled)
2012 {
2013 /* support push-updates */
2015 }
2016
2017 if (session->opt->pull)
2018 {
2019 /* support for receiving push_reply before sending
2020 * push request, also signal that the client wants
2021 * to get push-reply messages without requiring a round
2022 * trip for a push request message*/
2024
2025 /* Support keywords in the AUTH_PENDING control message */
2027
2028 /* support for AUTH_FAIL,TEMP control message */
2030
2031 /* support for tun-mtu as part of the push message */
2032 buf_printf(&out, "IV_MTU=%d\n", session->opt->frame.tun_max_mtu);
2033 }
2034
2035 /* support for Negotiable Crypto Parameters */
2036 if (session->opt->mode == MODE_SERVER || session->opt->pull)
2037 {
2038 if (tls_item_in_cipher_list("AES-128-GCM", session->opt->config_ncp_ciphers)
2039 && tls_item_in_cipher_list("AES-256-GCM", session->opt->config_ncp_ciphers))
2040 {
2041 buf_printf(&out, "IV_NCP=2\n");
2042 }
2043 }
2044 else
2045 {
2046 /* We are not using pull or p2mp server, instead do P2P NCP */
2048 }
2049
2050 if (session->opt->data_epoch_supported)
2051 {
2053 }
2054
2055 buf_printf(&out, "IV_CIPHERS=%s\n", session->opt->config_ncp_ciphers);
2056
2059
2060 buf_printf(&out, "IV_PROTO=%d\n", iv_proto);
2061
2062 if (session->opt->push_peer_info_detail > 1)
2063 {
2064 /* push compression status */
2065#ifdef USE_COMP
2066 comp_generate_peer_info_string(&session->opt->comp_options, &out);
2067#endif
2068 }
2069
2070 if (session->opt->push_peer_info_detail > 2)
2071 {
2072 /* push mac addr */
2073 struct route_gateway_info rgi;
2074 get_default_gateway(&rgi, 0, session->opt->net_ctx);
2075 if (rgi.flags & RGI_HWADDR_DEFINED)
2076 {
2077 buf_printf(&out, "IV_HWADDR=%s\n", format_hex_ex(rgi.hwaddr, 6, 0, 1, ":", &gc));
2078 }
2079 buf_printf(&out, "IV_SSL=%s\n", get_ssl_library_version());
2080#if defined(_WIN32)
2081 buf_printf(&out, "IV_PLAT_VER=%s\n", win32_version_string(&gc));
2082#else
2083 struct utsname u;
2084 uname(&u);
2085 buf_printf(&out, "IV_PLAT_VER=%s\n", u.release);
2086#endif
2087 }
2088
2089 if (session->opt->push_peer_info_detail > 1)
2090 {
2091 struct env_set *es = session->opt->es;
2092 /* push env vars that begin with UV_, IV_PLAT_VER and IV_GUI_VER */
2093 for (struct env_item *e = es->list; e != NULL; e = e->next)
2094 {
2095 if (e->string)
2096 {
2097 if ((((strncmp(e->string, "UV_", 3) == 0
2098 || strncmp(e->string, "IV_PLAT_VER=", sizeof("IV_PLAT_VER=") - 1) == 0)
2099 && session->opt->push_peer_info_detail > 2)
2100 || (strncmp(e->string, "IV_GUI_VER=", sizeof("IV_GUI_VER=") - 1) == 0)
2101 || (strncmp(e->string, "IV_SSO=", sizeof("IV_SSO=") - 1) == 0))
2102 && buf_safe(&out, strlen(e->string) + 1))
2103 {
2104 buf_printf(&out, "%s\n", e->string);
2105 }
2106 }
2107 }
2108 }
2109 }
2110
2111 /* write peer info string if there is anything in it, empty string otherwise */
2112 if (BLEN(&out) > 0)
2113 {
2114 if (!write_string(buf, BSTR(&out), -1))
2115 {
2116 goto error;
2117 }
2118 }
2119 else
2120 {
2121 if (!write_empty_string(buf))
2122 {
2123 goto error;
2124 }
2125 }
2126 ret = true;
2127
2128error:
2129 gc_free(&gc);
2130 return ret;
2131}
2132
2133#ifdef USE_COMP
2134static bool
2135write_compat_local_options(struct buffer *buf, const char *options)
2136{
2137 struct gc_arena gc = gc_new();
2138 const char *local_options = options_string_compat_lzo(options, &gc);
2139 bool ret = write_string(buf, local_options, TLS_OPTIONS_LEN);
2140 gc_free(&gc);
2141 return ret;
2142}
2143#endif
2144
2149static bool
2150key_method_2_write(struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
2151{
2152 struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
2153
2154 ASSERT(buf_init(buf, 0));
2155
2156 /* write a uint32 0 */
2157 if (!buf_write_u32(buf, 0))
2158 {
2159 goto error;
2160 }
2161
2162 /* write key_method + flags */
2163 if (!buf_write_u8(buf, KEY_METHOD_2))
2164 {
2165 goto error;
2166 }
2167
2168 /* write key source material */
2169 if (!key_source2_randomize_write(ks->key_src, buf, session->opt->server))
2170 {
2171 goto error;
2172 }
2173
2174 /* write options string */
2175 {
2176#ifdef USE_COMP
2177 if (multi->remote_usescomp && session->opt->mode == MODE_SERVER
2178 && multi->opt.comp_options.flags & COMP_F_MIGRATE)
2179 {
2180 if (!write_compat_local_options(buf, session->opt->local_options))
2181 {
2182 goto error;
2183 }
2184 }
2185 else
2186#endif
2187 if (!write_string(buf, session->opt->local_options, TLS_OPTIONS_LEN))
2188 {
2189 goto error;
2190 }
2191 }
2192
2193 /* write username/password if specified or we are using a auth-token */
2195 {
2196#ifdef ENABLE_MANAGEMENT
2197 auth_user_pass_setup(session->opt->auth_user_pass_file,
2198 session->opt->auth_user_pass_file_inline,
2199 session->opt->auth_user_pass_username_only, session->opt->sci);
2200#else
2201 auth_user_pass_setup(session->opt->auth_user_pass_file,
2202 session->opt->auth_user_pass_file_inline,
2203 session->opt->auth_user_pass_username_only, NULL);
2204#endif
2205 struct user_pass *up = &auth_user_pass;
2206
2207 /*
2208 * If we have a valid auth-token, send that instead of real
2209 * username/password
2210 */
2212 {
2213 up = &auth_token;
2214 }
2216
2217 if (!write_string(buf, up->username, -1))
2218 {
2219 msg(M_WARN, "WARNING: Failed to write auth username to TLS buffer");
2220 goto error;
2221 }
2222 else if (!write_string(buf, up->password, -1))
2223 {
2224 msg(M_WARN, "WARNING: Failed to write auth password to TLS buffer");
2225 goto error;
2226 }
2227 /* save username for auth-token which may get pushed later */
2228 if (session->opt->pull && up != &auth_token)
2229 {
2233 }
2235 /* respect auth-nocache */
2237 }
2238 else
2239 {
2240 if (!write_empty_string(buf)) /* no username */
2241 {
2242 goto error;
2243 }
2244 if (!write_empty_string(buf)) /* no password */
2245 {
2246 goto error;
2247 }
2248 }
2249
2250 if (!push_peer_info(buf, multi, session))
2251 {
2252 goto error;
2253 }
2254
2255 if (session->opt->server && session->opt->mode != MODE_SERVER && ks->key_id == 0)
2256 {
2257 /* tls-server option set and not P2MP server, so we
2258 * are a P2P client running in tls-server mode */
2259 p2p_mode_ncp(multi, session);
2260 }
2261
2262 return true;
2263
2264error:
2265 msg(D_TLS_ERRORS, "TLS Error: Key Method #2 write failed");
2266 secure_memzero(ks->key_src, sizeof(*ks->key_src));
2267 return false;
2268}
2269
2270static void
2272{
2273 if (session->opt->ekm_size > 0)
2274 {
2275 const size_t size = session->opt->ekm_size;
2276 struct gc_arena gc = gc_new();
2277
2278 unsigned char *ekm = gc_malloc(size, true, &gc);
2280 session->opt->ekm_label_size, ekm,
2281 session->opt->ekm_size))
2282 {
2283 const size_t len = (size * 2) + 2;
2284
2285 const char *key = format_hex_ex(ekm, size, len, 0, NULL, &gc);
2286 setenv_str(session->opt->es, "exported_keying_material", key);
2287
2288 dmsg(D_TLS_DEBUG_MED, "%s: exported keying material: %s", __func__, key);
2289 secure_memzero(ekm, size);
2290 }
2291 else
2292 {
2293 msg(M_WARN, "WARNING: Export keying material failed!");
2294 setenv_del(session->opt->es, "exported_keying_material");
2295 }
2296 gc_free(&gc);
2297 }
2298}
2299
2304static bool
2305key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_session *session)
2306{
2307 struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
2308
2309 struct gc_arena gc = gc_new();
2310 char *options;
2311 struct user_pass *up = NULL;
2312
2313 /* allocate temporary objects */
2315
2316 /* discard leading uint32 */
2317 if (!buf_advance(buf, 4))
2318 {
2319 msg(D_TLS_ERRORS, "TLS ERROR: Plaintext buffer too short (%d bytes).", buf->len);
2320 goto error;
2321 }
2322
2323 /* get key method */
2324 int key_method_flags = buf_read_u8(buf);
2325 if ((key_method_flags & KEY_METHOD_MASK) != 2)
2326 {
2327 msg(D_TLS_ERRORS, "TLS ERROR: Unknown key_method/flags=%d received from remote host",
2328 key_method_flags);
2329 goto error;
2330 }
2331
2332 /* get key source material (not actual keys yet) */
2333 if (!key_source2_read(ks->key_src, buf, session->opt->server))
2334 {
2336 "TLS Error: Error reading remote data channel key source entropy from plaintext buffer");
2337 goto error;
2338 }
2339
2340 /* get options */
2341 if (read_string(buf, options, TLS_OPTIONS_LEN) < 0)
2342 {
2343 msg(D_TLS_ERRORS, "TLS Error: Failed to read required OCC options string");
2344 goto error;
2345 }
2346
2348
2349 /* always extract username + password fields from buf, even if not
2350 * authenticating for it, because otherwise we can't get at the
2351 * peer_info data which follows behind
2352 */
2353 ALLOC_OBJ_CLEAR_GC(up, struct user_pass, &gc);
2354 int username_len = read_string(buf, up->username, USER_PASS_LEN);
2355 int password_len = read_string(buf, up->password, USER_PASS_LEN);
2356
2357 /* get peer info from control channel */
2358 free(multi->peer_info);
2359 multi->peer_info = read_string_alloc(buf);
2360 if (multi->peer_info)
2361 {
2362 output_peer_info_env(session->opt->es, multi->peer_info);
2363 uint32_t peer_id = extract_asymmetric_peer_id(multi->peer_info);
2364 if (peer_id != MAX_PEER_ID && !session->opt->dco_enabled)
2365 {
2366 multi->tx_peer_id = peer_id;
2367 multi->use_asymmetric_peer_id = true;
2368 multi->use_peer_id = true;
2369 }
2370 else
2371 {
2372 /* Peer has no support for asymmetric peer-id, and DCO currently
2373 * can only handle symmetric peer IDs */
2374 multi->tx_peer_id = multi->rx_peer_id;
2375 }
2376 }
2377
2378 free(multi->remote_ciphername);
2380 multi->remote_usescomp = strstr(options, ",comp-lzo,");
2381
2382 /* In OCC we send '[null-cipher]' instead 'none' */
2383 if (multi->remote_ciphername && strcmp(multi->remote_ciphername, "[null-cipher]") == 0)
2384 {
2385 free(multi->remote_ciphername);
2386 multi->remote_ciphername = string_alloc("none", NULL);
2387 }
2388
2389 if (username_len < 0 || password_len < 0)
2390 {
2391 msg(D_TLS_ERRORS, "TLS Error: Username (%d) or password (%d) too long", abs(username_len),
2392 abs(password_len));
2393 auth_set_client_reason(multi, "Username or password is too long. "
2394 "Maximum length is 128 bytes");
2395
2396 /* treat the same as failed username/password and do not error
2397 * out (goto error) to sent an AUTH_FAILED back to the client */
2399 }
2401 {
2402 /* Perform username/password authentication */
2403 if (!username_len || !password_len)
2404 {
2405 CLEAR(*up);
2406 if (!(session->opt->ssl_flags & SSLF_AUTH_USER_PASS_OPTIONAL))
2407 {
2408 msg(D_TLS_ERRORS, "TLS Error: Auth Username/Password was not provided by peer");
2409 goto error;
2410 }
2411 }
2412
2413 verify_user_pass(up, multi, session);
2414 }
2415 else
2416 {
2417 /* Session verification should have occurred during TLS negotiation*/
2418 if (!session->verified)
2419 {
2420 msg(D_TLS_ERRORS, "TLS Error: Certificate verification failed (key-method 2)");
2421 goto error;
2422 }
2424 }
2425
2426 /* clear username and password from memory */
2427 secure_memzero(up, sizeof(*up));
2428
2429 /* Perform final authentication checks */
2430 if (ks->authenticated > KS_AUTH_FALSE)
2431 {
2433 }
2434
2435 /* check options consistency */
2436 if (!options_cmp_equal(options, session->opt->remote_options))
2437 {
2438 const char *remote_options = session->opt->remote_options;
2439#ifdef USE_COMP
2440 if (multi->opt.comp_options.flags & COMP_F_MIGRATE && multi->remote_usescomp)
2441 {
2442 msg(D_PUSH, "Note: 'compress migrate' detected remote peer "
2443 "with compression enabled.");
2444 remote_options = options_string_compat_lzo(remote_options, &gc);
2445 }
2446#endif
2447
2448 options_warning(options, remote_options);
2449 }
2450
2451 buf_clear(buf);
2452
2453 /*
2454 * Call OPENVPN_PLUGIN_TLS_FINAL plugin if defined, for final
2455 * veto opportunity over authentication decision.
2456 */
2457 if ((ks->authenticated > KS_AUTH_FALSE)
2459 {
2461
2462 if (plugin_call(session->opt->plugins, OPENVPN_PLUGIN_TLS_FINAL, NULL, NULL,
2463 session->opt->es)
2465 {
2467 }
2468
2469 setenv_del(session->opt->es, "exported_keying_material");
2470 }
2471
2472 if (!session->opt->server && !session->opt->pull && ks->key_id == 0)
2473 {
2474 /* We are a p2p tls-client without pull, enable common
2475 * protocol options */
2476 p2p_mode_ncp(multi, session);
2477 }
2478
2479 gc_free(&gc);
2480 return true;
2481
2482error:
2484 secure_memzero(ks->key_src, sizeof(*ks->key_src));
2485 if (up)
2486 {
2487 secure_memzero(up, sizeof(*up));
2488 }
2489 buf_clear(buf);
2490 gc_free(&gc);
2491 return false;
2492}
2493
2494static int
2496{
2497 int ret = o->handshake_window;
2498 const int r2 = o->renegotiate_seconds / 2;
2499
2500 if (o->renegotiate_seconds && r2 < ret)
2501 {
2502 ret = r2;
2503 }
2504 return ret;
2505}
2506
2513static bool
2515 bool skip_initial_send)
2516{
2518 if (!buf)
2519 {
2520 return false;
2521 }
2522
2523 ks->initial = now;
2524 ks->must_negotiate = now + session->opt->handshake_window;
2526
2527 /* null buffer */
2529
2530 /* If we want to skip sending the initial handshake packet we still generate
2531 * it to increase internal counters etc. but immediately mark it as done */
2533 {
2535 }
2537
2539
2540 struct gc_arena gc = gc_new();
2541 dmsg(D_TLS_DEBUG, "TLS: Initial Handshake, sid=%s",
2542 session_id_print(&session->session_id, &gc));
2543 gc_free(&gc);
2544
2545#ifdef ENABLE_MANAGEMENT
2547 {
2548 management_set_state(management, OPENVPN_STATE_WAIT, NULL, NULL, NULL, NULL, NULL);
2549 }
2550#endif
2551 return true;
2552}
2553
2558static void
2560 struct link_socket_info *to_link_socket_info, struct key_state *ks)
2561{
2562 dmsg(D_TLS_DEBUG_MED, "STATE S_ACTIVE");
2563
2564 ks->established = now;
2566 {
2567 print_details(&ks->ks_ssl, "Control Channel:");
2568 }
2569 ks->state = S_ACTIVE;
2570 /* Cancel negotiation timeout */
2571 ks->must_negotiate = 0;
2573
2574 /* Set outgoing address for data channel packets */
2575 link_socket_set_outgoing_addr(to_link_socket_info, &ks->remote_addr, session->common_name,
2576 session->opt->es);
2577
2578 /* Check if we need to advance the tls_multi state machine */
2579 if (multi->multi_state == CAS_NOT_CONNECTED)
2580 {
2581 if (session->opt->mode == MODE_SERVER)
2582 {
2583 /* On a server we continue with running connect scripts next */
2585 }
2586 else
2587 {
2588 /* Skip the connect script related states */
2590 }
2591 }
2592
2593 /* Flush any payload packets that were buffered before our state transitioned to S_ACTIVE */
2595
2596#ifdef MEASURE_TLS_HANDSHAKE_STATS
2597 show_tls_performance_stats();
2598#endif
2599}
2600
2601bool
2603 struct link_socket_actual *from)
2604{
2605 struct key_state *ks = &session->key[KS_PRIMARY];
2606 ks->session_id_remote = state->peer_session_id;
2607 ks->remote_addr = *from;
2608 session->session_id = state->server_session_id;
2609 session->untrusted_addr = *from;
2610 session->burst = true;
2611
2612 /* The OpenVPN protocol implicitly mandates that packet id always start
2613 * from 0 in the RESET packets as OpenVPN 2.x will not allow gaps in the
2614 * ids and starts always from 0. Since we skip/ignore one (RESET) packet
2615 * in each direction, we need to set the ids to 1 */
2616 ks->rec_reliable->packet_id = 1;
2617 /* for ks->send_reliable->packet_id, session_move_pre_start moves the
2618 * counter to 1 */
2619 session->tls_wrap.opt.packet_id.send.id = 1;
2620 return session_move_pre_start(session, ks, true);
2621}
2622
2626static bool
2628 struct key_state *ks)
2629{
2630 while (buf->len > 0)
2631 {
2632 if (buf_len(buf) < 4)
2633 {
2634 goto error;
2635 }
2636 /* read type */
2637 int type = buf_read_u16(buf);
2638 int len = buf_read_u16(buf);
2639 if (type < 0 || len < 0 || buf_len(buf) < len)
2640 {
2641 goto error;
2642 }
2643
2644 switch (type)
2645 {
2647 if (len != sizeof(uint16_t))
2648 {
2649 goto error;
2650 }
2651 int flags = buf_read_u16(buf);
2652
2653 if (flags & EARLY_NEG_FLAG_RESEND_WKC)
2654 {
2655 /* Only accept the EARLY_NEG_FLAG_RESEND_WKC flag
2656 * from the server if we are configured with tls-crypt-v2 */
2657 if (session->tls_wrap.tls_crypt_v2_wkc)
2658 {
2660 }
2661 else
2662 {
2663 msg(D_TLS_ERRORS, "TLS Error: peer asked us to resend the wrapped "
2664 "client key, but this is not a tls-crypt-v2 client");
2665 }
2666 }
2667 break;
2668
2669 default:
2670 /* Skip types we do not parse */
2671 buf_advance(buf, len);
2672 }
2673 }
2675
2676 return true;
2677error:
2678 msg(D_TLS_ERRORS, "TLS Error: Early negotiation malformed packet");
2679 return false;
2680}
2681
2686static bool
2687read_incoming_tls_ciphertext(struct buffer *buf, struct key_state *ks, bool *continue_tls_process)
2688{
2689 int status = 0;
2690 if (buf->len)
2691 {
2693 if (status == -1)
2694 {
2695 msg(D_TLS_ERRORS, "TLS Error: Incoming Ciphertext -> TLS object write error");
2696 return false;
2697 }
2698 }
2699 else
2700 {
2701 status = 1;
2702 }
2703 if (status == 1)
2704 {
2706 *continue_tls_process = true;
2707 dmsg(D_TLS_DEBUG, "Incoming Ciphertext -> TLS");
2708 }
2709 return true;
2710}
2711
2712static bool
2714{
2715 return (ks->crypto_options.flags & CO_RESEND_WKC) && (ks->send_reliable->packet_id == 1);
2716}
2717
2718
2719static bool
2721 bool *continue_tls_process)
2722{
2723 ASSERT(buf_init(buf, 0));
2724
2725 int status = key_state_read_plaintext(&ks->ks_ssl, buf);
2726
2727 update_time();
2728 if (status == -1)
2729 {
2730 msg(D_TLS_ERRORS, "TLS Error: TLS object -> incoming plaintext read error");
2731 return false;
2732 }
2733 if (status == 1)
2734 {
2735 *continue_tls_process = true;
2736 dmsg(D_TLS_DEBUG, "TLS -> Incoming Plaintext");
2737
2738 /* More data may be available, wake up again asap to check. */
2739 *wakeup = 0;
2740 }
2741 return true;
2742}
2743
2744static bool
2745write_outgoing_tls_ciphertext(struct tls_session *session, bool *continue_tls_process)
2746{
2747 struct key_state *ks = &session->key[KS_PRIMARY];
2748
2750 if (rel_avail == 0)
2751 {
2752 return true;
2753 }
2754
2755 /* We need to determine how much space is actually available in the control
2756 * channel frame */
2757 int max_pkt_len = min_int(TLS_CHANNEL_BUF_SIZE, session->opt->frame.tun_mtu);
2758
2759 /* Subtract overhead */
2760 max_pkt_len -= (int)calc_control_channel_frame_overhead(session);
2761
2762 /* calculate total available length for outgoing tls ciphertext */
2763 int maxlen = max_pkt_len * rel_avail;
2764
2765 /* Is first packet one that will have a WKC appended? */
2767 {
2768 maxlen -= buf_len(session->tls_wrap.tls_crypt_v2_wkc);
2769 }
2770
2771 /* If we end up with a size that leaves no room for payload, ignore the
2772 * constraints to still be to send a packet. This might have gone negative
2773 * if we have a large wrapped client key. */
2774 if (maxlen < 16)
2775 {
2777 "Warning: --max-packet-size (%d) setting too low. "
2778 "Sending minimum sized packet.",
2779 session->opt->frame.tun_mtu);
2780 maxlen = 16;
2781 /* We set the maximum length here to ensure a packet with a wrapped
2782 * key can actually carry the 16 byte of payload */
2783 max_pkt_len = TLS_CHANNEL_BUF_SIZE;
2784 }
2785
2786 /* This seems a bit wasteful to allocate every time */
2787 struct gc_arena gc = gc_new();
2788 struct buffer tmp = alloc_buf_gc(maxlen, &gc);
2789
2791
2792 if (status == -1)
2793 {
2794 msg(D_TLS_ERRORS, "TLS Error: Ciphertext -> reliable TCP/UDP transport read error");
2795 gc_free(&gc);
2796 return false;
2797 }
2798 if (status == 1)
2799 {
2800 /* Split the TLS ciphertext (TLS record) into multiple small packets
2801 * that respect tls_mtu */
2802 while (tmp.len > 0)
2803 {
2804 int len = max_pkt_len;
2805 int opcode = P_CONTROL_V1;
2807 {
2808 opcode = P_CONTROL_WKC_V1;
2809 len = max_int(0, len - buf_len(session->tls_wrap.tls_crypt_v2_wkc));
2810 }
2811 /* do not send more than available */
2812 len = min_int(len, tmp.len);
2813
2815 /* we assert here since we checked for its availability before */
2816 ASSERT(buf);
2817 buf_copy_n(buf, &tmp, len);
2818
2821 *continue_tls_process = true;
2822 }
2823 dmsg(D_TLS_DEBUG, "Outgoing Ciphertext -> Reliable");
2824 }
2825
2826 gc_free(&gc);
2827 return true;
2828}
2829
2830static bool
2832 struct buffer *to_link, bool *continue_tls_process)
2833{
2834 if (to_link->len)
2835 {
2837 "Deferring outgoing ciphertext, previous packet not written out yet");
2838 return true;
2839 }
2840
2841 /* Outgoing Ciphertext to reliable buffer */
2842 if (ks->state >= S_START)
2843 {
2845 if (buf)
2846 {
2848 {
2849 return false;
2850 }
2851 }
2852 }
2853 return true;
2854}
2855
2856static bool
2857tls_process_state(struct tls_multi *multi, struct tls_session *session, struct buffer *to_link,
2858 struct link_socket_actual **to_link_addr,
2860{
2861 /* This variable indicates if we should call this method
2862 * again to process more incoming/outgoing TLS state/data
2863 * We want to repeat this until we either determined that there
2864 * is nothing more to process or that further processing
2865 * should only be done after the outer loop (sending packets etc.)
2866 * has run once more */
2867 bool continue_tls_process = false;
2868 struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
2869
2870 /* Initial handshake */
2871 if (ks->state == S_INITIAL)
2872 {
2873 continue_tls_process = session_move_pre_start(session, ks, false);
2874 }
2875
2876 /* Are we timed out on receive? */
2877 if (now >= ks->must_negotiate && ks->state >= S_UNDEF && ks->state < S_ACTIVE)
2878 {
2880 "TLS Error: TLS key negotiation failed to occur within %d seconds (check your network connectivity)",
2881 session->opt->handshake_window);
2882 goto error;
2883 }
2884
2885 /* Check if the initial three-way Handshake is complete.
2886 * We consider the handshake to be complete when our own initial
2887 * packet has been successfully ACKed. */
2888 if (ks->state == S_PRE_START && reliable_empty(ks->send_reliable))
2889 {
2890 ks->state = S_START;
2891 continue_tls_process = true;
2892
2893 /* New connection, remove any old X509 env variables */
2894 tls_x509_clear_env(session->opt->es);
2895 dmsg(D_TLS_DEBUG_MED, "STATE S_START");
2896 }
2897
2898 /* Wait for ACK */
2899 if (((ks->state == S_GOT_KEY && !session->opt->server)
2900 || (ks->state == S_SENT_KEY && session->opt->server))
2902 {
2903 session_move_active(multi, session, to_link_socket_info, ks);
2904 continue_tls_process = true;
2905 }
2906
2907 /* Reliable buffer to outgoing TCP/UDP (send up to CONTROL_SEND_ACK_MAX ACKs
2908 * for previously received packets) */
2909 if (!to_link->len && reliable_can_send(ks->send_reliable))
2910 {
2911 int opcode;
2912
2913 const struct buffer *buf = reliable_send(ks->send_reliable, &opcode);
2914 ASSERT(buf);
2915 struct buffer b = *buf;
2916 INCR_SENT;
2917
2918 write_control_auth(session, ks, &b, to_link_addr, opcode, CONTROL_SEND_ACK_MAX, true);
2919 *to_link = b;
2920 dmsg(D_TLS_DEBUG, "Reliable -> TCP/UDP");
2921
2922 /* This changed the state of the outgoing buffer. In order to avoid
2923 * running this function again/further and invalidating the key_state
2924 * buffer and accessing the buffer that is now in to_link after it being
2925 * freed for a potential error, we shortcircuit exiting of the outer
2926 * process here. */
2927 return false;
2928 }
2929
2930 if (ks->state == S_ERROR_PRE)
2931 {
2932 /* When we end up here, we had one last chance to send an outstanding
2933 * packet that contained an alert. We do not ensure that this packet
2934 * has been successfully delivered (ie wait for the ACK etc)
2935 * but rather stop processing now */
2936 ks->state = S_ERROR;
2937 return false;
2938 }
2939
2940 /* Write incoming ciphertext to TLS object */
2942 if (entry)
2943 {
2944 /* The first packet from the peer (the reset packet) is special and
2945 * contains early protocol negotiation */
2946 if (entry->packet_id == 0 && is_hard_reset_method2(entry->opcode))
2947 {
2948 if (!parse_early_negotiation_tlvs(&entry->buf, session, ks))
2949 {
2950 goto error;
2951 }
2952 }
2953 else
2954 {
2955 if (!read_incoming_tls_ciphertext(&entry->buf, ks, &continue_tls_process))
2956 {
2957 goto error;
2958 }
2959 }
2960 }
2961
2962 /* Read incoming plaintext from TLS object */
2963 struct buffer *buf = &ks->plaintext_read_buf;
2964 if (!buf->len)
2965 {
2966 if (!read_incoming_tls_plaintext(ks, buf, wakeup, &continue_tls_process))
2967 {
2968 goto error;
2969 }
2970 }
2971
2972 /* Send Key */
2973 buf = &ks->plaintext_write_buf;
2974 if (!buf->len
2975 && ((ks->state == S_START && !session->opt->server)
2976 || (ks->state == S_GOT_KEY && session->opt->server)))
2977 {
2978 if (!key_method_2_write(buf, multi, session))
2979 {
2980 goto error;
2981 }
2982
2983 continue_tls_process = true;
2984 dmsg(D_TLS_DEBUG_MED, "STATE S_SENT_KEY");
2985 ks->state = S_SENT_KEY;
2986 }
2987
2988 /* Receive Key */
2989 buf = &ks->plaintext_read_buf;
2990 if (buf->len
2991 && ((ks->state == S_SENT_KEY && !session->opt->server)
2992 || (ks->state == S_START && session->opt->server)))
2993 {
2994 if (!key_method_2_read(buf, multi, session))
2995 {
2996 goto error;
2997 }
2998
2999 continue_tls_process = true;
3000 dmsg(D_TLS_DEBUG_MED, "STATE S_GOT_KEY");
3001 ks->state = S_GOT_KEY;
3002 }
3003
3004 /* Write outgoing plaintext to TLS object */
3005 buf = &ks->plaintext_write_buf;
3006 if (buf->len)
3007 {
3008 int status = key_state_write_plaintext(&ks->ks_ssl, buf);
3009 if (status == -1)
3010 {
3011 msg(D_TLS_ERRORS, "TLS ERROR: Outgoing Plaintext -> TLS object write error");
3012 goto error;
3013 }
3014 if (status == 1)
3015 {
3016 continue_tls_process = true;
3017 dmsg(D_TLS_DEBUG, "Outgoing Plaintext -> TLS");
3018 }
3019 }
3021 {
3022 goto error;
3023 }
3024
3025 return continue_tls_process;
3026error:
3028
3029 /* Shut down the TLS session but do a last read from the TLS
3030 * object to be able to read potential TLS alerts */
3033
3034 /* Put ourselves in the pre error state that will only send out the
3035 * control channel packets but nothing else */
3036 ks->state = S_ERROR_PRE;
3037
3038 msg(D_TLS_ERRORS, "TLS Error: TLS handshake failed");
3039 INCR_ERROR;
3040 return true;
3041}
3042
3043#if defined(__GNUC__) || defined(__clang__)
3044#pragma GCC diagnostic push
3045#pragma GCC diagnostic ignored "-Wsign-compare"
3046#endif
3047
3052static bool
3054{
3055 /* Time limit */
3056 if (session->opt->renegotiate_seconds
3057 && now >= ks->established + session->opt->renegotiate_seconds)
3058 {
3059 return true;
3060 }
3061
3062 /* Byte limit */
3063 if (session->opt->renegotiate_bytes > 0 && ks->n_bytes >= session->opt->renegotiate_bytes)
3064 {
3065 return true;
3066 }
3067
3068 /* Packet limit */
3069 if (session->opt->renegotiate_packets && ks->n_packets >= session->opt->renegotiate_packets)
3070 {
3071 return true;
3072 }
3073
3074 /* epoch key id approaching the 16 bit limit */
3076 {
3077 /* We only need to check the send key as we always keep send
3078 * key epoch >= recv key epoch in \c epoch_replace_update_recv_key */
3079 if (ks->crypto_options.epoch_key_send.epoch >= 0xF000)
3080 {
3081 return true;
3082 }
3083 else
3084 {
3085 return false;
3086 }
3087 }
3088
3089
3090 /* Packet id approach the limit of the packet id */
3092 {
3093 return true;
3094 }
3095
3096 /* Check the AEAD usage limit of cleartext blocks + packets.
3097 *
3098 * Contrary to when epoch data mode is active, where only the sender side
3099 * checks the limit, here we check both receive and send limit since
3100 * we assume that only one side is aware of the limit.
3101 *
3102 * Since if both sides were aware, then both sides will probably also
3103 * switch to use epoch data channel instead, so this code is not
3104 * in effect then.
3105 *
3106 * When epoch are in use the crypto layer will handle this internally
3107 * with new epochs instead of triggering a renegotiation */
3108 const struct key_ctx_bi *key_ctx_bi = &ks->crypto_options.key_ctx_bi;
3109 const uint64_t usage_limit = session->opt->aead_usage_limit;
3110
3111 if (aead_usage_limit_reached(usage_limit, &key_ctx_bi->encrypt,
3115 {
3116 return true;
3117 }
3118
3120 {
3121 return true;
3122 }
3123
3124 return false;
3125}
3126
3127#if defined(__GNUC__) || defined(__clang__)
3128#pragma GCC diagnostic pop
3129#endif
3130
3131/*
3132 * This is the primary routine for processing TLS stuff inside the
3133 * the main event loop. When this routine exits
3134 * with non-error status, it will set *wakeup to the number of seconds
3135 * when it wants to be called again.
3136 *
3137 * Return value is true if we have placed a packet in *to_link which we
3138 * want to send to our peer.
3139 */
3140static bool
3141tls_process(struct tls_multi *multi, struct tls_session *session, struct buffer *to_link,
3142 struct link_socket_actual **to_link_addr, struct link_socket_info *to_link_socket_info,
3143 interval_t *wakeup)
3144{
3145 struct key_state *ks = &session->key[KS_PRIMARY]; /* primary key */
3146 struct key_state *ks_lame = &session->key[KS_LAME_DUCK]; /* retiring key */
3147
3148 /* Make sure we were initialized and that we're not in an error state */
3149 ASSERT(ks->state != S_UNDEF);
3150 ASSERT(ks->state != S_ERROR);
3151 ASSERT(session_id_defined(&session->session_id));
3152
3153 /* Should we trigger a soft reset? -- new key, keeps old key for a while */
3155 {
3157 "TLS: soft reset sec=%d/%d bytes=" counter_format "/%" PRIi64 " pkts=" counter_format
3158 "/%" PRIi64 " aead_limit_send=%" PRIu64 "/%" PRIu64 " aead_limit_recv=%" PRIu64
3159 "/%" PRIu64,
3160 (int)(now - ks->established), session->opt->renegotiate_seconds, ks->n_bytes,
3161 session->opt->renegotiate_bytes, ks->n_packets, session->opt->renegotiate_packets,
3163 session->opt->aead_usage_limit,
3165 session->opt->aead_usage_limit);
3166 key_state_soft_reset(session, to_link);
3167 }
3168
3169 /* Kill lame duck key transition_window seconds after primary key negotiation */
3170 if (lame_duck_must_die(session, wakeup))
3171 {
3172 key_state_free(ks_lame, true, to_link);
3173 msg(D_TLS_DEBUG_LOW, "TLS: tls_process: killed expiring key");
3174 }
3175
3176 bool continue_tls_process = true;
3177 while (continue_tls_process)
3178 {
3179 update_time();
3180
3181 dmsg(D_TLS_DEBUG, "TLS: tls_process: chg=%d ks=%s lame=%s to_link->len=%d wakeup=%d",
3182 continue_tls_process, state_name(ks->state), state_name(ks_lame->state), to_link->len,
3183 *wakeup);
3184 continue_tls_process =
3185 tls_process_state(multi, session, to_link, to_link_addr, to_link_socket_info, wakeup);
3186
3187 if (ks->state == S_ERROR)
3188 {
3189 return false;
3190 }
3191 }
3192
3193 update_time();
3194
3195 /* We often send acks back to back to a following control packet. This
3196 * normally does not create a problem (apart from an extra packet).
3197 * However, with the P_CONTROL_WKC_V1 we need to ensure that the packet
3198 * gets resent if not received by remote, so instead we use an empty
3199 * control packet in this special case */
3200
3201 /* Send 1 or more ACKs (each received control packet gets one ACK) */
3202 if (!to_link->len && !reliable_ack_empty(ks->rec_ack))
3203 {
3205 {
3207 if (!buf)
3208 {
3209 return false;
3210 }
3211
3212 /* We do not write anything to the buffer, this way this will be
3213 * an empty control packet that gets the ack piggybacked and
3214 * also appended the wrapped client key since it has a WCK opcode */
3216 }
3217 else
3218 {
3219 struct buffer buf = ks->ack_write_buf;
3220 ASSERT(buf_init(&buf, multi->opt.frame.buf.headroom));
3221 write_control_auth(session, ks, &buf, to_link_addr, P_ACK_V1, RELIABLE_ACK_SIZE, false);
3222 *to_link = buf;
3223 dmsg(D_TLS_DEBUG, "Dedicated ACK -> TCP/UDP");
3224 }
3225 }
3226
3227 /* When should we wake up again? */
3228 if (ks->state >= S_INITIAL || ks->state == S_ERROR_PRE)
3229 {
3231
3232 if (ks->must_negotiate)
3233 {
3235 }
3236 }
3237
3238 if (ks->established && session->opt->renegotiate_seconds)
3239 {
3240 compute_earliest_wakeup(wakeup, ks->established + session->opt->renegotiate_seconds - now);
3241 }
3242
3243 dmsg(D_TLS_DEBUG, "TLS: tls_process: timeout set to %d", *wakeup);
3244
3245 /* prevent event-loop spinning by setting minimum wakeup of 1 second */
3246 if (*wakeup <= 0)
3247 {
3248 *wakeup = 1;
3249
3250 /* if we had something to send to remote, but to_link was busy,
3251 * let caller know we need to be called again soon */
3252 return true;
3253 }
3254
3255 /* If any of the state changes resulted in the to_link buffer being
3256 * set, we are also active */
3257 if (to_link->len)
3258 {
3259 return true;
3260 }
3261
3262 return false;
3263}
3264
3265static void
3266check_keystate_buf_not_used(struct buffer *to_link, const struct key_state *ks)
3267{
3268 if (ks->state == S_UNDEF || !to_link || !to_link->data)
3269 {
3270 return;
3271 }
3272
3273 const uint8_t *dataptr = to_link->data;
3274
3275 /* we don't expect send_reliable to be NULL when state is
3276 * not S_UNDEF, but people have reported crashes nonetheless,
3277 * therefore we better catch this event, report and exit.
3278 */
3279 if (!ks->send_reliable)
3280 {
3281 msg(M_FATAL,
3282 "ERROR: ks.send_reliable (key-id %d), is NULL "
3283 "while key state is %s. Exiting.",
3284 ks->key_id, state_name(ks->state));
3285 }
3286
3287 for (int j = 0; j < ks->send_reliable->size; j++)
3288 {
3289 if (ks->send_reliable->array[j].buf.data == dataptr)
3290 {
3291 msg(M_INFO,
3292 "Warning buffer of freed TLS session is still in"
3293 " use (key-id %d, ks.send_reliable->array[%d])",
3294 ks->key_id, j);
3295
3296 goto used;
3297 }
3298 }
3299
3300 if (ks->ack_write_buf.data == dataptr)
3301 {
3302 msg(M_INFO, "Warning buffer of freed TLS session is still in use "
3303 "(ks.ack_write_buf, key-id %d)",
3304 ks->key_id);
3305
3306 goto used;
3307 }
3308 return;
3309
3310used:
3311 to_link->len = 0;
3312 to_link->data = 0;
3313}
3314
3322static void
3324{
3325 if (!to_link || !to_link->data)
3326 {
3327 return;
3328 }
3329 const uint8_t *dataptr = to_link->data;
3330
3331 /* Checks buffers in tls_wrap */
3332 if (session->tls_wrap.work.data == dataptr)
3333 {
3334 msg(M_INFO, "Warning buffer of freed TLS session is "
3335 "still in use (tls_wrap.work.data)");
3336 goto used;
3337 }
3338 if (session->tls_wrap_reneg.work.data == dataptr)
3339 {
3340 msg(M_INFO, "Warning buffer of freed TLS session is "
3341 "still in use (tls_wrap_reneg.work.data)");
3342 goto used;
3343 }
3344
3345 for (int i = 0; i < KS_SIZE; i++)
3346 {
3347 const struct key_state *ks = &session->key[i];
3348 check_keystate_buf_not_used(to_link, ks);
3349 }
3350 return;
3351
3352used:
3353 to_link->len = 0;
3354 to_link->data = 0;
3355 /* for debugging, you can add an ASSERT(0); here to trigger an abort */
3356}
3357/*
3358 * Called by the top-level event loop.
3359 *
3360 * Basically decides if we should call tls_process for
3361 * the active or untrusted sessions.
3362 */
3363
3364int
3365tls_multi_process(struct tls_multi *multi, struct buffer *to_link,
3366 struct link_socket_actual **to_link_addr,
3367 struct link_socket_info *to_link_socket_info, interval_t *wakeup)
3368{
3369 struct gc_arena gc = gc_new();
3370 int active = TLSMP_INACTIVE;
3371 bool error = false;
3372 /* kept separate from 'active' on purpose: a restart request must not be
3373 * overwritten by a later TLSMP_ACTIVE/TLSMP_RECONNECT assignment */
3374 bool restart = false;
3375
3377
3378 /*
3379 * Process each session object having state of S_INITIAL or greater,
3380 * and which has a defined remote IP addr.
3381 */
3382
3383 for (int i = 0; i < TM_SIZE; ++i)
3384 {
3385 struct tls_session *session = &multi->session[i];
3386 struct key_state *ks = &session->key[KS_PRIMARY];
3387 const struct key_state *ks_lame = &session->key[KS_LAME_DUCK];
3388
3389 /* set initial remote address. This triggers connecting with that
3390 * session. So we only do that if the TM_ACTIVE session is not
3391 * established */
3392 if (i == TM_INITIAL && ks->state == S_INITIAL && get_primary_key(multi)->state <= S_INITIAL
3393 && link_socket_actual_defined(&to_link_socket_info->lsa->actual))
3394 {
3395 ks->remote_addr = to_link_socket_info->lsa->actual;
3396 }
3397
3399 "TLS: tls_multi_process: i=%d state=%s, mysid=%s, stored-sid=%s, stored-ip=%s", i,
3400 state_name(ks->state), session_id_print(&session->session_id, &gc),
3403
3404 if ((ks->state >= S_INITIAL || ks->state == S_ERROR_PRE)
3406 {
3407 struct link_socket_actual *tla = NULL;
3408
3409 update_time();
3410
3411 if (tls_process(multi, session, to_link, &tla, to_link_socket_info, wakeup))
3412 {
3413 active = TLSMP_ACTIVE;
3414 }
3415
3416 /*
3417 * If tls_process produced an outgoing packet,
3418 * return the link_socket_actual object (which
3419 * contains the outgoing address).
3420 */
3421 if (tla)
3422 {
3423 multi->to_link_addr = *tla;
3424 *to_link_addr = &multi->to_link_addr;
3425 }
3426
3427 /*
3428 * If tls_process hits an error:
3429 * (1) If the session has an unexpired lame duck key, preserve it.
3430 * (2) Reinitialize the session.
3431 * (3) Increment soft error count
3432 */
3433 if (ks->state == S_ERROR)
3434 {
3435 ++multi->n_soft_errors;
3436
3437 if (i == TM_ACTIVE || (i == TM_INITIAL && get_primary_key(multi)->state < S_ACTIVE))
3438 {
3439 error = true;
3440 }
3441
3442 if (i == TM_ACTIVE && ks_lame->state >= S_GENERATED_KEYS
3443 && !multi->opt.single_session)
3444 {
3445 move_session(multi, TM_LAME_DUCK, TM_ACTIVE, true, to_link);
3446 }
3447 else
3448 {
3449 reset_session(multi, session, to_link);
3450 }
3451 }
3452 }
3453 }
3454
3455 update_time();
3456
3458
3459 /* If we have successfully authenticated and are still waiting for the authentication to finish
3460 * move the state machine for the multi context forward */
3461
3462 if (multi->multi_state >= CAS_CONNECT_DONE)
3463 {
3464 /* Only generate keys for the TM_ACTIVE session. We defer generating
3465 * keys for TM_INITIAL until we actually trust it.
3466 * For TM_LAME_DUCK it makes no sense to generate new keys. */
3467 struct tls_session *session = &multi->session[TM_ACTIVE];
3468 struct key_state *ks = &session->key[KS_PRIMARY];
3469
3470 if (ks->state == S_ACTIVE && ks->authenticated == KS_AUTH_TRUE)
3471 {
3472 /* Session is now fully authenticated.
3473 * tls_session_generate_data_channel_keys will move ks->state
3474 * from S_ACTIVE to S_GENERATED_KEYS */
3476 if (status != KEY_GEN_OK)
3477 {
3478 msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
3481 ks->state = S_ERROR_PRE;
3482
3483 /* Invalidating the key state is not enough to recover from a
3484 * DCO desync: the kernel peer has to be re-created, and the
3485 * key state we just invalidated will never be retried, so ask
3486 * for a restart right away */
3488 {
3489 restart = true;
3490 }
3491 }
3492
3493 /* Update auth token on the client if needed on renegotiation
3494 * (key id !=0) */
3495 if (session->key[KS_PRIMARY].key_id != 0)
3496 {
3498 }
3499 }
3500 }
3501
3503 {
3504 multi->multi_state = CAS_PENDING;
3505 }
3506
3507 /*
3508 * If lame duck session expires, kill it.
3509 */
3510 if (lame_duck_must_die(&multi->session[TM_LAME_DUCK], wakeup))
3511 {
3512 tls_session_free(&multi->session[TM_LAME_DUCK], true, to_link);
3513 msg(D_TLS_DEBUG_LOW, "TLS: tls_multi_process: killed expiring key");
3514 }
3515
3516 /*
3517 * If untrusted session achieves TLS authentication,
3518 * move it to active session, usurping any prior session.
3519 *
3520 * A semi-trusted session is one in which the certificate authentication
3521 * succeeded (if cert verification is enabled) but the username/password
3522 * verification failed. A semi-trusted session can forward data on the
3523 * TLS control channel but not on the tunnel channel.
3524 */
3525 if (TLS_AUTHENTICATED(multi, &multi->session[TM_INITIAL].key[KS_PRIMARY]))
3526 {
3527 move_session(multi, TM_ACTIVE, TM_INITIAL, true, to_link);
3528 tas = tls_authentication_status(multi);
3530 "TLS: tls_multi_process: initial untrusted "
3531 "session promoted to %strusted",
3532 tas == TLS_AUTHENTICATION_SUCCEEDED ? "" : "semi-");
3533
3534 if (multi->multi_state == CAS_CONNECT_DONE)
3535 {
3537 active = TLSMP_RECONNECT;
3538 }
3539 }
3540
3541 /*
3542 * A hard error means that TM_ACTIVE hit an S_ERROR state and that no
3543 * other key state objects are S_ACTIVE or higher.
3544 */
3545 if (error)
3546 {
3547 for (int i = 0; i < KEY_SCAN_SIZE; ++i)
3548 {
3549 if (get_key_scan(multi, i)->state >= S_ACTIVE)
3550 {
3551 goto nohard;
3552 }
3553 }
3554 ++multi->n_hard_errors;
3555 }
3556nohard:
3557
3558#ifdef ENABLE_DEBUG
3559 /* DEBUGGING -- flood peer with repeating connection attempts */
3560 {
3561 const int throw_level = GREMLIN_CONNECTION_FLOOD_LEVEL(multi->opt.gremlin);
3562 if (throw_level)
3563 {
3564 for (int i = 0; i < KEY_SCAN_SIZE; ++i)
3565 {
3566 if (get_key_scan(multi, i)->state >= throw_level)
3567 {
3568 ++multi->n_hard_errors;
3569 ++multi->n_soft_errors;
3570 }
3571 }
3572 }
3573 }
3574#endif
3575
3576 gc_free(&gc);
3577
3578 /* strongest outcome wins: killing the session supersedes restarting it,
3579 * and restarting supersedes whatever 'active' ended up being */
3580 if (tas == TLS_AUTHENTICATION_FAILED)
3581 {
3582 return TLSMP_KILL;
3583 }
3584 if (restart)
3585 {
3586 return TLSMP_RESTART;
3587 }
3588 return active;
3589}
3590
3595static void
3597 int key_id)
3598{
3599 struct gc_arena gc = gc_new();
3600 const char *source = print_link_socket_actual(from, &gc);
3601
3602
3603 for (int i = 0; i < KEY_SCAN_SIZE; ++i)
3604 {
3605 const struct key_state *ks = get_key_scan(multi, i);
3606 if (ks->key_id != key_id)
3607 {
3608 continue;
3609 }
3610
3611 /* Our key state has been progressed far enough to be part of a valid
3612 * session but has not generated keys. */
3613 if (ks->state >= S_INITIAL && ks->state < S_GENERATED_KEYS)
3614 {
3615 msg(D_MULTI_DROPPED, "Key %s [%d] not initialized (yet), dropping packet.", source,
3616 key_id);
3617 gc_free(&gc);
3618 return;
3619 }
3620 if (ks->state >= S_ACTIVE && ks->authenticated != KS_AUTH_TRUE)
3621 {
3622 msg(D_MULTI_DROPPED, "Key %s [%d] not authorized%s, dropping packet.", source, key_id,
3623 (ks->authenticated == KS_AUTH_DEFERRED) ? " (deferred)" : "");
3624 gc_free(&gc);
3625 return;
3626 }
3627 }
3628
3630 "TLS Error: local/remote TLS keys are out of sync: %s "
3631 "(received key id: %d, known key ids: %s)",
3632 source, key_id, print_key_id(multi, &gc));
3633 gc_free(&gc);
3634}
3635
3643static inline void
3645 struct buffer *buf, struct crypto_options **opt, bool floated,
3646 const uint8_t **ad_start)
3647{
3648 struct gc_arena gc = gc_new();
3649
3650 uint8_t c = *BPTR(buf);
3651 int op = c >> P_OPCODE_SHIFT;
3652 int key_id = c & P_KEY_ID_MASK;
3653
3654 for (int i = 0; i < KEY_SCAN_SIZE; ++i)
3655 {
3656 struct key_state *ks = get_key_scan(multi, i);
3657
3658 /*
3659 * This is the basic test of TLS state compatibility between a local OpenVPN
3660 * instance and its remote peer.
3661 *
3662 * If the test fails, it tells us that we are getting a packet from a source
3663 * which claims reference to a prior negotiated TLS session, but the local
3664 * OpenVPN instance has no memory of such a negotiation.
3665 *
3666 * It almost always occurs on UDP sessions when the passive side of the
3667 * connection is restarted without the active side restarting as well (the
3668 * passive side is the server which only listens for the connections, the
3669 * active side is the client which initiates connections).
3670 */
3671 if (ks->state >= S_GENERATED_KEYS && key_id == ks->key_id
3672 && ks->authenticated == KS_AUTH_TRUE
3673 && (floated || link_socket_actual_match(from, &ks->remote_addr)))
3674 {
3676 /* return appropriate data channel decrypt key in opt */
3677 *opt = &ks->crypto_options;
3678 if (op == P_DATA_V2)
3679 {
3680 *ad_start = BPTR(buf);
3681 }
3682 ASSERT(buf_advance(buf, 1));
3683 if (op == P_DATA_V1)
3684 {
3685 *ad_start = BPTR(buf);
3686 }
3687 else if (op == P_DATA_V2)
3688 {
3689 if (buf->len < 4)
3690 {
3692 "Protocol error: received P_DATA_V2 from %s but length is < 4",
3694 ++multi->n_soft_errors;
3695 goto done;
3696 }
3697 ASSERT(buf_advance(buf, 3));
3698 }
3699
3700 ++ks->n_packets;
3701 ks->n_bytes += buf->len;
3702 dmsg(D_TLS_KEYSELECT, "TLS: tls_pre_decrypt, key_id=%d, IP=%s", key_id,
3704 gc_free(&gc);
3705 return;
3706 }
3707 }
3708
3710
3711done:
3712 gc_free(&gc);
3714 buf->len = 0;
3715 *opt = NULL;
3716}
3717
3718/*
3719 *
3720 * When we are in TLS mode, this is the first routine which sees
3721 * an incoming packet.
3722 *
3723 * If it's a data packet, we set opt so that our caller can
3724 * decrypt it. We also give our caller the appropriate decryption key.
3725 *
3726 * If it's a control packet, we authenticate it and process it,
3727 * possibly creating a new tls_session if it represents the
3728 * first packet of a new session. For control packets, we will
3729 * also zero the size of *buf so that our caller ignores the
3730 * packet on our return.
3731 *
3732 * Note that openvpn only allows one active session at a time,
3733 * so a new session (once authenticated) will always usurp
3734 * an old session.
3735 *
3736 * Return true if input was an authenticated control channel
3737 * packet.
3738 *
3739 * If we are running in TLS thread mode, all public routines
3740 * below this point must be called with the L_TLS lock held.
3741 */
3742
3743bool
3744tls_pre_decrypt(struct tls_multi *multi, const struct link_socket_actual *from, struct buffer *buf,
3745 struct crypto_options **opt, bool floated, const uint8_t **ad_start)
3746{
3747 if (buf->len <= 0)
3748 {
3749 buf->len = 0;
3750 *opt = NULL;
3751 return false;
3752 }
3753
3754 struct gc_arena gc = gc_new();
3755 bool ret = false;
3756
3757 /* get opcode */
3758 uint8_t pkt_firstbyte = *BPTR(buf);
3759 int op = pkt_firstbyte >> P_OPCODE_SHIFT;
3760
3761 if ((op == P_DATA_V1) || (op == P_DATA_V2))
3762 {
3763 handle_data_channel_packet(multi, from, buf, opt, floated, ad_start);
3764 return false;
3765 }
3766
3767 /* get key_id */
3768 int key_id = pkt_firstbyte & P_KEY_ID_MASK;
3769
3770 /* control channel packet */
3771 bool do_burst = false;
3772 bool new_link = false;
3773 struct session_id sid; /* remote session ID */
3774
3775 /* verify legal opcode */
3776 if (op < P_FIRST_OPCODE || op > P_LAST_OPCODE)
3777 {
3779 {
3780 msg(D_TLS_ERRORS, "Peer tried unsupported key-method 1");
3781 }
3782 msg(D_TLS_ERRORS, "TLS Error: unknown opcode received from %s op=%d",
3783 print_link_socket_actual(from, &gc), op);
3784 goto error;
3785 }
3786
3787 /* hard reset ? */
3788 if (is_hard_reset_method2(op))
3789 {
3790 /* verify client -> server or server -> client connection */
3792 && !multi->opt.server)
3793 || ((op == P_CONTROL_HARD_RESET_SERVER_V2) && multi->opt.server))
3794 {
3796 "TLS Error: client->client or server->server connection attempted from %s",
3798 goto error;
3799 }
3800 }
3801
3802 /*
3803 * Authenticate Packet
3804 */
3805 dmsg(D_TLS_DEBUG, "TLS: control channel, op=%s, IP=%s", packet_opcode_name(op),
3807
3808 /* get remote session-id */
3809 {
3810 struct buffer tmp = *buf;
3811 buf_advance(&tmp, 1);
3813 {
3814 msg(D_TLS_ERRORS, "TLS Error: session-id not found in packet from %s",
3816 goto error;
3817 }
3818 }
3819
3820 int i;
3821 /* use session ID to match up packet with appropriate tls_session object */
3822 for (i = 0; i < TM_SIZE; ++i)
3823 {
3824 struct tls_session *session = &multi->session[i];
3825 struct key_state *ks = &session->key[KS_PRIMARY];
3826
3827 dmsg(
3829 "TLS: initial packet test, i=%d state=%s, mysid=%s, rec-sid=%s, rec-ip=%s, stored-sid=%s, stored-ip=%s",
3830 i, state_name(ks->state), session_id_print(&session->session_id, &gc),
3834
3835 if (session_id_equal(&ks->session_id_remote, &sid))
3836 /* found a match */
3837 {
3838 if (i == TM_LAME_DUCK)
3839 {
3840 msg(D_TLS_ERRORS, "TLS ERROR: received control packet with stale session-id=%s",
3841 session_id_print(&sid, &gc));
3842 goto error;
3843 }
3844 dmsg(D_TLS_DEBUG, "TLS: found match, session[%d], sid=%s", i,
3845 session_id_print(&sid, &gc));
3846 break;
3847 }
3848 }
3849
3850 /*
3851 * Hard reset and session id does not match any session in
3852 * multi->session: Possible initial packet. New sessions always start
3853 * as TM_INITIAL
3854 */
3855 if (i == TM_SIZE && is_hard_reset_method2(op))
3856 {
3857 /*
3858 * No match with existing sessions,
3859 * probably a new session.
3860 */
3861 struct tls_session *session = &multi->session[TM_INITIAL];
3862
3863 /*
3864 * If --single-session, don't allow any hard-reset connection request
3865 * unless it is the first packet of the session.
3866 */
3867 if (multi->opt.single_session && multi->n_sessions)
3868 {
3870 "TLS Error: Cannot accept new session request from %s due "
3871 "to session context expire or --single-session",
3873 goto error;
3874 }
3875
3877 {
3878 goto error;
3879 }
3880
3881#ifdef ENABLE_MANAGEMENT
3882 if (management)
3883 {
3884 management_set_state(management, OPENVPN_STATE_AUTH, NULL, NULL, NULL, NULL, NULL);
3885 }
3886#endif
3887
3888 /*
3889 * New session-initiating control packet is authenticated at this point,
3890 * assuming that the --tls-auth command line option was used.
3891 *
3892 * Without --tls-auth, we leave authentication entirely up to TLS.
3893 */
3894 msg(D_TLS_DEBUG_LOW, "TLS: Initial packet from %s, sid=%s",
3896
3897 do_burst = true;
3898 new_link = true;
3899 i = TM_INITIAL;
3900 session->untrusted_addr = *from;
3901 }
3902 else
3903 {
3904 /*
3905 * Packet must belong to an existing session.
3906 */
3907 if (i != TM_ACTIVE && i != TM_INITIAL)
3908 {
3909 msg(D_TLS_ERRORS, "TLS Error: Unroutable control packet received from %s (si=%d op=%s)",
3911 goto error;
3912 }
3913
3914 struct tls_session *session = &multi->session[i];
3915 struct key_state *ks = &session->key[KS_PRIMARY];
3916 /*
3917 * Verify remote IP address
3918 */
3919 if (!new_link && !link_socket_actual_match(&ks->remote_addr, from))
3920 {
3921 msg(D_TLS_ERRORS, "TLS Error: Received control packet from unexpected IP addr: %s",
3923 goto error;
3924 }
3925
3926 /*
3927 * Remote is requesting a key renegotiation. We only allow renegotiation
3928 * when the previous session is fully established to avoid weird corner
3929 * cases.
3930 */
3932 {
3934 session->opt))
3935 {
3936 goto error;
3937 }
3938
3940
3941 dmsg(D_TLS_DEBUG, "TLS: received P_CONTROL_SOFT_RESET_V1 s=%d sid=%s", i,
3942 session_id_print(&sid, &gc));
3943 }
3944 else
3945 {
3946 bool initial_packet = false;
3947 if (ks->state == S_PRE_START_SKIP)
3948 {
3949 /* When we are coming from the session_skip_to_pre_start
3950 * method, we allow this initial packet to setup the
3951 * tls-crypt-v2 peer specific key */
3952 initial_packet = true;
3953 ks->state = S_PRE_START;
3954 }
3955 /*
3956 * Remote responding to our key renegotiation request?
3957 */
3958 if (op == P_CONTROL_SOFT_RESET_V1)
3959 {
3960 do_burst = true;
3961 }
3962
3964 from, session->opt))
3965 {
3966 /* if an initial packet in read_control_auth, we rather
3967 * error out than anything else */
3968 if (initial_packet)
3969 {
3970 multi->n_hard_errors++;
3971 }
3972 goto error;
3973 }
3974
3975 dmsg(D_TLS_DEBUG, "TLS: received control channel packet s#=%d sid=%s", i,
3976 session_id_print(&sid, &gc));
3977 }
3978 }
3979
3980 /*
3981 * We have an authenticated control channel packet (if --tls-auth/tls-crypt
3982 * or tls-crypt-v2 was set).
3983 * Now pass to our reliability layer which deals with
3984 * packet acknowledgements, retransmits, sequencing, etc.
3985 */
3986 struct tls_session *session = &multi->session[i];
3987 struct key_state *ks = &session->key[KS_PRIMARY];
3988
3989 /* Make sure we were initialized and that we're not in an error state */
3990 ASSERT(ks->state != S_UNDEF);
3991 ASSERT(ks->state != S_ERROR);
3992 ASSERT(session_id_defined(&session->session_id));
3993
3994 /* Let our caller know we processed a control channel packet */
3995 ret = true;
3996
3997 /*
3998 * Set our remote address and remote session_id
3999 */
4000 if (new_link)
4001 {
4002 ks->session_id_remote = sid;
4003 ks->remote_addr = *from;
4004 ++multi->n_sessions;
4005 }
4006 else if (!link_socket_actual_match(&ks->remote_addr, from))
4007 {
4009 "TLS Error: Existing session control channel packet from unknown IP address: %s",
4011 goto error;
4012 }
4013
4014 /*
4015 * Should we do a retransmit of all unacknowledged packets in
4016 * the send buffer? This improves the start-up efficiency of the
4017 * initial key negotiation after the 2nd peer comes online.
4018 */
4019 if (do_burst && !session->burst)
4020 {
4022 session->burst = true;
4023 }
4024
4025 /* Check key_id */
4026 if (ks->key_id != key_id)
4027 {
4028 msg(D_TLS_ERRORS, "TLS ERROR: local/remote key IDs out of sync (%d/%d) ID: %s", ks->key_id,
4029 key_id, print_key_id(multi, &gc));
4030 goto error;
4031 }
4032
4033 /*
4034 * Process incoming ACKs for packets we can now
4035 * delete from reliable send buffer
4036 */
4037 {
4038 /* buffers all packet IDs to delete from send_reliable */
4039 struct reliable_ack send_ack;
4040
4041 if (!reliable_ack_read(&send_ack, buf, &session->session_id))
4042 {
4043 msg(D_TLS_ERRORS, "TLS Error: reading acknowledgement record from packet");
4044 goto error;
4045 }
4047 }
4048
4049 if (op != P_ACK_V1 && reliable_can_get(ks->rec_reliable))
4050 {
4051 packet_id_type id;
4052
4053 /* Extract the packet ID from the packet */
4054 if (reliable_ack_read_packet_id(buf, &id))
4055 {
4056 /* A hard reset always is the first packet of a session, so it
4057 * always must use packet id 0. Ignore it if it claims another id.
4058 * In a specific existing bug these packets were replays of an
4059 * already handled reset, so ignoring it is better than aborting
4060 * the connection attempt.
4061 */
4062 if (is_hard_reset_method2(op) && id != 0)
4063 {
4065 "TLS Error: received %s with packet id " packet_id_format
4066 " from %s -- 0 was expected, ignoring packet",
4069 }
4070 /* Avoid deadlock by rejecting packet that would de-sequentialize receive buffer */
4072 {
4073 if (reliable_not_replay(ks->rec_reliable, id))
4074 {
4075 /* Save incoming ciphertext packet to reliable buffer */
4076 struct buffer *in = reliable_get_buf(ks->rec_reliable);
4077 ASSERT(in);
4078 if (!buf_copy(in, buf))
4079 {
4080 msg(D_MULTI_DROPPED, "Incoming control channel packet too big, dropping.");
4081 goto error;
4082 }
4084 }
4085
4086 /* Process outgoing acknowledgment for packet just received, even if it's a replay
4087 */
4089 }
4090 }
4091 }
4092 /* Remember that we received a valid control channel packet */
4093 ks->peer_last_packet = now;
4094
4095done:
4096 buf->len = 0;
4097 *opt = NULL;
4098 gc_free(&gc);
4099 return ret;
4100
4101error:
4102 ++multi->n_soft_errors;
4104 goto done;
4105}
4106
4107
4108struct key_state *
4110{
4111 struct key_state *ks_select = NULL;
4112 for (int i = 0; i < KEY_SCAN_SIZE; ++i)
4113 {
4114 struct key_state *ks = get_key_scan(multi, i);
4115 if (ks->state >= S_GENERATED_KEYS && ks->authenticated == KS_AUTH_TRUE)
4116 {
4118
4119 if (!ks_select)
4120 {
4121 ks_select = ks;
4122 }
4123 if (now >= ks->auth_deferred_expire)
4124 {
4125 ks_select = ks;
4126 break;
4127 }
4128 }
4129 }
4130 return ks_select;
4131}
4132
4133
4134/* Choose the key with which to encrypt a data packet */
4135void
4136tls_pre_encrypt(struct tls_multi *multi, struct buffer *buf, struct crypto_options **opt)
4137{
4138 multi->save_ks = NULL;
4139 if (buf->len <= 0)
4140 {
4141 buf->len = 0;
4142 *opt = NULL;
4143 return;
4144 }
4145
4146 struct key_state *ks_select = tls_select_encryption_key(multi);
4147
4148 if (ks_select)
4149 {
4150 *opt = &ks_select->crypto_options;
4151 multi->save_ks = ks_select;
4152 dmsg(D_TLS_KEYSELECT, "TLS: tls_pre_encrypt: key_id=%d", ks_select->key_id);
4153 return;
4154 }
4155 else
4156 {
4157 struct gc_arena gc = gc_new();
4158 dmsg(D_TLS_KEYSELECT, "TLS Warning: no data channel send key available: %s",
4159 print_key_id(multi, &gc));
4160 gc_free(&gc);
4161
4162 *opt = NULL;
4163 buf->len = 0;
4164 }
4165}
4166
4167void
4168tls_prepend_opcode_v1(const struct tls_multi *multi, struct buffer *buf)
4169{
4170 const struct key_state *ks = multi->save_ks;
4171
4172 msg(D_TLS_DEBUG, __func__);
4173
4174 ASSERT(ks);
4175 ASSERT(ks->key_id <= P_KEY_ID_MASK);
4176
4177 uint8_t op = (P_DATA_V1 << P_OPCODE_SHIFT) | (uint8_t)ks->key_id;
4178 ASSERT(buf_write_prepend(buf, &op, 1));
4179}
4180
4181void
4182tls_prepend_opcode_v2(const struct tls_multi *multi, struct buffer *buf)
4183{
4184 const struct key_state *ks = multi->save_ks;
4185 uint32_t peer;
4186
4187 msg(D_TLS_DEBUG, __func__);
4188
4189 ASSERT(ks);
4190 peer = htonl(((P_DATA_V2 << P_OPCODE_SHIFT) | ks->key_id) << 24
4191 | (multi->tx_peer_id & 0xFFFFFF));
4192 ASSERT(buf_write_prepend(buf, &peer, 4));
4193}
4194
4195void
4196tls_post_encrypt(struct tls_multi *multi, struct buffer *buf)
4197{
4198 struct key_state *ks = multi->save_ks;
4199 multi->save_ks = NULL;
4200
4201 if (buf->len > 0)
4202 {
4203 ASSERT(ks);
4204
4205 ++ks->n_packets;
4206 ks->n_bytes += buf->len;
4207 }
4208}
4209
4210/*
4211 * Send a payload over the TLS control channel.
4212 * Called externally.
4213 */
4214
4215bool
4216tls_send_payload(struct key_state *ks, const uint8_t *data, size_t size)
4217{
4218 bool ret = false;
4219
4221
4222 ASSERT(ks);
4223
4224 if (ks->state >= S_ACTIVE)
4225 {
4226 ASSERT(size <= INT_MAX);
4227 if (key_state_write_plaintext_const(&ks->ks_ssl, data, (int)size) == 1)
4228 {
4229 ret = true;
4230 }
4231 }
4232 else
4233 {
4234 if (!ks->paybuf)
4235 {
4236 ks->paybuf = buffer_list_new();
4237 }
4238 buffer_list_push_data(ks->paybuf, data, size);
4239 ret = true;
4240 }
4241
4242
4244
4245 return ret;
4246}
4247
4248bool
4249tls_rec_payload(struct tls_multi *multi, struct buffer *buf)
4250{
4251 bool ret = false;
4252
4254
4255 ASSERT(multi);
4256
4257 struct key_state *ks = get_key_scan(multi, 0);
4258
4259 if (ks->state >= S_ACTIVE && BLEN(&ks->plaintext_read_buf))
4260 {
4261 if (buf_copy(buf, &ks->plaintext_read_buf))
4262 {
4263 ret = true;
4264 }
4265 ks->plaintext_read_buf.len = 0;
4266 }
4267
4269
4270 return ret;
4271}
4272
4273void
4274tls_update_remote_addr(struct tls_multi *multi, const struct link_socket_actual *addr)
4275{
4276 struct gc_arena gc = gc_new();
4277 for (int i = 0; i < TM_SIZE; ++i)
4278 {
4279 struct tls_session *session = &multi->session[i];
4280
4281 for (int j = 0; j < KS_SIZE; ++j)
4282 {
4283 struct key_state *ks = &session->key[j];
4284
4287 {
4288 continue;
4289 }
4290
4291 dmsg(D_TLS_KEYSELECT, "TLS: tls_update_remote_addr from IP=%s to IP=%s",
4294
4295 ks->remote_addr = *addr;
4296 }
4297 }
4298 gc_free(&gc);
4299}
4300
4301void
4302show_available_tls_ciphers(const char *cipher_list, const char *cipher_list_tls13,
4303 const char *tls_cert_profile)
4304{
4305 printf("Available TLS Ciphers, listed in order of preference:\n");
4306
4308 {
4309 printf("\nFor TLS 1.3 and newer (--tls-ciphersuites):\n\n");
4310 show_available_tls_ciphers_list(cipher_list_tls13, tls_cert_profile, true);
4311 }
4312
4313 printf("\nFor TLS 1.2 and older (--tls-cipher):\n\n");
4314 show_available_tls_ciphers_list(cipher_list, tls_cert_profile, false);
4315
4316 printf("\n"
4317 "Note: Whether a cipher suite in this list can actually work depends\n"
4318 "on the specific setup of both peers. See the man page entries of\n"
4319 "--tls-cipher and --show-tls for more details.\n\n");
4320}
4321
4322/*
4323 * Dump a human-readable rendition of an openvpn packet
4324 * into a garbage collectable string which is returned.
4325 */
4326const char *
4327protocol_dump(struct buffer *buffer, unsigned int flags, struct gc_arena *gc)
4328{
4329 struct buffer out = alloc_buf_gc(256, gc);
4330 struct buffer buf = *buffer;
4331
4332 uint8_t c;
4333 int op;
4334 int key_id;
4335
4337
4338 if (buf.len <= 0)
4339 {
4340 buf_printf(&out, "DATA UNDEF len=%d", buf.len);
4341 goto done;
4342 }
4343
4344 if (!(flags & PD_TLS))
4345 {
4346 goto print_data;
4347 }
4348
4349 /*
4350 * Initial byte (opcode)
4351 */
4352 if (!buf_read(&buf, &c, sizeof(c)))
4353 {
4354 goto done;
4355 }
4356 op = (c >> P_OPCODE_SHIFT);
4357 key_id = c & P_KEY_ID_MASK;
4358 buf_printf(&out, "%s kid=%d", packet_opcode_name(op), key_id);
4359
4360 if ((op == P_DATA_V1) || (op == P_DATA_V2))
4361 {
4362 goto print_data;
4363 }
4364
4365 /*
4366 * Session ID
4367 */
4368 {
4369 struct session_id sid;
4370
4371 if (!session_id_read(&sid, &buf))
4372 {
4373 goto done;
4374 }
4375 if (flags & PD_VERBOSE)
4376 {
4377 buf_printf(&out, " sid=%s", session_id_print(&sid, gc));
4378 }
4379 }
4380
4381 /*
4382 * tls-auth hmac + packet_id
4383 */
4384 if (tls_auth_hmac_size)
4385 {
4386 struct packet_id_net pin;
4387 uint8_t tls_auth_hmac[MAX_HMAC_KEY_LENGTH];
4388
4389 ASSERT(tls_auth_hmac_size <= MAX_HMAC_KEY_LENGTH);
4390
4391 if (!buf_read(&buf, tls_auth_hmac, tls_auth_hmac_size))
4392 {
4393 goto done;
4394 }
4395 if (flags & PD_VERBOSE)
4396 {
4397 buf_printf(&out, " tls_hmac=%s", format_hex(tls_auth_hmac, tls_auth_hmac_size, 0, gc));
4398 }
4399
4400 if (!packet_id_read(&pin, &buf, true))
4401 {
4402 goto done;
4403 }
4404 buf_printf(&out, " pid=%s", packet_id_net_print(&pin, (flags & PD_VERBOSE), gc));
4405 }
4406 /*
4407 * packet_id + tls-crypt hmac
4408 */
4409 if (flags & PD_TLS_CRYPT)
4410 {
4411 struct packet_id_net pin;
4412 uint8_t tls_crypt_hmac[TLS_CRYPT_TAG_SIZE];
4413
4414 if (!packet_id_read(&pin, &buf, true))
4415 {
4416 goto done;
4417 }
4418 buf_printf(&out, " pid=%s", packet_id_net_print(&pin, (flags & PD_VERBOSE), gc));
4419 if (!buf_read(&buf, tls_crypt_hmac, TLS_CRYPT_TAG_SIZE))
4420 {
4421 goto done;
4422 }
4423 if (flags & PD_VERBOSE)
4424 {
4425 buf_printf(&out, " tls_crypt_hmac=%s",
4426 format_hex(tls_crypt_hmac, TLS_CRYPT_TAG_SIZE, 0, gc));
4427 }
4428 /*
4429 * Remainder is encrypted and optional wKc
4430 */
4431 goto done;
4432 }
4433
4434 /*
4435 * ACK list
4436 */
4437 buf_printf(&out, " %s", reliable_ack_print(&buf, (flags & PD_VERBOSE), gc));
4438
4439 if (op == P_ACK_V1)
4440 {
4441 goto print_data;
4442 }
4443
4444 /*
4445 * Packet ID
4446 */
4447 {
4449 if (!buf_read(&buf, &l, sizeof(l)))
4450 {
4451 goto done;
4452 }
4453 l = ntohpid(l);
4455 }
4456
4457print_data:
4458 if (flags & PD_SHOW_DATA)
4459 {
4460 buf_printf(&out, " DATA %s", format_hex(BPTR(&buf), BLEN(&buf), 80, gc));
4461 }
4462 else
4463 {
4464 buf_printf(&out, " DATA len=%d", buf.len);
4465 }
4466
4467done:
4468 return BSTR(&out);
4469}
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:416
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:475
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:1210
void free_buf(struct buffer *buf)
Free the memory allocated for a buffer.
Definition buffer.c:169
void buf_clear(struct buffer *buf)
Zeroise and reset a buffer.
Definition buffer.c:148
void buffer_list_pop(struct buffer_list *ol)
Remove and free the head buffer of the list.
Definition buffer.c:1302
bool buf_printf(struct buffer *buf, const char *format,...)
printf-style append to a buffer with overflow check.
Definition buffer.c:226
struct buffer_list * buffer_list_new(void)
Allocate an empty buffer list of capacity max_size.
Definition buffer.c:1156
struct buffer * buffer_list_peek(struct buffer_list *ol)
Retrieve the head buffer.
Definition buffer.c:1238
void buffer_list_free(struct buffer_list *ol)
Frees a buffer list and all the buffers in it.
Definition buffer.c:1165
void * gc_malloc(size_t size, bool clear, struct gc_arena *a)
Allocate memory and, optionally, zero it.
Definition buffer.c:318
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:452
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:616
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:1320
#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:1365
#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:1335
static bool buf_write_prepend(struct buffer *dest, const void *src, int size)
Prepend data to a buffer.
Definition buffer.h:1286
static int buf_read_u16(struct buffer *buf)
Read and consume a uint16_t from the front of a buffer.
Definition buffer.h:1534
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:1383
#define ALLOC_ARRAY_CLEAR_GC(dptr, type, n, gc)
Allocate and zero-initialise a garbage-collected array of n elements.
Definition buffer.h:2093
static bool buf_safe(const struct buffer *buf, size_t len)
Check whether len bytes can be appended to a buffer.
Definition buffer.h:1017
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:1474
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:769
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:1188
static bool buf_write(struct buffer *dest, const void *src, size_t size)
Append data to a buffer.
Definition buffer.h:1262
static bool buf_write_u8(struct buffer *dest, uint8_t data)
Append a uint8_t to a buffer.
Definition buffer.h:1306
#define ALLOC_OBJ_CLEAR_GC(dptr, type, gc)
Allocate and zero-initialise a garbage-collected object of the given type.
Definition buffer.h:2134
static int buf_read_u8(struct buffer *buf)
Read and consume a uint8_t from the front of a buffer.
Definition buffer.h:1513
#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:983
#define BLENZ(buf)
Return the length of the buffer content as a size_t.
Definition buffer.h:153
static void strncpynt(char *dest, const char *src, size_t maxlen)
Like strncpy() but always null-terminates the destination.
Definition buffer.h:710
static void check_malloc_return(void *p)
Abort if a memory allocation returned NULL.
Definition buffer.h:2146
static void gc_free(struct gc_arena *a)
Free all allocations in a garbage collection arena.
Definition buffer.h:1976
#define ALLOC_OBJ_CLEAR(dptr, type)
Allocate and zero-initialise memory for a single object of the given type.
Definition buffer.h:2038
#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:1960
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
#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:1100
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:1180
void init_key_type(struct key_type *kt, const char *ciphername, const char *authname, bool tls_mode, bool warn)
Initialize a key_type structure with.
Definition crypto.c:875
bool check_key(struct key *key, const struct key_type *kt)
Definition crypto.c:1126
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:345
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:1062
void key_direction_state_init(struct key_direction_state *kds, int key_direction)
Definition crypto.c:1682
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:1735
#define KEY_DIRECTION_NORMAL
Definition crypto.h:232
#define CO_PACKET_ID_LONG_FORM
Bit-flag indicating whether to use OpenVPN's long packet ID format.
Definition crypto.h:347
#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:359
#define CO_USE_DYNAMIC_TLS_CRYPT
Bit-flag indicating that renegotiations are using tls-crypt with a TLS-EKM derived key.
Definition crypto.h:375
#define CO_IGNORE_PACKET_ID
Bit-flag indicating whether to ignore the packet ID of a received packet.
Definition crypto.h:350
#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:363
#define CO_EPOCH_DATA_KEY_FORMAT
Bit-flag indicating the epoch the data format.
Definition crypto.h:379
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:736
#define KEY_DIRECTION_INVERSE
Definition crypto.h:233
static bool aead_usage_limit_reached(const uint64_t limit, const struct key_ctx *key_ctx, int64_t higest_pid)
Checks if the usage limit for an AEAD cipher is reached.
Definition crypto.h:765
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:76
#define D_PUSH
Definition errlevel.h:82
#define D_TLS_DEBUG_MED
Definition errlevel.h:156
#define D_DCO
Definition errlevel.h:93
#define D_SHOW_KEYS
Definition errlevel.h:120
#define D_MULTI_DROPPED
Definition errlevel.h:100
#define D_HANDSHAKE
Definition errlevel.h:71
#define D_SHOW_KEY_SOURCE
Definition errlevel.h:121
#define D_TLS_KEYSELECT
Definition errlevel.h:145
#define D_MTU_INFO
Definition errlevel.h:104
#define D_TLS_ERRORS
Definition errlevel.h:58
#define M_INFO
Definition errlevel.h:54
#define D_TLS_DEBUG
Definition errlevel.h:164
#define S_ACTIVE
Operational key_state state immediately after negotiation has completed while still within the handsh...
Definition ssl_common.h:100
struct tls_auth_standalone * tls_auth_standalone_init(struct tls_options *tls_options, struct gc_arena *gc)
Definition ssl.c:1215
#define TM_INITIAL
As yet un-trusted tls_session \ being negotiated.
Definition ssl_common.h:545
#define KS_SIZE
Size of the tls_session.key array.
Definition ssl_common.h:468
static void tls_session_free(struct tls_session *session, bool clear, struct buffer *to_link)
Clean up a tls_session structure.
Definition ssl.c:1064
void tls_init_control_channel_frame_parameters(struct frame *frame, int tls_mtu)
Definition ssl.c:150
void tls_multi_free(struct tls_multi *multi, bool clear)
Cleanup a tls_multi structure and free associated memory allocations.
Definition ssl.c:1267
#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:464
#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
struct tls_multi * tls_multi_init(struct tls_options *tls_options)
Allocate and initialize a tls_multi structure.
Definition ssl.c:1174
void tls_multi_init_finalize(struct tls_multi *multi, int tls_mtu)
Finalize initialization of a tls_multi structure.
Definition ssl.c:1192
#define TM_LAME_DUCK
Old tls_session.
Definition ssl_common.h:548
static void tls_session_init(struct tls_multi *multi, struct tls_session *session)
Initialize a tls_session structure.
Definition ssl.c:991
#define TM_SIZE
Size of the tls_multi.session \ array.
Definition ssl_common.h:549
static void key_state_free(struct key_state *ks, bool clear, struct buffer *to_link)
Cleanup a key_state structure.
Definition ssl.c:912
void tls_auth_standalone_free(struct tls_auth_standalone *tas)
Frees a standalone tls-auth verification object.
Definition ssl.c:1240
#define TM_ACTIVE
Active tls_session.
Definition ssl_common.h:544
#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:465
#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:823
void tls_multi_init_set_options(struct tls_multi *multi, const char *local, const char *remote)
Definition ssl.c:1256
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, struct buffer *buf)
Perform some accounting for the key state used.
Definition ssl.c:4196
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:4109
#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:4168
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:4136
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:4182
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:3744
void reliable_free(struct reliable *rel)
Free allocated memory associated with a reliable structure and the pointer itself.
Definition reliable.c:364
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:144
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:595
void reliable_schedule_now(struct reliable *rel)
Reschedule all entries of a reliable structure to be ready for (re)sending immediately.
Definition reliable.c:719
bool reliable_ack_read_packet_id(struct buffer *buf, packet_id_type *pid)
Read the packet ID of a received packet.
Definition reliable.c:109
static int reliable_ack_outstanding(struct reliable_ack *ack)
Returns the number of packets that need to be acked.
Definition reliable.h:211
void reliable_mark_active_incoming(struct reliable *rel, struct buffer *buf, packet_id_type pid, int opcode)
Mark the reliable entry associated with the given buffer as active incoming.
Definition reliable.c:771
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:804
const char * reliable_ack_print(struct buffer *buf, bool verbose, struct gc_arena *gc)
Definition reliable.c:305
bool reliable_ack_acknowledge_packet_id(struct reliable_ack *ack, packet_id_type pid)
Record a packet ID for later acknowledgment.
Definition reliable.c:127
static void reliable_set_timeout(struct reliable *rel, interval_t timeout)
Definition reliable.h:548
bool reliable_can_get(const struct reliable *rel)
Check whether a reliable structure has any free buffers available for use.
Definition reliable.c:487
void reliable_send_purge(struct reliable *rel, const struct reliable_ack *ack)
Remove acknowledged packets from a reliable structure.
Definition reliable.c:402
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:551
struct buffer * reliable_send(struct reliable *rel, int *opcode)
Get the next packet to send to the remote peer.
Definition reliable.c:671
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:645
bool reliable_empty(const struct reliable *rel)
Check whether a reliable structure is empty.
Definition reliable.c:380
bool reliable_not_replay(const struct reliable *rel, packet_id_type id)
Check that a received packet's ID is not a replay.
Definition reliable.c:505
#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:737
struct reliable_entry * reliable_get_entry_sequenced(struct reliable *rel)
Get the buffer of the next sequential and active entry.
Definition reliable.c:630
void reliable_init(struct reliable *rel, int buf_size, int offset, int array_size, bool hold)
Initialize a reliable structure.
Definition reliable.c:348
void reliable_mark_deleted(struct reliable *rel, struct buffer *buf)
Remove an entry from a reliable structure.
Definition reliable.c:831
int reliable_get_num_output_sequenced_available(struct reliable *rel)
Counts the number of free buffers in output that can be potentially used for sending.
Definition reliable.c:566
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:532
#define ACK_SIZE(n)
Definition reliable.h:81
static bool reliable_ack_empty(struct reliable_ack *ack)
Check whether an acknowledgment structure contains any packet IDs to be acknowledged.
Definition reliable.h:187
#define TLS_CRYPT_TAG_SIZE
Definition tls_crypt.h:88
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:97
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
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:3901
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:2881
#define MF_EXTERNAL_KEY
Definition manage.h:36
#define OPENVPN_STATE_AUTH
Definition manage.h:460
#define OPENVPN_STATE_WAIT
Definition manage.h:459
#define MF_EXTERNAL_CERT
Definition manage.h:42
static bool management_enable_def_auth(const struct management *man)
Definition manage.h:440
#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:814
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:474
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:522
void output_peer_info_env(struct env_set *es, const char *peer_info)
Definition misc.c:760
struct buffer prepend_dir(const char *dir, const char *path, struct gc_arena *gc)
Prepend a directory to a path.
Definition misc.c:783
void protect_user_pass(struct user_pass *up)
Encrypt username and password buffers in user_pass.
Definition misc.c:794
void set_auth_token(struct user_pass *tk, const char *token)
Sets the auth-token to token.
Definition misc.c:502
#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, struct key_type *kt, const struct options *options, struct link_socket_info *lsi)
Set the –mssfix option.
Definition mss.c:317
void frame_print(const struct frame *frame, msglvl_t msglevel, const char *prefix)
Definition mtu.c:198
#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:552
bool key_is_external(const struct options *options)
Definition options.c:4165
#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:971
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_persist_load_obj(const struct packet_id_persist *p, struct packet_id *pid)
Definition packet_id.c:546
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:317
const char * packet_id_net_print(const struct packet_id_net *pin, bool print_timestamp, struct gc_arena *gc)
Definition packet_id.c:421
#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:328
#define ntohpid(x)
Definition packet_id.h:64
static int packet_id_size(bool long_form)
Definition packet_id.h:322
int platform_stat(const char *path, platform_stat_t *buf)
Definition platform.c:526
struct _stat platform_stat_t
Definition platform.h:118
bool plugin_defined(const struct plugin_list *pl, const int type)
Definition plugin.c:904
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:2531
#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:546
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)
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:395
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:1601
void ssl_set_auth_token_user(const char *username)
Definition ssl.c:375
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:525
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:3141
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:959
static int auth_deferred_expire_window(const struct tls_options *o)
Definition ssl.c:2495
static bool push_peer_info_peerid(struct buffer *out, struct tls_multi *multi, struct tls_session *session)
Definition ssl.c:1923
static struct user_pass passbuf
Definition ssl.c:254
static const char * print_key_id(struct tls_multi *multi, struct gc_arena *gc)
Definition ssl.c:772
#define INCR_GENERATED
Definition ssl.c:93
static struct user_pass auth_token
Definition ssl.c:289
static void compute_earliest_wakeup(interval_t *earliest, time_t seconds_from_now)
Definition ssl.c:1130
static bool lame_duck_must_die(const struct tls_session *session, interval_t *wakeup)
Definition ssl.c:1147
void ssl_set_auth_nocache(void)
Definition ssl.c:350
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:1420
static bool check_outgoing_ciphertext(struct key_state *ks, struct tls_session *session, struct buffer *to_link, bool *continue_tls_process)
Definition ssl.c:2831
static const char * ks_auth_name(enum ks_auth_state auth)
Definition ssl.c:731
static int key_source2_read(struct key_source2 *k2, struct buffer *buf, bool server)
Definition ssl.c:1770
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:3644
bool tls_send_payload(struct key_state *ks, const uint8_t *data, size_t size)
Definition ssl.c:4216
static void reset_session(struct tls_multi *multi, struct tls_session *session, struct buffer *to_link)
Definition ssl.c:1119
static void export_user_keying_material(struct tls_session *session)
Definition ssl.c:2271
void ssl_put_auth_challenge(const char *cr_str)
Definition ssl.c:420
#define INCR_SUCCESS
Definition ssl.c:94
int pem_password_callback(char *buf, int size, int rwflag, void *u)
Callback to retrieve the user's password.
Definition ssl.c:268
static bool control_packet_needs_wkc(const struct key_state *ks)
Definition ssl.c:2713
void tls_update_remote_addr(struct tls_multi *multi, const struct link_socket_actual *addr)
Updates remote address in TLS sessions.
Definition ssl.c:4274
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:2687
static void key_source2_print(const struct key_source2 *k)
Definition ssl.c:1321
static struct user_pass auth_user_pass
Definition ssl.c:288
bool tls_rec_payload(struct tls_multi *multi, struct buffer *buf)
Definition ssl.c:4249
static bool write_outgoing_tls_ciphertext(struct tls_session *session, bool *continue_tls_process)
Definition ssl.c:2745
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:3323
static void check_keystate_buf_not_used(struct buffer *to_link, const struct key_state *ks)
Definition ssl.c:3266
static void flush_payload_buffer(struct key_state *ks)
Definition ssl.c:1802
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:3596
bool tls_session_update_crypto_params_do_work(struct tls_multi *multi, struct tls_session *session, struct options *options, struct frame *frame, struct frame *frame_fragment, struct link_socket_info *lsi, dco_context_t *dco)
Definition ssl.c:1633
void tls_session_soft_reset(struct tls_multi *tls_multi)
Definition ssl.c:1833
void auth_user_pass_setup(const char *auth_file, bool is_inline, bool username_only, const struct static_challenge_info *sci)
Definition ssl.c:302
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:788
static bool push_peer_info(struct buffer *buf, 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:1958
static char * read_string_alloc(struct buffer *buf)
Definition ssl.c:1902
key_gen_status
Outcome of generating the data channel keys of a session.
Definition ssl.c:1413
@ KEY_GEN_DCO_DESYNC
the DCO peer is gone from the kernel
Definition ssl.c:1416
@ KEY_GEN_FAILED
generation failed, invalidate the key state
Definition ssl.c:1415
@ KEY_GEN_OK
keys were generated and installed
Definition ssl.c:1414
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:3053
int tls_version_parse(const char *vstr, const char *extra)
Definition ssl.c:434
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:1883
bool session_skip_to_pre_start(struct tls_session *session, struct tls_pre_decrypt_state *state, struct link_socket_actual *from)
Definition ssl.c:2602
static const char * session_index_name(int index)
Definition ssl.c:750
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:2559
static uint64_t tls_get_limit_aead(const char *ciphername)
Definition ssl.c:129
static bool random_bytes_to_buf(struct buffer *buf, uint8_t *out, int outlen)
Definition ssl.c:1724
static void move_session(struct tls_multi *multi, int dest, int src, bool reinit_src, struct buffer *to_link)
Definition ssl.c:1094
void ssl_set_auth_token(const char *token)
Definition ssl.c:369
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:1328
#define INCR_SENT
Definition ssl.c:92
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:1362
static enum key_gen_status generate_key_expansion(struct tls_multi *multi, struct key_state *ks, struct tls_session *session)
Definition ssl.c:1537
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:3365
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:2857
static void key_state_soft_reset(struct tls_session *session, struct buffer *to_link)
Definition ssl.c:1818
bool ssl_get_auth_nocache(void)
Definition ssl.c:360
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:2150
void pem_password_setup(const char *auth_file)
Definition ssl.c:257
void init_ssl_lib(void)
Definition ssl.c:234
static void key_source_print(const struct key_source *k, const char *prefix)
Definition ssl.c:1302
bool tls_session_update_crypto_params(struct tls_multi *multi, struct tls_session *session, struct options *options, struct frame *frame, struct frame *frame_fragment, 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:1705
static bool write_empty_string(struct buffer *buf)
Definition ssl.c:1843
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:115
void free_ssl_lib(void)
Definition ssl.c:242
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:2627
static bool auth_user_pass_enabled
Definition ssl.c:287
static char * auth_challenge
Definition ssl.c:292
static bool key_source2_randomize_write(struct key_source2 *k2, struct buffer *buf, bool server)
Definition ssl.c:1739
static const char * state_name(int state)
Definition ssl.c:688
static bool generate_key_expansion_openvpn_prf(const struct tls_session *session, struct key2 *key2)
Definition ssl.c:1493
#define INCR_ERROR
Definition ssl.c:95
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:475
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:197
static bool generate_key_expansion_tls_export(struct tls_session *session, struct key2 *key2)
Definition ssl.c:1479
bool ssl_clean_auth_token(void)
Definition ssl.c:384
static bool write_string(struct buffer *buf, const char *str, const int maxlen)
Definition ssl.c:1853
void enable_auth_user_pass(void)
Definition ssl.c:296
void ssl_purge_auth_challenge(void)
Definition ssl.c:413
void show_available_tls_ciphers(const char *cipher_list, const char *cipher_list_tls13, const char *tls_cert_profile)
Definition ssl.c:4302
static bool read_incoming_tls_plaintext(struct key_state *ks, struct buffer *buf, interval_t *wakeup, bool *continue_tls_process)
Definition ssl.c:2720
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:2305
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:2514
const char * protocol_dump(struct buffer *buffer, unsigned int flags, struct gc_arena *gc)
Definition ssl.c:4327
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:474
#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:527
#define PD_TLS
Definition ssl.h:525
#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:526
#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:524
#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:523
#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:566
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:734
#define UP_TYPE_PRIVATE_KEY
Definition ssl_common.h:42
#define SSLF_AUTH_USER_PASS_OPTIONAL
Definition ssl_common.h:426
@ CAS_CONNECT_DONE
Definition ssl_common.h:593
@ CAS_WAITING_AUTH
Initial TLS connection established but deferred auth is not yet finished.
Definition ssl_common.h:581
@ CAS_PENDING
Options import (Connect script/plugin, ccd,...)
Definition ssl_common.h:582
@ CAS_WAITING_OPTIONS_IMPORT
client with pull or p2p waiting for first time options import
Definition ssl_common.h:586
@ CAS_NOT_CONNECTED
Definition ssl_common.h:580
@ CAS_RECONNECT_PENDING
session has already successful established (CAS_CONNECT_DONE) but has a reconnect and needs to redo s...
Definition ssl_common.h:592
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:428
#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:757
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:524
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:479
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:166
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:196
#define EARLY_NEG_FLAG_RESEND_WKC
Definition ssl_pkt.h:313
#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:312
#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:231
#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:305
#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:282
#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:127
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:115
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:968
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:814
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:293
struct epoch_key epoch_key_send
last epoch_key used for generation of the current send data keys.
Definition crypto.h:303
unsigned int flags
Bit-flags determining behavior of security operation functions.
Definition crypto.h:386
struct packet_id_persist * pid_persist
Persistent packet ID state for keeping state between successive OpenVPN process startups.
Definition crypto.h:342
struct key_ctx_bi key_ctx_bi
OpenSSL cipher and HMAC contexts for both sending and receiving directions.
Definition crypto.h:294
struct packet_id packet_id
Current packet ID state for both sending and receiving directions.
Definition crypto.h:333
struct env_item * list
Definition env_set.h:45
uint8_t epoch_key[SHA256_DIGEST_LENGTH]
Definition crypto.h:193
uint16_t epoch
Definition crypto.h:194
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:240
int n
The number of key objects stored in the key2.keys array.
Definition crypto.h:241
struct key keys[2]
Two unidirectional sets of key material.
Definition crypto.h:243
Container for two sets of OpenSSL cipher and/or HMAC contexts for both sending and receiving directio...
Definition crypto.h:280
bool initialized
Definition crypto.h:285
struct key_ctx decrypt
cipher and/or HMAC contexts for receiving direction.
Definition crypto.h:283
struct key_ctx encrypt
Cipher and/or HMAC contexts for sending direction.
Definition crypto.h:281
uint64_t plaintext_blocks
Counter for the number of plaintext block encrypted using this cipher with the current key in number ...
Definition crypto.h:222
Key ordering of the key2.keys array.
Definition crypto.h:259
int in_key
Index into the key2.keys array for the receiving direction.
Definition crypto.h:262
int out_key
Index into the key2.keys array for the sending direction.
Definition crypto.h:260
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:142
Container for unidirectional cipher and HMAC key material.
Definition crypto.h:152
uint8_t cipher[MAX_CIPHER_KEY_LENGTH]
Key material for cipher operations.
Definition crypto.h:153
uint8_t hmac[MAX_HMAC_KEY_LENGTH]
Key material for HMAC operations.
Definition crypto.h:155
unsigned int imported_protocol_flags
Definition options.h:723
bool crl_file_inline
Definition options.h:616
const char * cryptoapi_cert
Definition options.h:638
bool pkcs12_file_inline
Definition options.h:605
const char * ca_file
Definition options.h:593
unsigned int ssl_flags
Definition options.h:625
const char * authname
Definition options.h:581
bool dh_file_inline
Definition options.h:597
const char * pkcs12_file
Definition options.h:604
const char * tls_groups
Definition options.h:608
const char * tls_cert_profile
Definition options.h:609
unsigned int management_flags
Definition options.h:459
const char * ciphername
Definition options.h:575
bool tls_server
Definition options.h:591
const char * extra_certs_file
Definition options.h:600
bool priv_key_file_inline
Definition options.h:603
const char * crl_file
Definition options.h:615
const char * dh_file
Definition options.h:596
bool ca_file_inline
Definition options.h:594
bool extra_certs_file_inline
Definition options.h:601
const char * cipher_list_tls13
Definition options.h:607
const char * ecdh_curve
Definition options.h:610
const char * cipher_list
Definition options.h:606
const char * management_certificate
Definition options.h:456
const char * chroot_dir
Definition options.h:379
const char * ca_path
Definition options.h:595
int ping_rec_timeout
Definition options.h:351
int ping_send_timeout
Definition options.h:350
const char * priv_key_file
Definition options.h:602
const char * cert_file
Definition options.h:598
bool cert_file_inline
Definition options.h:599
Data structure for describing the packet id that is received/send to the network.
Definition packet_id.h:191
uint64_t id
Definition packet_id.h:117
uint64_t id
Definition packet_id.h:153
struct packet_id_send send
Definition packet_id.h:200
struct packet_id_rec rec
Definition packet_id.h:201
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:611
int n_hard_errors
Definition ssl_common.h:637
bool remote_usescomp
remote announced comp-lzo in OCC string
Definition ssl_common.h:705
struct link_socket_actual to_link_addr
Definition ssl_common.h:628
char * peer_info
A multi-line string of general-purpose info received from peer over control channel.
Definition ssl_common.h:672
struct key_state * save_ks
Definition ssl_common.h:622
char * remote_ciphername
cipher specified in peer's config file
Definition ssl_common.h:704
char * locked_username
The locked username is the username we assume the client is using.
Definition ssl_common.h:649
enum multi_status multi_state
Definition ssl_common.h:632
struct tls_options opt
Definition ssl_common.h:616
struct tls_session session[TM_SIZE]
Array of tls_session objects representing control channel sessions with the remote peer.
Definition ssl_common.h:713
struct cert_hash_set * locked_cert_hash_set
Definition ssl_common.h:655
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:644
bool use_peer_id
Definition ssl_common.h:701
bool use_asymmetric_peer_id
Definition ssl_common.h:702
uint32_t tx_peer_id
Definition ssl_common.h:700
char * locked_original_username
The username that client initially used before being overridden by –override-user.
Definition ssl_common.h:653
int n_sessions
Number of sessions negotiated thus far.
Definition ssl_common.h:630
uint32_t rx_peer_id
Definition ssl_common.h:699
int dco_peer_id
This is the handle that DCO uses to identify this session with the kernel.
Definition ssl_common.h:725
int n_soft_errors
Definition ssl_common.h:638
struct tls_wrap_ctx tls_wrap
TLS handshake wrapping state.
Definition ssl_common.h:386
unsigned int crypto_flags
Definition ssl_common.h:367
interval_t renegotiate_seconds
Definition ssl_common.h:349
struct frame frame
Definition ssl_common.h:388
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:454
int replay_window
Definition ssl_common.h:369
struct that stores the temporary data for the tls lite decrypt functions
Definition ssl_pkt.h:106
Structure that wraps the TLS context.
off_t crl_last_size
size of last loaded CRL
time_t crl_last_mtime
CRL last modification time.
Security parameter state of a single session within a VPN tunnel.
Definition ssl_common.h:489
int key_id
The current active key id, used to keep track of renegotiations.
Definition ssl_common.h:511
struct key_state key[KS_SIZE]
Definition ssl_common.h:524
struct tls_options * opt
Definition ssl_common.h:491
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:122
const char * win32_version_string(struct gc_arena *gc)
Get Windows version string with architecture info.
Definition win32.c:1410