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