OpenVPN 3 Core Library
Loading...
Searching...
No Matches
proto.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12// ProtoContext, the fundamental OpenVPN protocol implementation.
13// It can be used by OpenVPN clients, servers, or unit tests.
14
15#ifndef OPENVPN_SSL_PROTO_H
16#define OPENVPN_SSL_PROTO_H
17
18#include <cstring>
19#include <string>
20#include <sstream>
21#include <algorithm> // for std::min
22#include <cstdint> // for std::uint32_t, etc.
23#include <memory>
24#include <optional>
25
26
32#include <openvpn/common/rc.hpp>
45#include <openvpn/ip/ip4.hpp>
46#include <openvpn/ip/ip6.hpp>
47#include <openvpn/ip/udp.hpp>
48#include <openvpn/ip/tcp.hpp>
49#include <openvpn/time/time.hpp>
64#include <openvpn/ssl/psid.hpp>
71#include <openvpn/tun/layer.hpp>
79
80#ifndef OPENVPN_DEBUG_PROTO
81#define OPENVPN_DEBUG_PROTO 1
82#endif
83
84/*
85
86ProtoContext -- OpenVPN protocol implementation
87
88Protocol negotiation states:
89
90Client:
91
921. send client reset to server
932. wait for server reset from server AND ack from 1 (C_WAIT_RESET, C_WAIT_RESET_ACK)
943. start SSL handshake
954. send auth message to server
965. wait for server auth message AND ack from 4 (C_WAIT_AUTH, C_WAIT_AUTH_ACK)
976. go active (ACTIVE)
98
99Server:
100
1011. wait for client reset (S_WAIT_RESET)
1022. send server reset to client
1033. wait for ACK from 2 (S_WAIT_RESET_ACK)
1044. start SSL handshake
1055. wait for auth message from client (S_WAIT_AUTH)
1066. send auth message to client
1077. wait for ACK from 6 (S_WAIT_AUTH_ACK)
1088. go active (ACTIVE)
109
110*/
111
112namespace openvpn {
113
114// utility namespace for ProtoContext
115namespace proto_context_private {
116namespace {
117// clang-format off
118const unsigned char auth_prefix[] = { 0, 0, 0, 0, 2 }; // CONST GLOBAL
119
120const unsigned char keepalive_message[] = { // CONST GLOBAL
121 0x2a, 0x18, 0x7b, 0xf3, 0x64, 0x1e, 0xb4, 0xcb,
122 0x07, 0xed, 0x2d, 0x0a, 0x98, 0x1f, 0xc7, 0x48
123};
124
125enum
126{
127 KEEPALIVE_FIRST_BYTE = 0x2a // first byte of keepalive message
128};
129
130inline bool is_keepalive(const Buffer &buf)
131{
132 return buf.size() >= sizeof(keepalive_message)
133 && buf[0] == KEEPALIVE_FIRST_BYTE
134 && !std::memcmp(keepalive_message, buf.c_data(), sizeof(keepalive_message));
135}
136
137const unsigned char explicit_exit_notify_message[] = { // CONST GLOBAL
138 0x28, 0x7f, 0x34, 0x6b, 0xd4, 0xef, 0x7a, 0x81,
139 0x2d, 0x56, 0xb8, 0xd3, 0xaf, 0xc5, 0x45, 0x9c,
140 6 // OCC_EXIT
141};
142// clang-format on
143
144enum
145{
146 EXPLICIT_EXIT_NOTIFY_FIRST_BYTE = 0x28 // first byte of exit message
147};
148} // namespace
149} // namespace proto_context_private
150
152{
153 public:
155
159 virtual void control_net_send(const Buffer &net_buf) = 0;
160
161 /*
162 * Receive as packet from the network
163 * \note app may take ownership of app_bp via std::move
164 */
165 virtual void control_recv(BufferPtr &&app_bp) = 0;
166
171 virtual void client_auth(Buffer &buf)
172 {
173 write_empty_string(buf); // username
174 write_empty_string(buf); // password
175 }
176
179 virtual void server_auth(const std::string &username,
180 const SafeString &password,
181 const std::string &peer_info,
182 const AuthCert::Ptr &auth_cert)
183 {
184 }
185
190 static void write_empty_string(Buffer &buf)
191 {
192 uint8_t empty[]{0x00, 0x00}; // empty length field without content
193 buf.write(&empty, 2);
194 }
195
199 virtual bool supports_epoch_data() = 0;
200
202 virtual void active(bool primary) = 0;
203};
204
205class ProtoContext : public logging::LoggingMixin<OPENVPN_DEBUG_PROTO,
206 logging::LOG_LEVEL_VERB,
207 ProtoContext>
208{
209#ifdef UNIT_TEST
210 public:
211#else
212 protected:
213#endif
214 static constexpr size_t APP_MSG_MAX = 65536;
215 static constexpr int OPCODE_SIZE = 1;
216
217 enum
218 {
219 // packet opcode (high 5 bits) and key-id (low 3 bits) are combined in one byte
222
223 // packet opcodes -- the V1 is intended to allow protocol changes in the future
224 // CONTROL_HARD_RESET_CLIENT_V1 = 1, // (obsolete) initial key from client, forget previous state
225 // CONTROL_HARD_RESET_SERVER_V1 = 2, // (obsolete) initial key from server, forget previous state
226 CONTROL_SOFT_RESET_V1 = 3, // new key, graceful transition from old to new key
227 CONTROL_V1 = 4, // control channel packet (usually TLS ciphertext)
228 CONTROL_WKC_V1 = 11, // control channel packet with wrapped client key appended
229 ACK_V1 = 5, // acknowledgement for packets received
230 DATA_V1 = 6, // data channel packet with 1-byte header
231 DATA_V2 = 9, // data channel packet with 4-byte header
232
233 // indicates key_method >= 2
234 CONTROL_HARD_RESET_CLIENT_V2 = 7, // initial key from client, forget previous state
235 CONTROL_HARD_RESET_CLIENT_V3 = 10, // initial key from client, forget previous state
236 CONTROL_HARD_RESET_SERVER_V2 = 8, // initial key from server, forget previous state
237
239
240 // DATA_V2 constants
241 OP_SIZE_V2 = 4, // size of initial packet opcode
242 OP_PEER_ID_UNDEF = 0x00FFFFFF, // indicates that Peer ID is undefined
243
244 // states
245 // C_x : client states
246 // S_x : server states
247
248 // ACK states -- must be first before other states
254 LAST_ACK_STATE = 3, // all ACK states must be <= this value
255
256 // key negotiation states (client)
258 C_WAIT_RESET = 5, // must be C_INITIAL+1
260
261 // key negotiation states (server)
263 S_WAIT_RESET = 8, // must be S_INITIAL+1
265
266 // key negotiation states (client and server)
267 ACTIVE = 10,
268 };
269
270 enum iv_proto_flag : unsigned int
271 {
272 // See ssl.h in openvpn2 for detailed documentation of IV_PROTO
273 //
274 // NOTE: Bit field (1 << 0) is reserved for historic reasons
275 // and not expected to be set. Do not use this field.
276 //
281 IV_PROTO_NCP_P2P = (1 << 5), // not implemented
282 IV_PROTO_DNS_OPTION = (1 << 6), // outdated, don't send
288 IV_PROTO_PUSH_UPDATE = (1 << 12)
289 };
290
291 enum tlv_types : uint16_t
292 {
293 EARLY_NEG_FLAGS = 0x0001
294 };
295
296 enum early_neg_flags : uint16_t
297 {
299 };
300
301 static unsigned int opcode_extract(const unsigned int op)
302 {
303 return op >> OPCODE_SHIFT;
304 }
305
306 static unsigned int key_id_extract(const unsigned int op)
307 {
308 return op & KEY_ID_MASK;
309 }
310
311 static size_t op_head_size(const unsigned int op)
312 {
313 return opcode_extract(op) == DATA_V2 ? OP_SIZE_V2 : 1;
314 }
315
316 static unsigned char op_compose(const unsigned int opcode, const unsigned int key_id)
317 {
318 // As long as 'opcode' stays within the range specified by the enum the cast should be safe.
319 // TODO: Use a more constrained type for opcode to ensure range violations can't happen.
320 return static_cast<unsigned char>((opcode << OPCODE_SHIFT) | key_id);
321 }
322
323 static unsigned int op32_compose(const unsigned int opcode,
324 const unsigned int key_id,
325 const int op_peer_id)
326 {
327 return (op_compose(opcode, key_id) << 24) | (op_peer_id & 0x00FFFFFF);
328 }
329
330 public:
331 OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_error);
332 OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, process_server_push_error);
333 OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_option_error);
334
335 // configuration data passed to ProtoContext constructor
336 class ProtoConfig : public RCCopyable<thread_unsafe_refcount>
337 {
338 public:
340
341 // master SSL context factory
343
344 // data channel
346
347 // TLSPRF factory
349
350 // master Frame object
352
353 // (non-smart) pointer to current time
355
356 // Random number generator.
357 // Use-cases demand highest cryptographic strength
358 // such as key generation.
360
361 // Pseudo-random number generator.
362 // Use-cases demand cryptographic strength
363 // combined with high performance. Used for
364 // IV and ProtoSessionID generation.
366
367 // If relay mode is enabled, connect to a special OpenVPN
368 // server that acts as a relay/proxy to a second server.
369 bool relay_mode = false;
370
371 // defer data channel initialization until after client options pull
372 bool dc_deferred = false;
373
374 // transmit username/password creds to server (client-only)
375 bool xmit_creds = true;
376
377 // send client exit notifications via control channel
378 bool cc_exit_notify = false;
379
380 // Transport protocol, i.e. UDPv4, etc.
381 Protocol protocol; // set with set_protocol()
382
383 // OSI layer
385
386 // compressor
388
389 // tls_auth/crypt parms
391 {
392 None = 0,
393 V1 = (1 << 0),
394 V2 = (1 << 1),
395 Dynamic = (1 << 2)
396 };
397
400
403
406
409
412
415
418
421 int key_direction = -1; // 0, 1, or -1 for bidirectional
422
425
427
428 // timeout parameters, relative to construction of KeyContext object
429 Time::Duration handshake_window; // SSL/TLS negotiation must complete by this time
430 Time::Duration become_primary; // KeyContext (that is ACTIVE) becomes primary at this time
431 Time::Duration renegotiate; // start SSL/TLS renegotiation at this time
432 Time::Duration expire; // KeyContext expires at this time
433 Time::Duration tls_timeout; // Packet retransmit timeout on TLS control channel
434
435 // keepalive parameters
436 Time::Duration keepalive_ping; // ping xmit period
437 Time::Duration keepalive_timeout; // timeout period after primary KeyContext reaches ACTIVE state
438 Time::Duration keepalive_timeout_early; // timeout period before primary KeyContext reaches ACTIVE state
439
442
443 // App control config
449
453
454 // op header
455 bool enable_op32 = false;
456 int remote_peer_id = -1; // -1 to disable
457 int local_peer_id = -1; // -1 to disable
458
459 // MTU
460 unsigned int tun_mtu = TUN_MTU_DEFAULT;
461 unsigned int tun_mtu_max = TUN_MTU_DEFAULT + 100;
463 unsigned int mss_fix = 0;
464
465 // For compatibility with openvpn2 we send initial options on rekeying,
466 // instead of possible modifications caused by NCP
467 std::string initial_options;
468
469 bool auth_nocache = false;
470
471 void load(const OptionList &opt,
473 const int default_key_direction,
474 const bool server)
475 {
476 // first set defaults
477 handshake_window = Time::Duration::seconds(60);
478 renegotiate = Time::Duration::seconds(3600);
479 tls_timeout = Time::Duration::seconds(1);
480 keepalive_ping = Time::Duration::seconds(8);
481 keepalive_timeout = Time::Duration::seconds(40);
484 protocol = Protocol();
485 key_direction = default_key_direction;
486
487 // layer
488 {
489 const Option *dev = opt.get_ptr("dev-type");
490 if (!dev)
491 dev = opt.get_ptr("dev");
492 if (!dev)
493 throw proto_option_error(ERR_INVALID_CONFIG, "missing dev-type or dev option");
494 const std::string &dev_type = dev->get(1, 64);
495 if (dev_type.starts_with("tun"))
497 else if (dev_type.starts_with("tap"))
498 throw proto_option_error(ERR_INVALID_CONFIG, "TAP mode is not supported");
499 else
500 throw proto_option_error(ERR_INVALID_OPTION_VAL, "bad dev-type");
501 }
502
503 // cipher/digest/tls-auth/tls-crypt
504 {
507
508 // data channel cipher
509 {
510 const Option *o = opt.get_ptr("cipher");
511 if (o)
512 {
513 const std::string &cipher_name = o->get(1, 128);
514 if (cipher_name != "none")
515 cipher = CryptoAlgs::lookup(cipher_name);
516 }
517 else
518 cipher = CryptoAlgs::lookup("BF-CBC");
519 }
520
521 // data channel HMAC
522 {
523 const Option *o = opt.get_ptr("auth");
524 if (o)
525 {
526 const std::string &auth_name = o->get(1, 128);
527 if (auth_name != "none")
528 digest = CryptoAlgs::lookup(auth_name);
529 }
530 else
531 digest = CryptoAlgs::lookup("SHA1");
532 }
533 dc.set_cipher(cipher);
534 dc.set_digest(digest);
535
536 // tls-auth
537 {
538 const Option *o = opt.get_ptr(relay_prefix("tls-auth"));
539 if (o)
540 {
541 if (!server && tls_crypt_context)
542 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-auth and tls-crypt are mutually exclusive");
543
544 tls_auth_key.parse(o->get(1, 0));
545
546 const Option *tad = opt.get_ptr(relay_prefix("tls-auth-digest"));
547 if (tad)
548 digest = CryptoAlgs::lookup(tad->get(1, 128));
549 if (digest != CryptoAlgs::NONE)
550 set_tls_auth_digest(digest);
551 }
552 }
553
554 // tls-crypt
555 {
556 const Option *o = opt.get_ptr(relay_prefix("tls-crypt"));
557 if (o)
558 {
559 if (!server && tls_auth_context)
560 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-auth and tls-crypt are mutually exclusive");
562 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-crypt and tls-crypt-v2 are mutually exclusive");
563
565 tls_crypt_key.parse(o->get(1, 0));
566
568 }
569 }
570
571 // tls-crypt-v2
572 {
573 const Option *o = opt.get_ptr(relay_prefix("tls-crypt-v2"));
574 if (o)
575 {
576 if (!server && tls_auth_context)
577 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-auth and tls-crypt-v2 are mutually exclusive");
579 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-crypt and tls-crypt-v2 are mutually exclusive");
580
581 // initialize tls_crypt_context
583
584 std::string keyfile = o->get(1, 0);
585
586 if (opt.exists("client"))
587 {
588 // in client mode expect the key to be a PEM encoded tls-crypt-v2 client key (key + WKc)
589 TLSCryptV2ClientKey tls_crypt_v2_key(tls_crypt_context);
590 tls_crypt_v2_key.parse(keyfile);
591 tls_crypt_v2_key.extract_key(tls_crypt_key);
592 tls_crypt_v2_key.extract_wkc(wkc);
593 }
594 else
595 {
597 {
598 // in server mode this is a PEM encoded tls-crypt-v2 server key
599 TLSCryptV2ServerKey tls_crypt_v2_key;
600 tls_crypt_v2_key.parse(keyfile);
601 tls_crypt_v2_key.extract_key(tls_crypt_key);
602 }
603 }
605 }
606 }
607 }
608
609 // key-direction
610 {
611 if (key_direction >= -1 && key_direction <= 1)
612 {
613 const Option *o = opt.get_ptr(relay_prefix("key-direction"));
614 if (o)
615 {
616 const std::string &dir = o->get(1, 16);
617 if (dir == "0")
618 key_direction = 0;
619 else if (dir == "1")
620 key_direction = 1;
621 else if (dir == "bidirectional" || dir == "bi")
622 key_direction = -1;
623 else
624 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "bad key-direction parameter");
625 }
626 }
627 else
628 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "bad key-direction default");
629 }
630
631 // compression
632 {
633 const Option *o = opt.get_ptr("compress");
634 if (o)
635 {
636 if (o->size() >= 2)
637 {
638 const std::string meth_name = o->get(1, 128);
640 if (meth == CompressContext::NONE)
641 OPENVPN_THROW_ARG1(proto_option_error, ERR_INVALID_OPTION_VAL, "Unknown compressor: '" << meth_name << '\'');
643 }
644 else
646 }
647 else
648 {
649 o = opt.get_ptr("comp-lzo");
650 if (o)
651 {
652 if (o->size() == 2 && o->ref(1) == "no")
653 {
654 // On the client, by using ANY instead of ANY_LZO, we are telling the server
655 // that it's okay to use any of our supported compression methods.
657 }
658 else
659 {
661 }
662 }
663 }
664 }
665
666 // tun-mtu
669
670 // mssfix
671 mss_parms.parse(opt, true);
673 {
675 {
677 mss_parms.mtu = true;
678 }
679 else
680 {
682 mss_parms.fixed = true;
683 }
684 }
685
686 // load parameters that can be present in both config file or pushed options
688 }
689
699
700 // load options string pushed by server
702 {
703 // data channel
705
706 // protocol-flags
708
709 // compression
710 parse_pushed_compression(opt, pco);
711
712 // peer ID
714
715 // custom app control channel options
717
718 try
719 {
720 // load parameters that can be present in both config file or pushed options
722 }
723 catch (const std::exception &e)
724 {
725 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed parameter: " << e.what());
726 }
727
728 // show negotiated options
730 }
731
733 {
734 try
735 {
736 const Option *o = opt.get_ptr("custom-control");
737 if (o)
738 {
739 app_control_config.max_msg_size = o->get_num(1, 1, std::numeric_limits<int>::max());
740 const auto &flags = o->get(2, 1024);
741 const auto &protocols = o->get(3, 1024);
743
745
746 /* This implementation always wants to have at least both base64 and text encoding */
748 {
749 OPENVPN_LOG("Warning: custom app control requires base64 encoding to properly work");
750 }
751 }
752 }
753 catch (const std::exception &e)
754 {
755 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed parameter: " << e.what());
757 }
758 }
759
761 {
762 // cipher
763 std::string new_cipher;
764 try
765 {
766 const Option *o = opt.get_ptr("cipher");
767 if (o)
768 {
769 new_cipher = o->get(1, 128);
770 if (new_cipher != "none")
771 dc.set_cipher(CryptoAlgs::lookup(new_cipher));
772 }
773 }
774 catch (const std::exception &e)
775 {
776 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed cipher '" << new_cipher << "': " << e.what());
777 }
778
779 // digest
780 std::string new_digest;
781 try
782 {
783 const Option *o = opt.get_ptr("auth");
784 if (o)
785 {
786 new_digest = o->get(1, 128);
787 if (new_digest != "none")
788 dc.set_digest(CryptoAlgs::lookup(new_digest));
789 }
790 }
791 catch (const std::exception &e)
792 {
793 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed digest '" << new_digest << "': " << e.what());
794 }
795 }
796
798 {
799 try
800 {
801 const Option *o = opt.get_ptr("peer-id");
802 if (o)
803 {
804 bool status = parse_number_validate<int>(o->get(1, 16),
805 16,
806 -1,
807 0xFFFFFE,
809 if (!status)
810 throw Exception("parse/range issue");
811 enable_op32 = true;
812 }
813 }
814 catch (const std::exception &e)
815 {
816 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed peer-id: " << e.what());
817 }
818 }
819
821 {
822 // tls key-derivation method with old key-derivation option
823 std::string key_method;
824 try
825 {
826 const Option *o = opt.get_ptr("key-derivation");
827 if (o)
828 {
829 key_method = o->get(1, 128);
830 if (key_method == "tls-ekm")
832 else
833 OPENVPN_THROW(process_server_push_error, "Problem accepting key-derivation method '" << key_method << "'");
834 }
835 else
837 }
838 catch (const std::exception &e)
839 {
840 OPENVPN_THROW(process_server_push_error, "Problem accepting key-derivation method '" << key_method << "': " << e.what());
841 }
842
843 try
844 {
845 const Option *o = opt.get_ptr("protocol-flags");
846 if (o)
847 {
848 o->min_args(2);
849 for (std::size_t i = 1; i < o->size(); i++)
850 {
851 std::string flag = o->get(i, 128);
852 if (flag == "cc-exit")
853 {
854 cc_exit_notify = true;
855 }
856 else if (flag == "dyn-tls-crypt")
857 {
859 }
860 else if (flag == "tls-ekm")
861 {
862 // Overrides "key-derivation" method set above
864 }
865 else if (flag == "aead-epoch")
866 {
868 }
869 else
870 {
871 OPENVPN_THROW(process_server_push_error, "unknown flag '" << flag << "'");
872 }
873 }
874 }
875 }
876 catch (const std::exception &e)
877 {
878 OPENVPN_THROW(process_server_push_error, "Problem accepting protocol-flags: " << e.what());
879 }
880 }
881
883 {
884 std::string new_comp;
885 try
886 {
887 const Option *o;
888 o = opt.get_ptr("compress");
889 if (o)
890 {
891 new_comp = o->get(1, 128);
893 if (meth != CompressContext::NONE)
894 {
895 // if compression is not availabe, CompressContext ctor throws an exception
896 if (pco.is_comp())
898 else
899 {
900 // server pushes compression but client has compression disabled
901 // degrade to asymmetric compression (downlink only)
902 comp_ctx = CompressContext(meth, true);
903 if (!comp_ctx.is_any_stub(meth))
904 {
905 OPENVPN_LOG("Server has pushed compressor "
906 << comp_ctx.str()
907 << ", but client has disabled compression, switching to asymmetric");
908 }
909 }
910 }
911 }
912 else
913 {
914 o = opt.get_ptr("comp-lzo");
915 if (o)
916 {
917 if (o->size() == 2 && o->ref(1) == "no")
918 {
920 }
921 else
922 {
924 }
925 }
926 }
927 }
928 catch (const std::exception &e)
929 {
930 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed compressor '" << new_comp << "': " << e.what());
931 }
932 }
933
934 void get_data_channel_options(std::ostringstream &os) const
935 {
936 os << " data channel:";
937 os << " cipher " << CryptoAlgs::name(dc.cipher());
939 os << ", digest " << CryptoAlgs::name(dc.digest());
940
941 os << ", peer-id " << remote_peer_id;
942
943 if (dc.useEpochKeys())
944 os << ", aead-epoch";
945
946 os << '\n';
947 }
948
949 void show_cc_enc_option(std::ostringstream &os) const
950 {
951 if (tls_auth_enabled())
952 {
953 os << " control channel: tls-auth enabled\n";
954 }
956 {
957 os << " control channel: tls-crypt v2 enabled\n";
958 }
959 else if (tls_crypt_enabled())
960 {
961 os << " control channel: tls-crypt enabled\n";
962 }
963 else if (dynamic_tls_crypt_enabled())
964 {
965 os << " control channel: dynamic tls-crypt enabled\n";
966 }
967 }
968
969 std::string show_options() const
970 {
971 std::ostringstream os;
972 os << "PROTOCOL OPTIONS:\n";
973 os << " key-derivation: " << CryptoAlgs::name(dc.key_derivation()) << '\n';
975 os << " compress: " << comp_ctx.str() << '\n';
976
979
981 {
982 os << " app custom control channel: " << app_control_config.str() << '\n';
983 }
984
985 return os.str();
986 }
987
988 void set_protocol(const Protocol &p)
989 {
990 // adjust options for new transport protocol
991 protocol = p;
992 }
993
995 {
997 }
998
1000 {
1002 return;
1003
1004 auto digest = CryptoAlgs::lookup("SHA256");
1005 auto cipher = CryptoAlgs::lookup("AES-256-CTR");
1006
1007 if ((digest == CryptoAlgs::NONE) || (cipher == CryptoAlgs::NONE))
1008 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "missing support for tls-crypt algorithms");
1009
1010 /* TODO: we currently use the default SSL library context here as the
1011 * library context is not available this early. This should not matter
1012 * for the algorithms used by tls_crypt */
1013 tls_crypt_context = tls_crypt_factory->new_obj(nullptr, digest, cipher);
1014 }
1015
1016 void set_xmit_creds(const bool xmit_creds_arg)
1017 {
1018 xmit_creds = xmit_creds_arg;
1019 }
1020
1021 bool tls_auth_enabled() const
1022 {
1024 }
1025
1027 {
1029 }
1030
1035
1037 {
1038 return (tls_crypt_ & TLSCrypt::Dynamic);
1039 }
1040
1041 // generate a string summarizing options that will be
1042 // transmitted to peer for options consistency check
1043 std::string options_string()
1044 {
1045 if (!initial_options.empty())
1046 return initial_options;
1047
1048 std::ostringstream out;
1049
1050 const bool server = ssl_factory->mode().is_server();
1051 const unsigned int l2extra = (layer() == Layer::OSI_LAYER_2 ? 32 : 0);
1052
1053 out << "V4";
1054
1055 out << ",dev-type " << layer.dev_type();
1056 out << ",link-mtu " << tun_mtu + link_mtu_adjust() + l2extra;
1057 out << ",tun-mtu " << tun_mtu + l2extra;
1058 out << ",proto " << protocol.occ_str(server);
1059
1060 {
1061 const char *compstr = comp_ctx.options_string();
1062 if (compstr)
1063 out << ',' << compstr;
1064 }
1065
1066 if (tls_auth_context && (key_direction >= 0))
1067 out << ",keydir " << key_direction;
1068
1069 out << ",cipher " << CryptoAlgs::name(dc.cipher(), "[null-cipher]");
1070 out << ",auth " << CryptoAlgs::name(dc.digest(), "[null-digest]");
1071 out << ",keysize " << (CryptoAlgs::key_length(dc.cipher()) * 8);
1072
1073 if (tls_auth_context)
1074 out << ",tls-auth";
1075
1076 // sending tls-crypt does not make sense. If we got to this point it
1077 // means that tls-crypt was already there and it worked fine.
1078 // tls-auth has to be kept for backward compatibility as it is there
1079 // since a bit.
1080
1081 out << ",key-method 2";
1082
1083 if (server)
1084 out << ",tls-server";
1085 else
1086 out << ",tls-client";
1087
1088 initial_options = out.str();
1089
1090 return initial_options;
1091 }
1092
1098 {
1101 {
1102 /* check if the IV_HWADDR is already present in the extra_peer_info set as it has then been
1103 * statically been overridden */
1104 if (!extra_peer_info->contains_key("IV_HWADDR"))
1105 {
1106 std::string hwaddr = get_hwaddr(transport->server_endpoint_addr());
1107 if (!hwaddr.empty())
1108 extra_peer_info_transport->emplace_back("IV_HWADDR", hwaddr);
1109 }
1110 }
1111 }
1112
1113 // generate a string summarizing information about the client
1114 // including capabilities
1115 std::string peer_info_string(bool supports_epoch_data) const
1116 {
1117 std::ostringstream out;
1118 const char *compstr = nullptr;
1119
1120 // supports op32 and P_DATA_V2 and expects a push reply
1121 unsigned int iv_proto = IV_PROTO_DATA_V2
1128
1129 if (supports_epoch_data)
1130 iv_proto |= IV_PROTO_DATA_EPOCH;
1131
1132 if (CryptoAlgs::lookup("SHA256") != CryptoAlgs::NONE && CryptoAlgs::lookup("AES-256-CTR") != CryptoAlgs::NONE)
1133 iv_proto |= IV_PROTO_DYN_TLS_CRYPT;
1134
1135 if (SSLLib::SSLAPI::support_key_material_export())
1136 {
1137 iv_proto |= IV_PROTO_TLS_KEY_EXPORT;
1138 }
1139
1140 out << "IV_VER=" << OPENVPN_VERSION << '\n';
1141 out << "IV_PLAT=" << platform_name() << '\n';
1142 out << "IV_NCP=2\n"; // negotiable crypto parameters V2
1143 out << "IV_TCPNL=1\n"; // supports TCP non-linear packet ID
1144 out << "IV_PROTO=" << iv_proto << '\n';
1145 out << "IV_MTU=" << tun_mtu_max << "\n";
1146 /*
1147 * OpenVPN3 allows to be pushed any cipher that it supports as it
1148 * only implements secure ones and BF-CBC for backwards
1149 * compatibility and generally adopts the concept of the server being
1150 * responsible for sensible choices. Include the cipher here since
1151 * OpenVPN 2.5 will otherwise ignore it and break on conrer cases
1152 * like --cipher AES-128-CBC on client and --data-ciphers "AES-128-CBC"
1153 * on server.
1154 *
1155 */
1156 out << "IV_CIPHERS=";
1158 [&out](CryptoAlgs::Type type, const CryptoAlgs::Alg &alg) -> bool
1159 {
1160 if (!alg.dc_cipher())
1161 return false;
1162 out << alg.name() << ':';
1163 return true;
1164 });
1165 out.seekp(-1, std::ios_base::cur);
1166 out << "\n";
1167
1168 compstr = comp_ctx.peer_info_string();
1169
1170 if (compstr)
1171 out << compstr;
1172 if (extra_peer_info)
1173 out << extra_peer_info->to_string();
1175 out << extra_peer_info_transport->to_string();
1176 if (is_bs64_cipher(dc.cipher()))
1177 out << "IV_BS64DL=1\n"; // indicate support for data limits when using 64-bit block-size ciphers, version 1 (CVE-2016-6329)
1178 if (relay_mode)
1179 out << "IV_RELAY=1\n";
1180
1181
1182 const std::string ret = out.str();
1183 OVPN_LOG_INFO("Sending Peer Info:\n"
1184 << ret);
1185 return ret;
1186 }
1187
1188 // Used to generate link_mtu option sent to peer.
1189 // Not const because dc.context() caches the DC context.
1190 unsigned int link_mtu_adjust()
1191 {
1192 size_t dc_overhead;
1193 if (dc.cipher() == CryptoAlgs::BF_CBC)
1194 {
1195 /* since often configuration lack BF-CBC, we hardcode the overhead for BF-CBC to avoid
1196 * trying to load BF-CBC, which is not available anymore in modern crypto libraries */
1197 dc_overhead = CryptoAlgs::size(dc.digest()) // HMAC
1198 + 64 / 8 // Cipher IV
1199 + 64 / 8; // worst-case PKCS#7 padding expansion (blocksize)
1200 }
1201 else
1202 {
1203 dc_overhead = dc.context().encap_overhead();
1204 }
1205 const size_t adj = protocol.extra_transport_bytes() + // extra 2 bytes for TCP-streamed packet length
1206 (enable_op32 ? 4 : 1) + // leading op
1207 comp_ctx.extra_payload_bytes() + // compression header
1208 PacketIDData::size(false) + // sequence number
1209 dc_overhead; // data channel crypto layer overhead
1210 return (unsigned int)adj;
1211 }
1212
1213 private:
1220
1221 // load parameters that can be present in both config file or pushed options
1222 void load_common(const OptionList &opt,
1224 const LoadCommonType type)
1225 {
1226 // duration parms
1227 load_duration_parm(renegotiate, "reneg-sec", opt, 10, false, false);
1229 load_duration_parm(expire, "tran-window", opt, 10, false, false);
1231 load_duration_parm(handshake_window, "hand-window", opt, 10, false, false);
1232 if (is_bs64_cipher(dc.cipher())) // special data limits for 64-bit block-size ciphers (CVE-2016-6329)
1233 {
1234 become_primary = Time::Duration::seconds(5);
1235 tls_timeout = Time::Duration::milliseconds(1000);
1236 }
1237 else
1238 become_primary = Time::Duration::seconds(std::min(handshake_window.to_seconds(),
1239 renegotiate.to_seconds() / 2));
1240 load_duration_parm(become_primary, "become-primary", opt, 0, false, false);
1241 load_duration_parm(tls_timeout, "tls-timeout", opt, 100, false, true);
1242
1243 if (type == LOAD_COMMON_SERVER)
1244 renegotiate += handshake_window; // avoid renegotiation collision with client
1245
1246 // keepalive, ping, ping-restart
1247 {
1248 const Option *o = opt.get_ptr("keepalive");
1249 if (o)
1250 {
1251 set_duration_parm(keepalive_ping, "keepalive ping", o->get(1, 16), 1, false, false);
1252 set_duration_parm(keepalive_timeout, "keepalive timeout", o->get(2, 16), 1, type == LOAD_COMMON_SERVER, false);
1253
1254 if (o->size() >= 4)
1255 set_duration_parm(keepalive_timeout_early, "keepalive timeout early", o->get(3, 16), 1, false, false);
1256 else
1258 }
1259 else
1260 {
1261 load_duration_parm(keepalive_ping, "ping", opt, 1, false, false);
1262 load_duration_parm(keepalive_timeout, "ping-restart", opt, 1, false, false);
1263 }
1264 }
1265
1266 if ((type == LOAD_COMMON_CLIENT) || (type == LOAD_COMMON_CLIENT_PUSHED))
1267 {
1268 auth_nocache = opt.exists("auth-nocache");
1269 }
1270 }
1271
1272 std::string relay_prefix(const char *optname) const
1273 {
1274 std::string ret;
1275 if (relay_mode)
1276 ret = "relay-";
1277 ret += optname;
1278 return ret;
1279 }
1280 };
1281
1282 // Used to describe an incoming network packet
1284 {
1285 friend class ProtoContext;
1286
1287 enum
1288 {
1289 DEFINED = 1 << 0, // packet is valid (otherwise invalid)
1290 CONTROL = 1 << 1, // packet for control channel (otherwise for data channel)
1291 SECONDARY = 1 << 2, // packet is associated with secondary KeyContext (otherwise primary)
1292 SOFT_RESET = 1 << 3, // packet is a CONTROL_SOFT_RESET_V1 msg indicating a request for SSL/TLS renegotiate
1293 };
1294
1295 public:
1296 bool is_defined() const
1297 {
1298 return flags & DEFINED;
1299 }
1300 bool is_control() const
1301 {
1302 return (flags & (CONTROL | DEFINED)) == (CONTROL | DEFINED);
1303 }
1304 bool is_data() const
1305 {
1306 return (flags & (CONTROL | DEFINED)) == DEFINED;
1307 }
1308 bool is_soft_reset() const
1309 {
1310 return (flags & (CONTROL | DEFINED | SECONDARY | SOFT_RESET))
1312 }
1313 int peer_id() const
1314 {
1315 return peer_id_;
1316 }
1317
1318 private:
1319 PacketType(const Buffer &buf, class ProtoContext &proto)
1321 {
1322 if (likely(buf.size()))
1323 {
1324 // get packet header byte
1325 const unsigned int op = buf[0];
1326
1327 // examine opcode
1328 {
1329 const unsigned int opc = opcode_extract(op);
1330 switch (opc)
1331 {
1333 case CONTROL_V1:
1334 case ACK_V1:
1335 {
1336 flags |= CONTROL;
1337 opcode = opc;
1338 break;
1339 }
1340 case DATA_V2:
1341 {
1342 if (unlikely(buf.size() < 4))
1343 return;
1344 std::uint32_t opi;
1345 // avoid unaligned access
1346 std::memcpy(&opi, buf.c_data(), sizeof(opi));
1347 opi = ntohl(opi) & 0x00FFFFFF;
1348 if (opi != OP_PEER_ID_UNDEF)
1349 peer_id_ = opi;
1350 opcode = opc;
1351 break;
1352 }
1353 case DATA_V1:
1354 {
1355 opcode = opc;
1356 break;
1357 }
1360 {
1361 if (!proto.is_server())
1362 return;
1363 flags |= CONTROL;
1364 opcode = opc;
1365 break;
1366 }
1368 if (proto.is_server())
1369 return;
1370 [[fallthrough]];
1371 case CONTROL_WKC_V1:
1372 {
1373 flags |= CONTROL;
1374 opcode = opc;
1375 break;
1376 }
1377 default:
1378 return;
1379 }
1380 }
1381
1382 // examine key ID
1383 {
1384 const unsigned int kid = key_id_extract(op);
1385 if (proto.primary && kid == proto.primary->key_id())
1386 flags |= DEFINED;
1387 else if (proto.secondary && kid == proto.secondary->key_id())
1388 flags |= (DEFINED | SECONDARY);
1389 else if (opcode == CONTROL_SOFT_RESET_V1 && kid == proto.upcoming_key_id)
1391 }
1392 }
1393 }
1394
1395 unsigned int flags;
1396 unsigned int opcode;
1398 };
1399
1400 static const char *opcode_name(const unsigned int opcode)
1401 {
1402 switch (opcode)
1403 {
1405 return "CONTROL_SOFT_RESET_V1";
1406 case CONTROL_V1:
1407 return "CONTROL_V1";
1408 case ACK_V1:
1409 return "ACK_V1";
1410 case DATA_V1:
1411 return "DATA_V1";
1412 case DATA_V2:
1413 return "DATA_V2";
1415 return "CONTROL_HARD_RESET_CLIENT_V2";
1417 return "CONTROL_HARD_RESET_CLIENT_V3";
1419 return "CONTROL_HARD_RESET_SERVER_V2";
1420 case CONTROL_WKC_V1:
1421 return "CONTROL_WKC_V1";
1422 }
1423 return nullptr;
1424 }
1425
1426 std::string dump_packet(const Buffer &buf)
1427 {
1428 std::ostringstream out;
1429 try
1430 {
1431 Buffer b(buf);
1432 const size_t orig_size = b.size();
1433 const unsigned int op = b.pop_front();
1434
1435 const unsigned int opcode = opcode_extract(op);
1436 const char *op_name = opcode_name(opcode);
1437 if (op_name)
1438 out << op_name << '/' << key_id_extract(op);
1439 else
1440 return "BAD_PACKET";
1441
1442 if (opcode == DATA_V1 || opcode == DATA_V2)
1443 {
1444 if (opcode == DATA_V2)
1445 {
1446 const unsigned int p1 = b.pop_front();
1447 const unsigned int p2 = b.pop_front();
1448 const unsigned int p3 = b.pop_front();
1449 const unsigned int peer_id = (p1 << 16) + (p2 << 8) + p3;
1450 if (peer_id != 0xFFFFFF)
1451 out << " PEER_ID=" << peer_id;
1452 }
1453 out << " SIZE=" << b.size() << '/' << orig_size;
1454 }
1455 else
1456 {
1457 {
1458 ProtoSessionID src_psid(b);
1459 out << " SRC_PSID=" << src_psid.str();
1460 }
1461
1463 {
1464 PacketIDControl pid;
1465 pid.read(b);
1466 out << " PID=" << pid.str();
1467
1468 const unsigned char *hmac = b.read_alloc(hmac_size);
1469 out << " HMAC=" << render_hex(hmac, hmac_size);
1470 out << " TLS-CRYPT ENCRYPTED PAYLOAD=" << b.size() << " bytes";
1471 }
1472 else
1473 {
1474 if (tls_wrap_mode == TLS_AUTH)
1475 {
1476 const unsigned char *hmac = b.read_alloc(hmac_size);
1477 out << " HMAC=" << render_hex(hmac, hmac_size);
1478
1479 PacketIDControl pid;
1480 pid.read(b);
1481 out << " PID=" << pid.str();
1482 }
1483
1484 ReliableAck ack{};
1485 ack.read(b);
1486 const bool dest_psid_defined = !ack.empty();
1487 out << " ACK=[";
1488 while (!ack.empty())
1489 {
1490 out << " " << ack.front();
1491 ack.pop_front();
1492 }
1493 out << " ]";
1494
1495 if (dest_psid_defined)
1496 {
1497 ProtoSessionID dest_psid(b);
1498 out << " DEST_PSID=" << dest_psid.str();
1499 }
1500
1501 if (opcode != ACK_V1)
1502 out << " MSG_ID=" << ReliableAck::read_id(b);
1503
1504 out << " SIZE=" << b.size() << '/' << orig_size;
1505 }
1506 }
1507#ifdef OPENVPN_DEBUG_PROTO_DUMP
1508 out << '\n'
1510#endif
1511 }
1512 catch (const std::exception &e)
1513 {
1514 out << " EXCEPTION: " << e.what();
1515 }
1516 return out.str();
1517 }
1518
1519 // used for reading/writing authentication strings (username, password, etc.) from buffer using the
1520 // 2 byte prefix for length
1521 static void write_uint16_length(const size_t size, Buffer &buf)
1522 {
1523 if (size > 0xFFFF)
1524 throw proto_error("auth_string_overflow");
1525 const std::uint16_t net_size = htons(static_cast<std::uint16_t>(size));
1526 buf.write((const unsigned char *)&net_size, sizeof(net_size));
1527 }
1528
1529 static uint16_t read_uint16_length(Buffer &buf)
1530 {
1531 if (!buf.empty())
1532 {
1533 std::uint16_t net_size;
1534 buf.read((unsigned char *)&net_size, sizeof(net_size));
1535 return ntohs(net_size);
1536 }
1537 return 0;
1538 }
1539
1540 template <typename S>
1541 static void write_auth_string(const S &str, Buffer &buf)
1542 {
1543 const size_t len = str.length();
1544 if (len)
1545 {
1546 write_uint16_length(len + 1, buf);
1547 buf.write((const unsigned char *)str.c_str(), len);
1548 buf.null_terminate();
1549 }
1550 else
1551 write_uint16_length(0, buf);
1552 }
1553
1554 template <typename S>
1556 {
1557 const size_t len = read_uint16_length(buf);
1558 if (len)
1559 {
1560 const char *data = (const char *)buf.read_alloc(len);
1561 if (len > 1)
1562 return S(data, len - 1);
1563 }
1564 return S();
1565 }
1566
1567 template <typename S>
1568 static void write_control_string(const S &str, Buffer &buf)
1569 {
1570 const size_t len = str.length();
1571 buf.write((const unsigned char *)str.c_str(), len);
1572 buf.null_terminate();
1573 }
1574
1575 static void write_empty_string(Buffer &buf)
1576 {
1577 write_uint16_length(0, buf);
1578 }
1579
1580 template <typename S>
1581 static S read_control_string(const Buffer &buf)
1582 {
1583 size_t size = buf.size();
1584 if (size)
1585 {
1586 /* Trim any trailing \n or \r or 0x00 characters. Scripts plugin sometimes accidentally include a \n or \r\n in AUTH_FAILED
1587 * or similar messages */
1588 while (size > 0 && (buf[size - 1] == 0 || buf[size - 1] == '\r' || buf[size - 1] == '\n'))
1589 {
1590 --size;
1591 }
1592
1593 if (size)
1594 {
1595 return S{reinterpret_cast<const char *>(buf.c_data()), size};
1596 }
1597 }
1598 return {};
1599 }
1600
1601 template <typename S>
1603 {
1604 const size_t len = str.length();
1605 auto bp = BufferAllocatedRc::Create(len + 1);
1607 control_send(std::move(bp));
1608 }
1609
1610 // Packet structure for managing network packets, passed as a template
1611 // parameter to ProtoStackBase
1613 {
1614 friend class ProtoContext;
1615
1616 public:
1618 {
1619 reset_non_buf();
1620 }
1621
1622 Packet(BufferPtr &&buf_arg, const unsigned int opcode_arg = CONTROL_V1)
1623 : opcode(opcode_arg), buf(std::move(buf_arg))
1624 {
1625 }
1626
1627 // clone packet, including buffer content
1629 {
1630 Packet pkt;
1631 pkt.opcode = opcode;
1633 return pkt;
1634 }
1635
1636 void reset()
1637 {
1638 reset_non_buf();
1639 buf.reset();
1640 }
1641
1642 void frame_prepare(const Frame &frame, const unsigned int context)
1643 {
1644 if (!buf)
1646 frame.prepare(context, *buf);
1647 }
1648
1654 {
1655 return opcode == CONTROL_V1 || opcode == CONTROL_WKC_V1;
1656 }
1657 operator bool() const
1658 {
1659 return bool(buf);
1660 }
1662 {
1663 return buf;
1664 }
1665 const Buffer &buffer() const
1666 {
1667 return *buf;
1668 }
1669
1670 private:
1672 {
1674 }
1675
1676 unsigned int opcode;
1678 };
1679
1680 // KeyContext encapsulates a single SSL/TLS session.
1681 // ProtoStackBase uses CRTP-based static polymorphism for method callbacks.
1682 class KeyContext : ProtoStackBase<Packet, KeyContext>, public RC<thread_unsafe_refcount>
1683 {
1685 friend Base;
1688
1689 // ProtoStackBase protected vars
1690 using Base::now;
1691 using Base::rel_recv;
1692 using Base::rel_send;
1693 using Base::xmit_acks;
1694
1695 // ProtoStackBase member functions
1696 using Base::raw_send;
1699
1700 // Helper for handling deferred data channel setup,
1701 // for example if cipher/digest are pushed.
1703 {
1705 std::optional<CryptoDCInstance::RekeyType> rekey_type;
1706 };
1707
1708 public:
1710
1711 // ProtoStackBase member functions
1713
1714 OPENVPN_SIMPLE_EXCEPTION(tls_crypt_unwrap_wkc_error);
1715
1716 // KeyContext events occur on two basic key types:
1717 // Primary Key -- the key we transmit/encrypt on.
1718 // Secondary Key -- new keys and retiring keys.
1719 //
1720 // The very first key created (key_id == 0) is a
1721 // primary key. Subsequently created keys are always,
1722 // at least initially, secondary keys. Secondary keys
1723 // promote to primary via the KEV_BECOME_PRIMARY event
1724 // (actually KEV_BECOME_PRIMARY swaps the primary and
1725 // secondary keys, so the old primary is demoted
1726 // to secondary and marked for expiration).
1727 //
1728 // Secondary keys are created by:
1729 // 1. locally-generated soft renegotiation requests, and
1730 // 2. peer-requested soft renegotiation requests.
1731 // In each case, any previous secondary key will be
1732 // wiped (including a secondary key that exists due to
1733 // demotion of a previous primary key that has been marked
1734 // for expiration).
1736 {
1738
1739 // KeyContext has reached the ACTIVE state, occurs on both
1740 // primary and secondary.
1742
1743 // SSL/TLS negotiation must complete by this time. If this
1744 // event is hit on the first primary (i.e. first KeyContext
1745 // with key_id == 0), it is fatal to the session and will
1746 // trigger a disconnect/reconnect. If it's hit on the
1747 // secondary, it will trigger a soft renegotiation.
1749
1750 // When a KeyContext (normally the secondary) is scheduled
1751 // to transition to the primary state.
1753
1754 // Waiting for condition on secondary (usually
1755 // dataflow-based) to trigger KEV_BECOME_PRIMARY.
1757
1758 // Start renegotiating a new KeyContext on secondary
1759 // (ignored unless originating on primary).
1761
1762 // Trigger a renegotiation originating from either
1763 // primary or secondary.
1765
1766 // Queue delayed renegotiation request from secondary
1767 // to take effect after KEV_BECOME_PRIMARY.
1769
1770 // Expiration of KeyContext.
1772 };
1773
1774 // for debugging
1775 static const char *event_type_string(const EventType et)
1776 {
1777 switch (et)
1778 {
1779 case KEV_NONE:
1780 return "KEV_NONE";
1781 case KEV_ACTIVE:
1782 return "KEV_ACTIVE";
1783 case KEV_NEGOTIATE:
1784 return "KEV_NEGOTIATE";
1785 case KEV_BECOME_PRIMARY:
1786 return "KEV_BECOME_PRIMARY";
1788 return "KEV_PRIMARY_PENDING";
1789 case KEV_RENEGOTIATE:
1790 return "KEV_RENEGOTIATE";
1792 return "KEV_RENEGOTIATE_FORCE";
1794 return "KEV_RENEGOTIATE_QUEUE";
1795 case KEV_EXPIRE:
1796 return "KEV_EXPIRE";
1797 default:
1798 return "KEV_?";
1799 }
1800 }
1801
1802 KeyContext(ProtoContext &p, const bool initiator, bool psid_cookie_mode = false)
1803 : Base(*p.config->ssl_factory,
1804 p.config->now,
1806 p.config->frame,
1807 p.stats,
1808 psid_cookie_mode),
1809 proto(p),
1811 crypto_flags(0),
1812 dirty(0),
1814 tlsprf(p.config->tlsprf_factory->new_obj(p.is_server()))
1815 {
1816 // reliable protocol?
1817 set_protocol(proto.config->protocol);
1818
1819 // get key_id from parent
1821
1822 // set initial state
1823 set_state((proto.is_server() ? S_INITIAL : C_INITIAL) + (initiator ? 0 : 1));
1824
1825 // cache stuff that we need to access in hot path
1826 cache_op32();
1827
1828 // remember when we were constructed
1830
1831 // set must-negotiate-by time
1833 }
1834
1835 void set_protocol(const Protocol &p)
1836 {
1837 is_reliable = p.is_reliable(); // cache is_reliable state locally
1838 }
1839
1840 uint32_t get_tls_warnings() const
1841 {
1842 return Base::get_tls_warnings();
1843 }
1844
1852 void start(const ProtoSessionID cookie_psid = ProtoSessionID())
1853 {
1854 if (cookie_psid.defined())
1855 {
1857 dirty = true;
1858 }
1859 if (state == C_INITIAL || state == S_INITIAL)
1860 {
1861 send_reset();
1862 set_state(state + 1);
1863 dirty = true;
1864 }
1865 }
1866
1867 // control channel flush
1868 void flush()
1869 {
1870 if (dirty)
1871 {
1873 Base::flush();
1875 dirty = false;
1876 }
1877 }
1878
1879 void invalidate(const Error::Type reason)
1880 {
1881 Base::invalidate(reason);
1882 }
1883
1884 // retransmit packets as part of reliability layer
1886 {
1887 // note that we don't set dirty here
1889 }
1890
1891 // when should we next call retransmit method
1893 {
1894 const Time t = Base::next_retransmit();
1895 if (t <= next_event_time)
1896 return t;
1897 return next_event_time;
1898 }
1899
1901 {
1902 if (bp->size() > APP_MSG_MAX)
1903 throw proto_error("app_send: sent control message is too large");
1904 Base::app_send(std::move(bp));
1905 }
1906
1907 // send app-level cleartext data to peer via SSL
1909 {
1910 if (state >= ACTIVE)
1911 {
1912 app_send_validate(std::move(bp));
1913 dirty = true;
1914 }
1915 else
1916 app_pre_write_queue.push_back(bp);
1917 }
1918
1919 // pass received ciphertext packets on network to SSL/reliability layers
1920 bool net_recv(Packet &&pkt)
1921 {
1922 const bool ret = Base::net_recv(std::move(pkt));
1923 dirty = true;
1924 return ret;
1925 }
1926
1927 // data channel encrypt
1929 {
1930 if (state >= ACTIVE
1932 && !invalidated())
1933 {
1934 // compress and encrypt packet and prepend op header
1935 const bool pid_wrap = do_encrypt(buf, true);
1936
1937 // Trigger a new SSL/TLS negotiation if packet ID (a 32-bit unsigned int)
1938 // is getting close to wrapping around. If it wraps back to 0 without
1939 // a renegotiation, it would cause the replay protection logic to wrongly
1940 // think that all further packets are replays.
1941 if (pid_wrap)
1943 }
1944 else
1945 buf.reset_size(); // no crypto context available
1946 }
1947
1948 // data channel decrypt
1950 {
1951 try
1952 {
1953 if (state >= ACTIVE
1955 && !invalidated())
1956 {
1957 // Knock off leading op from buffer, but pass the 32-bit version to
1958 // decrypt so it can be used as Additional Data for packet authentication.
1959 const size_t head_size = op_head_size(buf[0]);
1960 const unsigned char *op32 = (head_size == OP_SIZE_V2) ? buf.c_data() : nullptr;
1961 buf.advance(head_size);
1962
1963 // decrypt packet
1964 const Error::Type err = crypto->decrypt(buf, now->seconds_since_epoch(), op32);
1965 if (err)
1966 {
1967 proto.stats->error(err);
1968 if (proto.is_tcp() && (err == Error::DECRYPT_ERROR || err == Error::HMAC_ERROR))
1969 invalidate(err);
1970 }
1971
1972 // trigger renegotiation if we hit decrypt data limit
1973 if (data_limit)
1975 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "Unable to add data limit");
1976
1977 // decompress packet
1978 if (compress)
1979 compress->decompress(buf);
1980
1981 // set MSS for segments server can receive
1982 if (proto.config->mss_fix > 0)
1983 MSSFix::mssfix(buf, numeric_cast<uint16_t>(proto.config->mss_fix));
1984 }
1985 else
1986 buf.reset_size(); // no crypto context available
1987 }
1988 catch (std::exception &)
1989 {
1991 buf.reset_size();
1992 if (proto.is_tcp())
1994 }
1995 }
1996
1997 // usually called by parent ProtoContext object when this KeyContext
1998 // has been retired.
2000 {
2001 set_event(current_ev,
2002 KEV_EXPIRE,
2004 }
2005
2006 // set a default next event, if unspecified
2008 {
2009 if (next_event == KEV_NONE && !invalidated())
2011 }
2012
2013 // set a key limit renegotiation event at time t
2014 void key_limit_reneg(const EventType ev, const Time &t)
2015 {
2016 if (t.defined())
2017 set_event(KEV_NONE, ev, t + Time::Duration::seconds(proto.is_server() ? 2 : 1));
2018 }
2019
2020 // return time of upcoming KEV_BECOME_PRIMARY event
2022 {
2024 return next_event_time;
2025 return Time();
2026 }
2027
2028 // is an KEV_x event pending?
2030 {
2033 return current_event != KEV_NONE;
2034 }
2035
2036 // get KEV_x event
2038 {
2039 return current_event;
2040 }
2041
2042 // clear KEV_x event
2044 {
2046 }
2047
2048 // was session invalidated by an exception?
2049 bool invalidated() const
2050 {
2051 return Base::invalidated();
2052 }
2053
2054 // Reason for invalidation
2056 {
2058 }
2059
2060 // our Key ID in the OpenVPN protocol
2061 unsigned int key_id() const
2062 {
2063 return key_id_;
2064 }
2065
2066 // indicates that data channel is keyed and ready to encrypt/decrypt packets
2068 {
2069 return state >= ACTIVE;
2070 }
2071
2072 bool is_dirty() const
2073 {
2074 return dirty;
2075 }
2076
2077 // notification from parent of rekey operation
2079 {
2080 if (crypto)
2081 crypto->rekey(type);
2082 else if (data_channel_key)
2083 {
2084 // save for deferred processing
2085 data_channel_key->rekey_type = type;
2086 }
2087 }
2088
2089 // time that our state transitioned to ACTIVE
2091 {
2092 return reached_active_time_;
2093 }
2094
2095 // transmit a keepalive message to peer
2097 {
2098 send_data_channel_message(proto_context_private::keepalive_message,
2099 sizeof(proto_context_private::keepalive_message));
2100 }
2101
2102 // send explicit-exit-notify message to peer
2104 {
2107 else
2108 send_data_channel_message(proto_context_private::explicit_exit_notify_message,
2109 sizeof(proto_context_private::explicit_exit_notify_message));
2110 }
2111
2112 // general purpose method for sending constant string messages
2113 // to peer via data channel
2114 void send_data_channel_message(const unsigned char *data, const size_t size)
2115 {
2116 if (state >= ACTIVE
2118 && !invalidated())
2119 {
2120 // allocate packet
2121 Packet pkt;
2123
2124 // write keepalive message
2125 pkt.buf->write(data, size);
2126
2127 // process packet for transmission
2128 do_encrypt(*pkt.buf, false); // set compress hint to "no"
2129
2130 // send it
2131 proto.net_send(key_id_, pkt);
2132 }
2133 }
2134
2135 // validate the integrity of a packet
2136 static bool validate(const Buffer &net_buf, ProtoContext &proto, TimePtr now)
2137 {
2138 try
2139 {
2140 Buffer recv(net_buf);
2141
2142 switch (proto.tls_wrap_mode)
2143 {
2144 case TLS_AUTH:
2145 return validate_tls_auth(recv, proto, now);
2146 case TLS_CRYPT_V2:
2148 {
2149 // skip validation of HARD_RESET_V3 because the tls-crypt
2150 // engine has not been initialized yet
2151 OVPN_LOG_VERBOSE("SKIPPING VALIDATION OF HARD_RESET_V3");
2152 return true;
2153 }
2154 /* no break */
2155 case TLS_CRYPT:
2156 return validate_tls_crypt(recv, proto, now);
2157 case TLS_PLAIN:
2158 return validate_tls_plain(recv, proto, now);
2159 }
2160 }
2161 catch ([[maybe_unused]] BufferException &e)
2162 {
2163 OVPN_LOG_VERBOSE("validate() exception: " << e.what());
2164 }
2165 return false;
2166 }
2167
2168 // Resets data_channel_key but also retains old
2169 // rekey_defined and rekey_type from previous instance.
2171 {
2172 std::unique_ptr<DataChannelKey> dck(new DataChannelKey());
2173
2174 if (proto.config->dc.key_derivation() == CryptoAlgs::KeyDerivation::TLS_EKM)
2175 {
2176 // USE RFC 5705 key material export
2177 export_key_material(dck->key, "EXPORTER-OpenVPN-datakeys");
2178 }
2179 else
2180 {
2181 // use the TLS PRF construction to exchange session keys for building
2182 // the data channel crypto context
2184 }
2185 tlsprf->erase();
2187 << " KEY " << CryptoAlgs::name(proto.config->dc.key_derivation())
2188 << " " << proto.mode().str() << ' ' << dck->key.render());
2189
2190 if (data_channel_key)
2191 {
2192 dck->rekey_type = data_channel_key->rekey_type;
2193 }
2194 dck.swap(data_channel_key);
2195 }
2196
2198 {
2199 if (c.mss_parms.fixed)
2200 {
2201 // substract IPv4 and TCP overhead, mssfix method will add extra 20 bytes for IPv6
2202 c.mss_fix = c.mss_parms.mssfix - (20 + 20);
2203 OPENVPN_LOG("fixed mssfix=" << c.mss_fix);
2204 return;
2205 }
2206
2207 /* If we are running default mssfix but have a different tun-mtu pushed
2208 * disable mssfix */
2209 if (c.tun_mtu != TUN_MTU_DEFAULT && c.tun_mtu != 0 && c.mss_parms.mssfix_default)
2210 {
2211 c.mss_fix = 0;
2212 OPENVPN_LOG("mssfix disabled since tun-mtu is non-default ("
2213 << c.tun_mtu << ")");
2214 return;
2215 }
2216
2217 auto payload_overhead = size_t(0);
2218
2219 // compv2 doesn't increase payload size
2220 switch (c.comp_ctx.type())
2221 {
2225 break;
2226 default:
2227 payload_overhead += 1;
2228 }
2229
2231 payload_overhead += PacketIDData::size(false);
2232
2233 // account for IPv4 and TCP headers of the payload, mssfix method
2234 // will add 20 extra bytes if payload is IPv6
2235 payload_overhead += 20 + 20;
2236
2237 auto overhead = c.protocol.extra_transport_bytes()
2238 + (enable_op32 ? OP_SIZE_V2 : 1)
2239 + c.dc.context().encap_overhead();
2240
2241 // in CBC mode, the packet id is part of the payload size / overhead
2243 overhead += PacketIDData::size(false);
2244
2245 if (c.mss_parms.mtu)
2246 {
2247 overhead += c.protocol.is_ipv6()
2248 ? sizeof(struct IPv6Header)
2249 : sizeof(struct IPv4Header);
2250 overhead += proto.is_tcp()
2251 ? sizeof(struct TCPHeader)
2252 : sizeof(struct UDPHeader);
2253 }
2254
2255 auto target = c.mss_parms.mssfix - overhead;
2256 if (CryptoAlgs::mode(c.dc.cipher()) == CryptoAlgs::CBC_HMAC)
2257 {
2258 // openvpn3 crypto includes blocksize in overhead, but we can
2259 // be a bit smarter here and instead make sure that resulting
2260 // ciphertext size (which is always multiple blocksize) is not
2261 // larger than target by running down target to the nearest
2262 // multiple of multiple and substracting 1.
2263
2264 auto block_size = CryptoAlgs::block_size(c.dc.cipher());
2265 target += block_size;
2266 target = (target / block_size) * block_size;
2267 target -= 1;
2268 }
2269
2270 if (!is_safe_conversion<decltype(c.mss_fix)>(target - payload_overhead))
2271 {
2272 OPENVPN_LOG("mssfix disabled since computed value is outside type bounds ("
2273 << c.mss_fix << ")");
2274 c.mss_fix = 0;
2275 return;
2276 }
2277
2278 c.mss_fix = static_cast<decltype(c.mss_fix)>(target - payload_overhead);
2279 OVPN_LOG_VERBOSE("mssfix=" << c.mss_fix
2280 << " (upper bound=" << c.mss_parms.mssfix
2281 << ", overhead=" << overhead
2282 << ", payload_overhead=" << payload_overhead
2283 << ", target=" << target << ")");
2284 }
2285
2286 // Initialize the components of the OpenVPN data channel protocol
2288 {
2289 // don't run until our prerequisites are satisfied
2290 if (!data_channel_key)
2291 return;
2293
2294 // set up crypto for data channel
2295 bool enable_compress = true;
2296 ProtoConfig &c = *proto.config;
2297 const unsigned int key_dir = proto.is_server() ? OpenVPNStaticKey::INVERSE : OpenVPNStaticKey::NORMAL;
2298 const OpenVPNStaticKey &key = data_channel_key->key;
2299
2300 // special data limits for 64-bit block-size ciphers (CVE-2016-6329)
2301 if (is_bs64_cipher(c.dc.cipher()))
2302 {
2306 OVPN_LOG_INFO("Per-Key Data Limit: "
2307 << dp.encrypt_red_limit << '/' << dp.decrypt_red_limit);
2308 data_limit.reset(new DataLimit(dp));
2309 }
2310
2311 // build crypto context for data channel encryption/decryption
2314
2319
2323
2324 crypto->init_pid("DATA",
2325 int(key_id_),
2326 proto.stats);
2327
2329
2330 enable_compress = crypto->consider_compression(proto.config->comp_ctx);
2331
2332 if (data_channel_key->rekey_type.has_value())
2333 crypto->rekey(data_channel_key->rekey_type.value());
2334 data_channel_key.reset();
2335
2336 // set up compression for data channel
2337 if (enable_compress)
2338 compress = proto.config->comp_ctx.new_compressor(proto.config->frame, proto.stats);
2339 else
2340 compress.reset();
2341
2342 // cache op32 for hot path in do_encrypt
2343 cache_op32();
2344
2346 }
2347
2349 const DataLimit::State cdl_status)
2350 {
2351 if (data_limit)
2352 data_limit_event(cdl_mode, data_limit->update_state(cdl_mode, cdl_status));
2353 }
2354
2355 int get_state() const
2356 {
2357 return state;
2358 }
2359
2372 ProtoConfig &proto_config,
2375 {
2376 // the ``WKc`` is located at the end of the packet, after the tls-crypt
2377 // payload.
2378 //
2379 // K_id is optional, and controlled by proto_config.tls_crypt_v2_serverkey_id.
2380 // If it is missing, we will use a single server key for all clients.
2381 //
2382 // Format is as follows:
2383 //
2384 // ``len = len(WKc)`` (16 bit, network byte order)
2385 // ``T = HMAC-SHA256(Ka, len || K_id || Kc || metadata)``
2386 // ``IV = 128 most significant bits of T``
2387 // ``WKc = T || AES-256-CTR(Ke, IV, Kc || metadata) || K_id || len``
2388
2389 const unsigned char *orig_data = recv.data();
2390 const size_t orig_size = recv.size();
2391 const size_t hmac_size = proto_config.tls_crypt_context->digest_size();
2392 const size_t tls_frame_size = OPCODE_SIZE + ProtoSessionID::SIZE
2394 + hmac_size
2395 // the following is the tls-crypt payload
2396 + sizeof(char) // length of ACK array
2397 + sizeof(id_t); // reliable ID
2398
2399 // check that at least the authentication tag ``T`` is present
2400 if (orig_size < (tls_frame_size + hmac_size))
2401 return Error::CC_ERROR;
2402
2403 // the ``WKc`` is just appended after the standard tls-crypt frame
2404 const unsigned char *wkc_raw = orig_data + tls_frame_size;
2405 size_t wkc_raw_size = orig_size - tls_frame_size - sizeof(uint16_t);
2406 // retrieve the ``WKc`` len from the bottom of the packet and convert it to Host Order
2407 uint16_t wkc_len;
2408 // avoid unaligned access
2409 std::memcpy(&wkc_len, wkc_raw + wkc_raw_size, sizeof(wkc_len));
2410 wkc_len = ntohs(wkc_len);
2411
2412 // There's also a payload here, so the assumption that the difference in size
2413 // from the TLS frame's end to the end of the packet constitutes the WKc no
2414 // longer holds. We can only rely on wkc_len for P_CONTROL_WKC_V1 packets.
2415 if (opcode_extract(orig_data[0]) != CONTROL_HARD_RESET_CLIENT_V3)
2416 {
2417 wkc_raw = orig_data + orig_size - wkc_len;
2418 wkc_raw_size = wkc_len - sizeof(uint16_t);
2419 }
2420
2421 uint32_t k_id = 0;
2422 const size_t serverkey_id_size = proto_config.tls_crypt_v2_serverkey_id ? sizeof(k_id) : 0;
2423
2424 if (proto_config.tls_crypt_v2_serverkey_id)
2425 {
2426 std::memcpy(&k_id, wkc_raw + wkc_raw_size - serverkey_id_size, sizeof(k_id));
2427 k_id = ntohl(k_id);
2428 }
2429
2430 // length sanity check (the size of the ``len`` field is included in the value)
2431 if ((wkc_len - sizeof(uint16_t)) != wkc_raw_size)
2432 return Error::CC_ERROR;
2433
2435 // plaintext will be used to compute the Auth Tag, therefore start by prepending
2436 // the WKc length in network order
2437 const uint16_t net_wkc_len = htons(wkc_len);
2438 plaintext.write(&net_wkc_len, sizeof(net_wkc_len));
2439
2440 if (proto_config.tls_crypt_v2_serverkey_id)
2441 {
2442 std::stringstream ss;
2443 ss << std::hex << std::setfill('0') << std::uppercase << std::setw(8) << k_id;
2444
2445 const std::string serverkey_fn = ss.str() + ".key";
2446 const std::string serverkey_path = proto_config.tls_crypt_v2_serverkey_dir + "/"
2447 + serverkey_fn.substr(0, 2) + "/" + serverkey_fn;
2448
2449 // If the key is missing, an exception will be thrown here, for example:
2450 // "cannot open for read: <KEYS_DIR>/06/063FE634.key"
2451 const std::string serverkey = read_text(serverkey_path);
2452
2453 OVPN_LOG_VERBOSE("Using TLS-crypt-V2 server key " << serverkey_path);
2454
2455 TLSCryptV2ServerKey tls_crypt_v2_key;
2456 tls_crypt_v2_key.parse(serverkey);
2457 tls_crypt_v2_key.extract_key(proto_config.tls_crypt_key);
2458
2459 // the server key is composed by one key set only, therefore direction and
2460 // mode should not be specified when slicing
2461 tls_crypt_server.init(proto_config.ssl_factory->libctx(),
2464
2465 k_id = htonl(k_id);
2466 plaintext.write(&k_id, sizeof(k_id));
2467 }
2468
2469 if (plaintext.max_size() <= 2 + serverkey_id_size)
2470 return Error::DECRYPT_ERROR;
2471
2472 const size_t decrypt_bytes = tls_crypt_server.decrypt(wkc_raw,
2473 plaintext.data() + 2 + serverkey_id_size,
2474 plaintext.max_size() - 2 - serverkey_id_size,
2475 wkc_raw + hmac_size,
2476 wkc_raw_size - hmac_size - serverkey_id_size);
2477 plaintext.inc_size(decrypt_bytes);
2478 // decrypted data must at least contain a full 2048bits client key
2479 // (metadata is optional)
2480 if (plaintext.size() < OpenVPNStaticKey::KEY_SIZE)
2481 return Error::DECRYPT_ERROR;
2482
2483 if (!tls_crypt_server.hmac_cmp(wkc_raw, 0, plaintext.c_data(), plaintext.size()))
2484 return Error::HMAC_ERROR;
2485
2486 // we can now remove the WKc length (and the server key ID, if present)
2487 // from the plaintext, as they are not really part of the key material
2488 plaintext.advance(sizeof(wkc_len));
2489
2490 if (proto_config.tls_crypt_v2_serverkey_id)
2491 plaintext.advance(sizeof(k_id));
2492
2494
2495 // verify metadata
2496 int metadata_type = -1;
2497 if (!plaintext.empty())
2498 metadata_type = plaintext.pop_front();
2499
2500 if (tls_crypt_metadata && !tls_crypt_metadata->verify(metadata_type, plaintext))
2502
2503 // virtually remove the WKc from the packet
2504 recv.set_size(orig_size - wkc_len);
2505
2506 return Error::SUCCESS;
2507 }
2508
2509 private:
2511 {
2512 const unsigned char *orig_data = recv.data();
2513 const size_t orig_size = recv.size();
2514
2515 // advance buffer past initial op byte
2516 recv.advance(1);
2517
2518 // get source PSID
2519 ProtoSessionID src_psid(recv);
2520
2521 // verify HMAC
2522 {
2523 recv.advance(proto.hmac_size);
2524 if (!proto.ta_hmac_recv->ovpn_hmac_cmp(orig_data,
2525 orig_size,
2529 {
2530 return false;
2531 }
2532 }
2533
2534 // verify source PSID
2535 if (!proto.psid_peer.match(src_psid))
2536 return false;
2537
2538 // read tls_auth packet ID
2539 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
2540
2541 // get current time_t
2543
2544 // verify tls_auth packet ID
2545 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
2546
2547 // make sure that our own PSID is contained in packet received from peer
2548 if (ReliableAck::ack_skip(recv))
2549 {
2550 ProtoSessionID dest_psid(recv);
2551 if (!proto.psid_self.match(dest_psid))
2552 return false;
2553 }
2554
2555 return pid_ok;
2556 }
2557
2559 {
2560 const unsigned char *orig_data = recv.data();
2561 const size_t orig_size = recv.size();
2562
2563 // advance buffer past initial op byte
2564 recv.advance(1);
2565 // get source PSID
2566 ProtoSessionID src_psid(recv);
2567 // read tls_auth packet ID
2568 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
2569
2570 recv.advance(proto.hmac_size);
2571
2572 const size_t head_size = OPCODE_SIZE + ProtoSessionID::SIZE + PacketIDControl::size();
2573 const size_t data_offset = head_size + proto.hmac_size;
2574 if (orig_size < data_offset)
2575 return false;
2576
2577 // we need a buffer to perform the payload decryption and being this a static
2578 // function we can't use the instance member like in decapsulate_tls_crypt()
2580 proto.config->frame->prepare(Frame::DECRYPT_WORK, work);
2581
2582 // decrypt payload from 'recv' into 'work'
2583 const size_t decrypt_bytes = proto.tls_crypt_recv->decrypt(orig_data + head_size,
2584 work.data(),
2585 work.max_size(),
2586 recv.c_data(),
2587 recv.size());
2588 if (!decrypt_bytes)
2589 return false;
2590
2591 work.inc_size(decrypt_bytes);
2592
2593 // verify HMAC
2594 if (!proto.tls_crypt_recv->hmac_cmp(orig_data,
2596 work.c_data(),
2597 work.size()))
2598 return false;
2599
2600 // verify source PSID
2601 if (proto.psid_peer.defined())
2602 {
2603 if (!proto.psid_peer.match(src_psid))
2604 return false;
2605 }
2606 else
2607 {
2608 proto.psid_peer = src_psid;
2609 }
2610
2611 // get current time_t
2613
2614 // verify tls_auth packet ID
2615 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
2616 // make sure that our own PSID is contained in packet received from peer
2618 {
2619 ProtoSessionID dest_psid(work);
2620 if (!proto.psid_self.match(dest_psid))
2621 return false;
2622 }
2623
2624 return pid_ok;
2625 }
2626
2628 {
2629 // advance buffer past initial op byte
2630 recv.advance(1);
2631
2632 // verify source PSID
2633 ProtoSessionID src_psid(recv);
2634 if (!proto.psid_peer.match(src_psid))
2635 return false;
2636
2637 // make sure that our own PSID is contained in packet received from peer
2638 if (ReliableAck::ack_skip(recv))
2639 {
2640 ProtoSessionID dest_psid(recv);
2641 if (!proto.psid_self.match(dest_psid))
2642 return false;
2643 }
2644 return true;
2645 }
2646
2647 bool do_encrypt(BufferAllocated &buf, const bool compress_hint)
2648 {
2649 if (!is_safe_conversion<uint16_t>(proto.config->mss_fix))
2650 return false;
2651
2652 // set MSS for segments client can receive
2653 if (proto.config->mss_fix > 0)
2654 MSSFix::mssfix(buf, static_cast<uint16_t>(proto.config->mss_fix));
2655
2656 // compress packet
2657 if (compress)
2658 compress->compress(buf, compress_hint);
2659
2660 // trigger renegotiation if we hit encrypt data limit
2661 if (data_limit)
2663 return false;
2664
2665 bool pid_wrap;
2666
2667 if (enable_op32)
2668 {
2669 const std::uint32_t op32 = htonl(op32_compose(DATA_V2, key_id_, remote_peer_id));
2670
2671 static_assert(sizeof(op32) == OP_SIZE_V2, "OP_SIZE_V2 inconsistency");
2672
2673 // encrypt packet
2674 pid_wrap = crypto->encrypt(buf, (const unsigned char *)&op32);
2675
2676 // prepend op
2677 buf.prepend((const unsigned char *)&op32, sizeof(op32));
2678 }
2679 else
2680 {
2681 // encrypt packet
2682 pid_wrap = crypto->encrypt(buf, nullptr);
2683
2684 // prepend op
2686 }
2687 return pid_wrap;
2688 }
2689
2690 // cache op32 and remote_peer_id
2692 {
2693 enable_op32 = proto.config->enable_op32;
2694 remote_peer_id = proto.config->remote_peer_id;
2695 }
2696
2697 void set_state(const int newstate)
2698 {
2700 << " KeyContext[" << key_id_ << "] "
2701 << state_string(state) << " -> " << state_string(newstate));
2702 state = newstate;
2703 }
2704
2705 void set_event(const EventType current)
2706 {
2708 << " KeyContext[" << key_id_ << "] "
2709 << event_type_string(current));
2710 current_event = current;
2711 }
2712
2713 void set_event(const EventType current, const EventType next, const Time &next_time)
2714 {
2716 << " KeyContext[" << key_id_ << "] "
2717 << event_type_string(current) << " -> " << event_type_string(next)
2718 << '(' << seconds_until(next_time) << ')');
2719 current_event = current;
2720 next_event = next;
2721 next_event_time = next_time;
2722 }
2723
2724 void invalidate_callback() // called by ProtoStackBase when session is invalidated
2725 {
2729 }
2730
2731 // Trigger a renegotiation based on data flow condition such
2732 // as per-key data limit or packet ID approaching wraparound.
2734 {
2736 {
2737 OVPN_LOG_VERBOSE(proto.debug_prefix() << " SCHEDULE KEY LIMIT RENEGOTIATION");
2738
2741
2742 // If primary, renegotiate now (within a second or two).
2743 // If secondary, queue the renegotiation request until
2744 // key reaches primary.
2745 if (next_event == KEV_BECOME_PRIMARY) // secondary key before transition to primary?
2746 {
2747 // reneg request crosses over to primary,
2748 // doesn't wipe next_event (KEV_BECOME_PRIMARY)
2750 }
2751 else
2752 {
2754 }
2755 }
2756 }
2757
2758 // Handle data-limited keys such as Blowfish and other 64-bit block-size ciphers.
2759 bool data_limit_add(const DataLimit::Mode mode, const size_t size)
2760 {
2761 if (is_safe_conversion<DataLimit::size_type>(size))
2762 return false;
2763 const DataLimit::State state = data_limit->add(mode, static_cast<DataLimit::size_type>(size));
2764 if (state > DataLimit::None)
2766 return true;
2767 }
2768
2769 // Handle a DataLimit event.
2771 {
2773 << " DATA LIMIT " << DataLimit::mode_str(mode)
2774 << ' ' << DataLimit::state_str(state)
2775 << " key_id=" << key_id_);
2776
2777 // State values:
2778 // DataLimit::Green -- first packet received and decrypted.
2779 // DataLimit::Red -- data limit has been exceeded, so trigger a renegotiation.
2780 if (state == DataLimit::Red)
2782
2783 // When we are in KEV_PRIMARY_PENDING state, we must receive at least
2784 // one packet from the peer on this key before we transition to
2785 // KEV_BECOME_PRIMARY so we can transmit on it.
2786 if (next_event == KEV_PRIMARY_PENDING && data_limit->is_decrypt_green())
2787 set_event(KEV_NONE, KEV_BECOME_PRIMARY, *now + Time::Duration::seconds(1));
2788 }
2789
2790 // Should we enter KEV_PRIMARY_PENDING state? Do it if:
2791 // 1. we are a client,
2792 // 2. data limit is enabled,
2793 // 3. this is a renegotiated key in secondary context, i.e. not the first key, and
2794 // 4. no data received yet from peer on this key.
2795 bool data_limit_defer() const
2796 {
2797 return !proto.is_server()
2798 && data_limit
2799 && key_id_
2800 && !data_limit->is_decrypt_green();
2801 }
2802
2803 // General expiration set when key hits data limit threshold.
2805 {
2806 return *now + (proto.config->handshake_window * 2);
2807 }
2808
2810 {
2813 reached_active() + proto.config->become_primary);
2814 }
2815
2817 {
2818 if (*now >= next_event_time)
2819 {
2820 switch (next_event)
2821 {
2822 case KEV_BECOME_PRIMARY:
2823 if (data_limit_defer())
2825 else
2828 construct_time + proto.config->renegotiate);
2829 break;
2830 case KEV_RENEGOTIATE:
2833 break;
2834 case KEV_NEGOTIATE:
2836 break;
2839 break;
2840 case KEV_EXPIRE:
2842 break;
2843 default:
2844 break;
2845 }
2846 }
2847 }
2848
2849 void kev_error(const EventType ev, const Error::Type reason)
2850 {
2851 proto.stats->error(reason);
2852 invalidate(reason);
2853 set_event(ev);
2854 }
2855
2856 unsigned int initial_op(const bool sender, const bool tls_crypt_v2) const
2857 {
2858 if (key_id_)
2859 {
2860 return CONTROL_SOFT_RESET_V1;
2861 }
2862
2863 if (proto.is_server() == sender)
2865
2866 if (!tls_crypt_v2)
2869 }
2870
2872 {
2873 Packet pkt;
2876 raw_send(std::move(pkt));
2877 }
2878
2880 {
2881 /* The data in the early negotiation packet is structured as
2882 * TLV (type, length, value) */
2883
2884 Buffer buf = pkt.buffer();
2885 while (!buf.empty())
2886 {
2887 if (buf.size() < 4)
2888 {
2889 /* Buffer does not have enough bytes for type (uint16) and length (uint16) */
2890 return false;
2891 }
2892
2893 uint16_t type = read_uint16_length(buf);
2894 uint16_t len = read_uint16_length(buf);
2895
2896 /* TLV defines a length that is larger than the remainder in the buffer. */
2897 if (buf.size() < len)
2898 return false;
2899
2900 if (type == EARLY_NEG_FLAGS)
2901 {
2902 if (len != 2)
2903 return false;
2904 uint16_t flags = read_uint16_length(buf);
2905
2907 {
2908 resend_wkc = true;
2909 }
2910 }
2911 else
2912 {
2913 /* skip over unknown types. We rather ignore undefined TLV to
2914 * not needing to add bits initial reset message (where space
2915 * is really tight) for optional features. */
2916 buf.advance(len);
2917 }
2918 }
2919 return true;
2920 }
2921
2922
2923 void raw_recv(Packet &&raw_pkt) // called by ProtoStackBase
2924 {
2925 if (raw_pkt.opcode == initial_op(false, proto.tls_wrap_mode == TLS_CRYPT_V2))
2926 {
2927 switch (state)
2928 {
2929 case C_WAIT_RESET:
2931 if (!parse_early_negotiation(raw_pkt))
2932 {
2934 }
2935 break;
2936 case S_WAIT_RESET:
2937 send_reset();
2939 break;
2940 }
2941 }
2942 }
2943
2944 void app_recv(BufferPtr &&to_app_buf) // called by ProtoStackBase
2945 {
2946 app_recv_buf.put(std::move(to_app_buf));
2948 throw proto_error("app_recv: received control message is too large");
2950 switch (state)
2951 {
2952 case C_WAIT_AUTH:
2953 if (recv_auth_complete(bcc))
2954 {
2955 recv_auth(bcc.get());
2957 }
2958 break;
2959 case S_WAIT_AUTH:
2960 if (recv_auth_complete(bcc))
2961 {
2962 recv_auth(bcc.get());
2963 send_auth();
2965 }
2966 break;
2967 case S_WAIT_AUTH_ACK:
2968 // rare case where client receives auth, goes ACTIVE,
2969 // but the ACK response is dropped
2970 case ACTIVE:
2971 if (bcc.advance_to_null()) // does composed buffer contain terminating null char?
2972 proto.app_recv(key_id_, bcc.get());
2973 break;
2974 }
2975 }
2976
2977 void net_send(const Packet &net_pkt, const Base::NetSendType nstype) // called by ProtoStackBase
2978 {
2979 if (!is_reliable || nstype != Base::NET_SEND_RETRANSMIT) // retransmit packets on UDP only, not TCP
2980 proto.net_send(key_id_, net_pkt);
2981 }
2982
2984 {
2986 {
2987 switch (state)
2988 {
2989 case C_WAIT_RESET_ACK:
2991 send_auth();
2993 break;
2994 case S_WAIT_RESET_ACK:
2997 break;
2998 case C_WAIT_AUTH_ACK:
2999 active();
3001 break;
3002 case S_WAIT_AUTH_ACK:
3003 active();
3005 break;
3006 }
3007 }
3008 }
3009
3011 {
3012 auto buf = BufferAllocatedRc::Create();
3013 proto.config->frame->prepare(Frame::WRITE_SSL_CLEARTEXT, *buf);
3014 buf->write(proto_context_private::auth_prefix, sizeof(proto_context_private::auth_prefix));
3016 tlsprf->self_write(*buf);
3017 const std::string options = proto.config->options_string();
3018 write_auth_string(options, *buf);
3019 if (!proto.is_server())
3020 {
3021 OVPN_LOG_INFO("Tunnel Options:" << options);
3022 buf->add_flags(BufAllocFlags::DESTRUCT_ZERO);
3023 if (proto.config->xmit_creds)
3024 proto.client_auth(*buf);
3025 else
3026 {
3027 write_empty_string(*buf); // username
3028 write_empty_string(*buf); // password
3029 }
3030 const std::string peer_info = proto.config->peer_info_string(proto.proto_callback->supports_epoch_data());
3031 write_auth_string(peer_info, *buf);
3032 }
3033 app_send_validate(std::move(buf));
3034 dirty = true;
3035 }
3036
3038 {
3039 const unsigned char *buf_pre = buf->read_alloc(sizeof(proto_context_private::auth_prefix));
3040 if (std::memcmp(buf_pre, proto_context_private::auth_prefix, sizeof(proto_context_private::auth_prefix)))
3041 throw proto_error("bad_auth_prefix");
3042 tlsprf->peer_read(*buf);
3043 const std::string options = read_auth_string<std::string>(*buf);
3044 if (proto.is_server())
3045 {
3046 const std::string username = read_auth_string<std::string>(*buf);
3047 const SafeString password = read_auth_string<SafeString>(*buf);
3048 const std::string peer_info = read_auth_string<std::string>(*buf);
3049 proto.proto_callback->server_auth(username, password, peer_info, Base::auth_cert());
3050 }
3051 }
3052
3053 // return true if complete recv_auth message is contained in buffer
3055 {
3056 if (!bc.advance(sizeof(proto_context_private::auth_prefix)))
3057 return false;
3058 if (!tlsprf->peer_read_complete(bc))
3059 return false;
3060 if (!bc.advance_string()) // options
3061 return false;
3062 if (proto.is_server())
3063 {
3064 if (!bc.advance_string()) // username
3065 return false;
3066 if (!bc.advance_string()) // password
3067 return false;
3068 if (!bc.advance_string()) // peer_info
3069 return false;
3070 }
3071 return true;
3072 }
3073
3074 void active()
3075 {
3076 OVPN_LOG_INFO("TLS Handshake: " << Base::ssl_handshake_details());
3077
3078 /* Our internal state machine only decides after push request what protocol
3079 * options we want to use. Therefore we also have to postpone data key
3080 * generation until this happens, create a empty DataChannelKey as
3081 * placeholder */
3082 data_channel_key.reset(new DataChannelKey());
3083 if (!proto.dc_deferred)
3085
3086 while (!app_pre_write_queue.empty())
3087 {
3088 app_send_validate(std::move(app_pre_write_queue.front()));
3089 app_pre_write_queue.pop_front();
3090 dirty = true;
3091 }
3094 active_event();
3095 }
3096
3097 void prepend_dest_psid_and_acks(Buffer &buf, unsigned int opcode)
3098 {
3099 // if sending ACKs, prepend dest PSID
3100 if (xmit_acks.acks_ready())
3101 {
3102 if (proto.psid_peer.defined())
3103 proto.psid_peer.prepend(buf);
3104 else
3105 {
3107 throw proto_error("peer_psid_undef");
3108 }
3109 }
3110
3111 // prepend ACKs for messages received from peer
3112 xmit_acks.prepend(buf, opcode == ACK_V1);
3113 }
3114
3115 bool verify_src_psid(const ProtoSessionID &src_psid)
3116 {
3117 if (proto.psid_peer.defined())
3118 {
3119 if (!proto.psid_peer.match(src_psid))
3120 {
3122 if (proto.is_tcp())
3124 return false;
3125 }
3126 }
3127 else
3128 {
3129 proto.psid_peer = src_psid;
3130 }
3131 return true;
3132 }
3133
3135 {
3136 ProtoSessionID dest_psid(buf);
3137 if (!proto.psid_self.match(dest_psid))
3138 {
3140 if (proto.is_tcp())
3142 return false;
3143 }
3144 return true;
3145 }
3146
3147 void gen_head_tls_auth(const unsigned int opcode, Buffer &buf)
3148 {
3149 // write tls-auth packet ID
3151
3152 // make space for tls-auth HMAC
3154
3155 // write source PSID
3156 proto.psid_self.prepend(buf);
3157
3158 // write opcode
3159 buf.push_front(op_compose(opcode, key_id_));
3160
3161 // write hmac
3163 buf.size(),
3167 }
3168
3169 void gen_head_tls_crypt(const unsigned int opcode, BufferAllocated &buf)
3170 {
3171 // in 'work' we store all the fields that are not supposed to be encrypted
3172 proto.config->frame->prepare(Frame::ENCRYPT_WORK, work);
3173 // make space for HMAC
3175 // write tls-crypt packet ID
3177 // write source PSID
3179 // write opcode
3181
3182 // compute HMAC using header fields (from 'work') and plaintext
3183 // payload (from 'buf')
3186 buf.c_data(),
3187 buf.size());
3188
3189 const size_t data_offset = TLSCryptContext::hmac_offset + proto.hmac_size;
3190
3191 // encrypt the content of 'buf' (packet payload) into 'work'
3192 const size_t encrypt_bytes = proto.tls_crypt_send->encrypt(work.c_data() + TLSCryptContext::hmac_offset,
3193 work.data() + data_offset,
3194 work.max_size() - data_offset,
3195 buf.c_data(),
3196 buf.size());
3197 if (!encrypt_bytes)
3198 {
3199 buf.reset_size();
3200 return;
3201 }
3202 work.inc_size(encrypt_bytes);
3203
3204 // append WKc to wrapped packet for tls-crypt-v2
3205 if ((opcode == CONTROL_HARD_RESET_CLIENT_V3 || opcode == CONTROL_WKC_V1)
3208
3209 // 'work' now contains the complete packet ready to go. swap it with 'buf'
3210 buf.swap(work);
3211 }
3212
3213 void gen_head_tls_plain(const unsigned int opcode, Buffer &buf)
3214 {
3215 // write source PSID
3216 proto.psid_self.prepend(buf);
3217 // write opcode
3218 buf.push_front(op_compose(opcode, key_id_));
3219 }
3220
3221 void gen_head(const unsigned int opcode, BufferAllocated &buf)
3222 {
3223 switch (proto.tls_wrap_mode)
3224 {
3225 case TLS_AUTH:
3226 gen_head_tls_auth(opcode, buf);
3227 break;
3228 case TLS_CRYPT:
3229 case TLS_CRYPT_V2:
3230 gen_head_tls_crypt(opcode, buf);
3231 break;
3232 case TLS_PLAIN:
3233 gen_head_tls_plain(opcode, buf);
3234 break;
3235 }
3236 }
3237
3238 void encapsulate(id_t id, Packet &pkt) // called by ProtoStackBase
3239 {
3240 BufferAllocated &buf = *pkt.buf;
3241
3242 // prepend message sequence number
3243 ReliableAck::prepend_id(buf, id);
3244
3245 // prepend dest PSID and ACKs to reply to peer
3247
3248 // generate message head
3249 int opcode = pkt.opcode;
3250 if (id == 1 && resend_wkc)
3251 {
3252 opcode = CONTROL_WKC_V1;
3253 }
3254
3255 gen_head(opcode, buf);
3256 }
3257
3258 void generate_ack(Packet &pkt) // called by ProtoStackBase
3259 {
3260 BufferAllocated &buf = *pkt.buf;
3261
3262 // prepend dest PSID and ACKs to reply to peer
3264
3265 gen_head(ACK_V1, buf);
3266 }
3267
3269 {
3270 Buffer &recv = *pkt.buf;
3271
3272 // update our last-packet-received time
3274
3275 // verify source PSID
3276 if (!verify_src_psid(src_psid))
3277 return false;
3278
3279 // get current time_t
3281 // verify tls_auth/crypt packet ID
3282 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
3283
3284 // process ACKs sent by peer (if packet ID check failed,
3285 // read the ACK IDs, but don't modify the rel_send object).
3286 if (ReliableAck::ack(rel_send, recv, pid_ok))
3287 {
3288 // make sure that our own PSID is contained in packet received from peer
3289 if (!verify_dest_psid(recv))
3290 return false;
3291 }
3292
3293 // for CONTROL packets only, not ACK
3294 if (pkt.opcode != ACK_V1)
3295 {
3296 // get message sequence number
3297 const id_t id = ReliableAck::read_id(recv);
3298
3299 if (pid_ok)
3300 {
3301 // try to push message into reliable receive object
3302 const unsigned int rflags = rel_recv.receive(pkt, id);
3303
3304 // should we ACK packet back to sender?
3305 if (rflags & ReliableRecv::ACK_TO_SENDER)
3306 xmit_acks.push_back(id); // ACK packet to sender
3307
3308 // was packet accepted by reliable receive object?
3309 if (rflags & ReliableRecv::IN_WINDOW)
3310 {
3311 // remember tls_auth packet ID so that it can't be replayed
3312 proto.ta_pid_recv.test_add(pid, t, true);
3313 return true;
3314 }
3315 }
3316 else // treat as replay
3317 {
3319 if (pid.is_valid())
3320 // even replayed packets must be ACKed or protocol could deadlock
3321 xmit_acks.push_back(id);
3322 }
3323 }
3324 else
3325 {
3326 if (pid_ok)
3327 // remember tls_auth packet ID of ACK packet to prevent replay
3328 proto.ta_pid_recv.test_add(pid, t, true);
3329 else
3331 }
3332 return false;
3333 }
3334
3336 {
3337 Buffer &recv = *pkt.buf;
3338 const unsigned char *orig_data = recv.data();
3339 const size_t orig_size = recv.size();
3340
3341 // advance buffer past initial op byte
3342 recv.advance(1);
3343
3344 // get source PSID
3345 ProtoSessionID src_psid(recv);
3346
3347 // verify HMAC
3348 {
3349 recv.advance(proto.hmac_size);
3350 if (!proto.ta_hmac_recv->ovpn_hmac_cmp(orig_data,
3351 orig_size,
3355 {
3357 if (proto.is_tcp())
3359 return false;
3360 }
3361 }
3362
3363 // read tls_auth packet ID
3364 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
3365
3366 return decapsulate_post_process(pkt, src_psid, pid);
3367 }
3368
3370 {
3371 auto &recv = *pkt.buf;
3372 const unsigned char *orig_data = recv.data();
3373 const size_t orig_size = recv.size();
3374
3375 // advance buffer past initial op byte
3376 recv.advance(1);
3377 // get source PSID
3378 ProtoSessionID src_psid(recv);
3379 // get tls-crypt packet ID
3380 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
3381 // skip the hmac
3382 recv.advance(proto.hmac_size);
3383
3384 const size_t data_offset = TLSCryptContext::hmac_offset + proto.hmac_size;
3385 if (orig_size < data_offset)
3386 return false;
3387
3388 // decrypt payload
3389 proto.config->frame->prepare(Frame::DECRYPT_WORK, work);
3390
3391 const size_t decrypt_bytes = proto.tls_crypt_recv->decrypt(orig_data + TLSCryptContext::hmac_offset,
3392 work.data(),
3393 work.max_size(),
3394 recv.c_data(),
3395 recv.size());
3396 if (!decrypt_bytes)
3397 {
3399 if (proto.is_tcp())
3401 return false;
3402 }
3403
3404 work.inc_size(decrypt_bytes);
3405
3406 // verify HMAC
3407 if (!proto.tls_crypt_recv->hmac_cmp(orig_data,
3409 work.c_data(),
3410 work.size()))
3411 {
3413 if (proto.is_tcp())
3415 return false;
3416 }
3417
3418 // move the decrypted payload to 'recv', so that the processing of the
3419 // packet can continue
3420 recv.swap(work);
3421
3422 return decapsulate_post_process(pkt, src_psid, pid);
3423 }
3424
3426 {
3427 Buffer &recv = *pkt.buf;
3428
3429 // update our last-packet-received time
3431
3432 // advance buffer past initial op byte
3433 recv.advance(1);
3434
3435 // verify source PSID
3436 ProtoSessionID src_psid(recv);
3437 if (!verify_src_psid(src_psid))
3438 return false;
3439
3440 // process ACKs sent by peer
3441 if (ReliableAck::ack(rel_send, recv, true))
3442 {
3443 // make sure that our own PSID is in packet received from peer
3444 if (!verify_dest_psid(recv))
3445 return false;
3446 }
3447
3448 // for CONTROL packets only, not ACK
3449 if (pkt.opcode != ACK_V1)
3450 {
3451 // get message sequence number
3452 const id_t id = ReliableAck::read_id(recv);
3453
3454 // try to push message into reliable receive object
3455 const unsigned int rflags = rel_recv.receive(pkt, id);
3456
3457 // should we ACK packet back to sender?
3458 if (rflags & ReliableRecv::ACK_TO_SENDER)
3459 xmit_acks.push_back(id); // ACK packet to sender
3460
3461 // was packet accepted by reliable receive object?
3462 if (rflags & ReliableRecv::IN_WINDOW)
3463 return true;
3464 }
3465 return false;
3466 }
3467
3468 bool decapsulate(Packet &pkt) // called by ProtoStackBase
3469 {
3470 try
3471 {
3472 if (proto.is_server()
3474 && proto.config->tls_crypt_v2_enabled()
3476 {
3477 // setup key to be used to unwrap WKc upon client connection.
3478 // tls-crypt session key setup is postponed to reception of WKc
3479 // from client
3481
3483 proto.hmac_size = proto.config->tls_crypt_context->digest_size();
3484
3485 // init tls_crypt packet ID
3487 proto.ta_pid_recv.init("SSL-CC", 0, proto.stats);
3488 }
3489
3490 switch (proto.tls_wrap_mode)
3491 {
3492 case TLS_AUTH:
3493 return decapsulate_tls_auth(pkt);
3494 case TLS_CRYPT_V2:
3496 {
3497 // unwrap WKc and extract Kc (client key) from packet.
3498 // This way we can initialize the tls-crypt per-client contexts
3499 // (this happens on the server side only)
3500 OpenVPNStaticKey client_key;
3501 const Error::Type unwrap_wkc_result = unwrap_tls_crypt_wkc(*pkt.buf,
3502 *proto.config,
3505 switch (unwrap_wkc_result)
3506 {
3508 case Error::HMAC_ERROR:
3509 proto.stats->error(unwrap_wkc_result);
3510 if (proto.is_tcp())
3511 invalidate(unwrap_wkc_result);
3512 return false;
3514 proto.stats->error(unwrap_wkc_result);
3515 return false;
3516 case Error::SUCCESS:
3517 break;
3518 default:
3519 return false;
3520 }
3521
3522 // WKc has been authenticated: it contains the client key followed
3523 // by the optional metadata. Let's initialize the tls-crypt context
3524 // with the client key
3525 proto.reset_tls_crypt(*proto.config, proto.config->wrapped_tls_crypt_key);
3526 }
3527 // now that the tls-crypt contexts have been initialized it is
3528 // possible to proceed with the standard tls-crypt decapsulation
3529 /* no break */
3530 case TLS_CRYPT:
3531 return decapsulate_tls_crypt(pkt);
3532 case TLS_PLAIN:
3533 return decapsulate_tls_plain(pkt);
3534 }
3535 }
3536 catch (const BufferException &)
3537 {
3539 if (proto.is_tcp())
3541 }
3542 return false;
3543 }
3544
3545 // for debugging
3546 static const char *state_string(const int s)
3547 {
3548 switch (s)
3549 {
3550 case C_WAIT_RESET_ACK:
3551 return "C_WAIT_RESET_ACK";
3552 case C_WAIT_AUTH_ACK:
3553 return "C_WAIT_AUTH_ACK";
3554 case S_WAIT_RESET_ACK:
3555 return "S_WAIT_RESET_ACK";
3556 case S_WAIT_AUTH_ACK:
3557 return "S_WAIT_AUTH_ACK";
3558 case C_INITIAL:
3559 return "C_INITIAL";
3560 case C_WAIT_RESET:
3561 return "C_WAIT_RESET";
3562 case C_WAIT_AUTH:
3563 return "C_WAIT_AUTH";
3564 case S_INITIAL:
3565 return "S_INITIAL";
3566 case S_WAIT_RESET:
3567 return "S_WAIT_RESET";
3568 case S_WAIT_AUTH:
3569 return "S_WAIT_AUTH";
3570 case ACTIVE:
3571 return "ACTIVE";
3572 default:
3573 return "STATE_UNDEF";
3574 }
3575 }
3576
3577 // for debugging
3578 int seconds_until(const Time &next_time)
3579 {
3580 Time::Duration d = next_time - *now;
3581 if (d.is_infinite())
3582 return -1;
3583 return numeric_cast<int>(d.to_seconds());
3584 }
3585
3586 // BEGIN KeyContext data members
3587
3590 unsigned int key_id_;
3591 unsigned int crypto_flags;
3592 int remote_peer_id; // -1 to disable
3594 /* early negotiation enabled resending of wrapped tls-crypt-v2 client key
3595 * with third packet of the three-way handshake
3596 */
3597 bool resend_wkc = false;
3598 bool dirty;
3609 std::deque<BufferPtr> app_pre_write_queue;
3610 std::unique_ptr<DataChannelKey> data_channel_key;
3612 std::unique_ptr<DataLimit> data_limit;
3614
3615 // static member used by validate_tls_crypt()
3617 };
3618
3620 {
3621 public:
3622 PsidCookieHelper(unsigned int op_field)
3623 : op_code_(opcode_extract(op_field)), key_id_(key_id_extract(op_field))
3624 {
3625 }
3626
3628 {
3629 return key_id_ == 0 && (op_code_ == CONTROL_HARD_RESET_CLIENT_V2 || op_code_ == CONTROL_HARD_RESET_CLIENT_V3);
3630 }
3631
3633 bool is_tls_crypt_v2() const noexcept
3634 {
3635 return op_code_ == CONTROL_HARD_RESET_CLIENT_V3 || op_code_ == CONTROL_WKC_V1;
3636 }
3637
3639 bool supports_early_negotiation(const PacketIDControl &pidc) const noexcept
3640 {
3641 return (pidc.id & EARLY_NEG_MASK) == EARLY_NEG_START;
3642 }
3643
3645 {
3646 return key_id_ == 0 && (op_code_ == CONTROL_V1 || op_code_ == ACK_V1 || op_code_ == CONTROL_WKC_V1);
3647 }
3648
3650 static void prepend_TLV(Buffer &payload)
3651 {
3652 // The only supported TLV payload for now.
3653 const uint16_t type = htons(EARLY_NEG_FLAGS);
3654 const uint16_t len = htons(sizeof(uint16_t));
3655 const uint16_t flags = htons(EARLY_NEG_FLAG_RESEND_WKC);
3656
3657 payload.prepend(&flags, sizeof(flags));
3658 payload.prepend(&len, sizeof(len));
3659 payload.prepend(&type, sizeof(type));
3660 }
3661
3662 static unsigned char get_server_hard_reset_opfield()
3663 {
3664 return op_compose(CONTROL_HARD_RESET_SERVER_V2, 0);
3665 }
3666
3667 private:
3668 const unsigned int op_code_;
3669 const unsigned int key_id_;
3670 };
3671
3673 {
3674 public:
3675 IvProtoHelper(const OptionList &peer_info)
3676 : proto_field_(peer_info.get_num<unsigned int>("IV_PROTO", 1, 0))
3677 {
3678 }
3679
3681 {
3682 return proto_field_ & iv_proto_flag::IV_PROTO_TLS_KEY_EXPORT;
3683 }
3684
3686 {
3687 return proto_field_ & iv_proto_flag::IV_PROTO_AUTH_FAIL_TEMP;
3688 }
3689
3691 {
3692 return proto_field_ & iv_proto_flag::IV_PROTO_DATA_V2;
3693 }
3694
3696 {
3697 return proto_field_ & iv_proto_flag::IV_PROTO_AUTH_PENDING_KW;
3698 }
3699
3701 {
3702 return proto_field_ & iv_proto_flag::IV_PROTO_PUSH_UPDATE;
3703 }
3704
3706 {
3707 return proto_field_ & iv_proto_flag::IV_PROTO_REQUEST_PUSH;
3708 }
3709
3712 {
3713 return proto_field_ & iv_proto_flag::IV_PROTO_CC_EXIT_NOTIFY;
3714 }
3715
3718 {
3719 return proto_field_ & iv_proto_flag::IV_PROTO_DYN_TLS_CRYPT;
3720 }
3721
3724 {
3725 return proto_field_ & iv_proto_flag::IV_PROTO_DNS_OPTION_V2;
3726 }
3727
3728 private:
3729 unsigned int proto_field_;
3730 };
3731
3732 class TLSWrapPreValidate : public RC<thread_unsafe_refcount>
3733 {
3734 public:
3736
3737 virtual bool validate(const BufferAllocated &net_buf) = 0;
3738 };
3739
3740 // Validate the integrity of a packet, only considering tls-auth HMAC.
3742 {
3743 public:
3744 OPENVPN_SIMPLE_EXCEPTION(tls_auth_pre_validate);
3745
3746 TLSAuthPreValidate(const ProtoConfig &c, const bool server)
3747 {
3748 if (!c.tls_auth_enabled())
3749 throw tls_auth_pre_validate();
3750
3751 // save hard reset op we expect to receive from peer
3752 reset_op = server ? CONTROL_HARD_RESET_CLIENT_V2 : CONTROL_HARD_RESET_SERVER_V2;
3753
3754 // init OvpnHMACInstance
3755 ta_hmac_recv = c.tls_auth_context->new_obj();
3756
3757 // init tls_auth hmac
3758 if (c.key_direction >= 0)
3759 {
3760 // key-direction is 0 or 1
3761 const unsigned int key_dir = c.key_direction
3762 ? OpenVPNStaticKey::INVERSE
3763 : OpenVPNStaticKey::NORMAL;
3764 ta_hmac_recv->init(c.tls_auth_key.slice(OpenVPNStaticKey::HMAC | OpenVPNStaticKey::DECRYPT | key_dir));
3765 }
3766 else
3767 {
3768 // key-direction bidirectional mode
3769 ta_hmac_recv->init(c.tls_auth_key.slice(OpenVPNStaticKey::HMAC));
3770 }
3771 }
3772
3773 bool validate(const BufferAllocated &net_buf)
3774 {
3775 try
3776 {
3777 if (net_buf.empty())
3778 return false;
3779
3780 const unsigned int op = net_buf[0];
3781 if (opcode_extract(op) != reset_op || key_id_extract(op) != 0)
3782 return false;
3783
3784 return ta_hmac_recv->ovpn_hmac_cmp(net_buf.c_data(),
3785 net_buf.size(),
3786 OPCODE_SIZE + ProtoSessionID::SIZE,
3787 ta_hmac_recv->output_size(),
3788 PacketIDControl::size());
3789 }
3790 catch (const BufferException &)
3791 {
3792 }
3793
3794 return false;
3795 }
3796
3797 private:
3799 unsigned int reset_op;
3800 };
3801
3803 {
3804 public:
3805 OPENVPN_SIMPLE_EXCEPTION(tls_crypt_pre_validate);
3806
3807 TLSCryptPreValidate(const ProtoConfig &c, const bool server)
3808 {
3809 const bool tls_crypt_v2_enabled = c.tls_crypt_v2_enabled();
3810
3811 if (!c.tls_crypt_enabled() && !tls_crypt_v2_enabled)
3812 throw tls_crypt_pre_validate();
3813
3814 // save hard reset op we expect to receive from peer
3815 reset_op = CONTROL_HARD_RESET_SERVER_V2;
3816
3817 if (server)
3818 {
3819 // We can't pre-validate because we haven't extracted the server key from
3820 // the server key ID that's present in the client key yet.
3821 if (tls_crypt_v2_enabled && c.tls_crypt_v2_serverkey_id)
3822 {
3823 disabled = true;
3824 return;
3825 }
3826
3827 reset_op = tls_crypt_v2_enabled
3828 ? CONTROL_HARD_RESET_CLIENT_V3
3829 : CONTROL_HARD_RESET_CLIENT_V2;
3830 }
3831
3832 tls_crypt_recv = c.tls_crypt_context->new_obj_recv();
3833
3834 // static direction assignment - not user configurable
3835 const unsigned int key_dir = server ? OpenVPNStaticKey::NORMAL : OpenVPNStaticKey::INVERSE;
3836 tls_crypt_recv->init(c.ssl_factory->libctx(),
3837 c.tls_crypt_key.slice(OpenVPNStaticKey::HMAC | OpenVPNStaticKey::DECRYPT | key_dir),
3838 c.tls_crypt_key.slice(OpenVPNStaticKey::CIPHER | OpenVPNStaticKey::DECRYPT | key_dir));
3839
3840 // needed to create the decrypt buffer during validation
3841 frame = c.frame;
3842 }
3843
3844 bool validate(const BufferAllocated &net_buf)
3845 {
3846 if (disabled)
3847 return true;
3848
3849 try
3850 {
3851 if (net_buf.empty())
3852 return false;
3853
3854 const unsigned int op = net_buf[0];
3855 if (opcode_extract(op) != reset_op || key_id_extract(op) != 0)
3856 return false;
3857
3858 const size_t data_offset = TLSCryptContext::hmac_offset + tls_crypt_recv->output_hmac_size();
3859 if (net_buf.size() < data_offset)
3860 return false;
3861
3862 frame->prepare(Frame::DECRYPT_WORK, work);
3863
3864 // decrypt payload from 'net_buf' into 'work'
3865 const size_t decrypt_bytes = tls_crypt_recv->decrypt(net_buf.c_data() + TLSCryptContext::hmac_offset,
3866 work.data(),
3867 work.max_size(),
3868 net_buf.c_data() + data_offset,
3869 net_buf.size() - data_offset);
3870 if (!decrypt_bytes)
3871 return false;
3872
3873 work.inc_size(decrypt_bytes);
3874
3875 // verify HMAC
3876 return tls_crypt_recv->hmac_cmp(net_buf.c_data(),
3877 TLSCryptContext::hmac_offset,
3878 work.data(),
3879 work.size());
3880 }
3881 catch (const BufferException &)
3882 {
3883 }
3884 return false;
3885 }
3886
3887 protected:
3888 unsigned int reset_op;
3889
3890 private:
3894 bool disabled = false;
3895 };
3896
3897 OPENVPN_SIMPLE_EXCEPTION(select_key_context_error);
3898
3900 const ProtoConfig::Ptr &config_arg, // configuration
3901 const SessionStats::Ptr &stats_arg) // error stats
3902 : proto_callback(cb_arg),
3903 config(config_arg),
3904 stats(stats_arg),
3905 mode_(config_arg->ssl_factory->mode()),
3906 n_key_ids(0),
3907 now_(config_arg->now)
3908 {
3910 }
3911
3913 {
3914 // Prefer TLS auth as the default if both TLS crypt V2 and TLS auth
3915 // are enabled.
3916 if (c.tls_crypt_v2_enabled() && !c.tls_auth_enabled())
3917 {
3919
3920 // get HMAC size from Digest object
3922
3923 return;
3924 }
3925
3926 if (c.tls_crypt_enabled() && !c.tls_auth_enabled())
3927 {
3929
3930 // get HMAC size from Digest object
3932
3933 return;
3934 }
3935
3936 if (c.tls_auth_enabled())
3937 {
3939
3940 // get HMAC size from Digest object
3942
3943 return;
3944 }
3945
3947 hmac_size = 0;
3948 }
3949
3950 uint32_t get_tls_warnings() const
3951 {
3952 if (primary)
3953 return primary->get_tls_warnings();
3954
3955 OPENVPN_LOG("TLS: primary key context uninitialized. Can't retrieve TLS warnings");
3956 return 0;
3957 }
3958
3959 bool uses_bs64_cipher() const
3960 {
3961 return is_bs64_cipher(conf().dc.cipher());
3962 }
3963
3965 {
3968
3969 // static direction assignment - not user configurable
3971
3978 }
3979
3981 {
3982 OpenVPNStaticKey dyn_key;
3983 key_ctx->export_key_material(dyn_key, "EXPORTER-OpenVPN-dynamic-tls-crypt");
3984
3985 if (c.tls_auth_enabled())
3986 dyn_key.XOR(c.tls_auth_key);
3987 else if (c.tls_crypt_enabled() || c.tls_crypt_v2_enabled())
3988 dyn_key.XOR(c.tls_crypt_key);
3989
3991
3992 // get HMAC size from Digest object
3994
3995 ta_pid_send.init();
3996 ta_pid_recv.init("SSL-CC", 0, stats);
3997
3998 reset_tls_crypt(c, dyn_key);
3999 }
4000
4002 {
4003 // It is possible that the PSID/HMAC cookie logic has already set the TLS crypt V2
4004 // keys up, during the processing of the second packet. If so, just use them.
4006 {
4008 }
4009 else
4010 {
4011 // tls-crypt session key is derived later from WKc received from the client
4014
4015 // server context is used only to process incoming WKc's
4017
4019 {
4020 // the server key is composed by one key set only, therefore direction and
4021 // mode should not be specified when slicing
4025 }
4026 }
4027
4029 }
4030
4042 void reset(const ProtoSessionID cookie_psid = ProtoSessionID())
4043 {
4044 const ProtoConfig &c = *config;
4045
4046 // defer data channel initialization until after client options pull?
4048
4049 // clear key contexts
4050 reset_all();
4051
4052 // start with key ID 0
4053 upcoming_key_id = 0;
4054
4055 unsigned int key_dir;
4056
4057 // tls-auth initialization
4059 switch (tls_wrap_mode)
4060 {
4061 case TLS_CRYPT:
4063 // init tls_crypt packet ID
4064 ta_pid_send.init();
4065 ta_pid_recv.init("SSL-CC", 0, stats);
4066 break;
4067 case TLS_CRYPT_V2:
4068 if (is_server())
4069 // setup key to be used to unwrap WKc upon client connection.
4070 // tls-crypt session key setup is postponed to reception of WKc
4071 // from client
4073 else
4077 // init tls_crypt packet ID
4079 ta_pid_recv.init("SSL-CC", 0, stats);
4080 break;
4081 case TLS_AUTH:
4082 // init OvpnHMACInstance
4085
4086 // init tls_auth hmac
4087 if (c.key_direction >= 0)
4088 {
4089 // key-direction is 0 or 1
4093 }
4094 else
4095 {
4096 // key-direction bidirectional mode
4099 }
4100
4110 ta_pid_send.init(cookie_psid.defined() ? 1 : 0);
4111 ta_pid_recv.init("SSL-CC", 0, stats);
4112 break;
4113 case TLS_PLAIN:
4114 break;
4115 }
4116
4117 // initialize proto session ID
4118 if (cookie_psid.defined())
4119 psid_self = cookie_psid;
4120 else
4122 psid_peer.reset();
4123
4124 // initialize key contexts
4125 primary.reset(new KeyContext(*this, is_client(), cookie_psid.defined()));
4126 OVPN_LOG_VERBOSE(debug_prefix() << " New KeyContext PRIMARY id=" << primary->key_id());
4127
4128 // initialize keepalive timers
4129 keepalive_expire = Time::infinite(); // initially disabled
4130 update_last_sent(); // set timer for initial keepalive send
4131 }
4132
4133 void set_protocol(const Protocol &p)
4134 {
4135 config->set_protocol(p);
4136 if (primary)
4137 primary->set_protocol(p);
4138 if (secondary)
4139 secondary->set_protocol(p);
4140 }
4141
4142 // Free up space when parent object has been halted but
4143 // object destruction is not immediately scheduled.
4145 {
4146 reset_all();
4147 }
4148
4149 // Is primary key defined
4151 {
4152 return bool(primary);
4153 }
4154
4155 virtual ~ProtoContext() = default;
4156
4157 // return the PacketType of an incoming network packet
4159 {
4160 return PacketType(buf, *this);
4161 }
4162
4171 void start(const ProtoSessionID cookie_psid = ProtoSessionID())
4172 {
4173 if (!primary)
4174 throw proto_error("start: no primary key");
4175 primary->start(cookie_psid);
4176 update_last_received(); // set an upper bound on when we expect a response
4177 }
4178
4179 // trigger a protocol renegotiation
4181 {
4182 // set up dynamic tls-crypt keys when the first rekeying happens
4183 // primary key_id 0 indicates that it is the first rekey
4184 if (conf().dynamic_tls_crypt_enabled() && primary && primary->key_id() == 0)
4186
4187 // initialize secondary key context
4188 new_secondary_key(true);
4189 secondary->start();
4190 }
4191
4192 // Should be called at the end of sequence of send/recv
4193 // operations on underlying protocol object.
4194 // If control_channel is true, do a full flush.
4195 // If control_channel is false, optimize flush for data
4196 // channel only.
4197 void flush(const bool control_channel)
4198 {
4199 if (control_channel || process_events())
4200 {
4201 do
4202 {
4203 if (primary)
4204 primary->flush();
4205 if (secondary)
4206 secondary->flush();
4207 } while (process_events());
4208 }
4209 }
4210
4211 // Perform various time-based housekeeping tasks such as retransmiting
4212 // unacknowleged packets as part of the reliability layer and testing
4213 // for keepalive timouts.
4214 // Should be called at the time returned by next_housekeeping.
4216 {
4217 // handle control channel retransmissions on primary
4218 if (primary)
4219 primary->retransmit();
4220
4221 // handle control channel retransmissions on secondary
4222 if (secondary)
4223 secondary->retransmit();
4224
4225 // handle possible events
4226 flush(false);
4227
4228 // handle keepalive/expiration
4230 }
4231
4232 // When should we next call housekeeping?
4233 // Will return a time value for immediate execution
4234 // if session has been invalidated.
4236 {
4237 if (!invalidated())
4238 {
4240 if (primary)
4241 ret.min(primary->next_retransmit());
4242 if (secondary)
4243 ret.min(secondary->next_retransmit());
4244 ret.min(keepalive_xmit);
4245 ret.min(keepalive_expire);
4246 return ret;
4247 }
4248 return Time();
4249 }
4250
4251 // send app-level cleartext to remote peer
4252
4254 {
4255 select_control_send_context().app_send(std::move(app_bp));
4256 }
4257
4259 {
4260 control_send(BufferAllocatedRc::Create(std::move(app_buf)));
4261 }
4262
4263 // validate a control channel network packet
4264 bool control_net_validate(const PacketType &type, const Buffer &net_buf)
4265 {
4266 return type.is_defined() && KeyContext::validate(net_buf, *this, now_);
4267 }
4268
4269 // pass received control channel network packets (ciphertext) into protocol object
4270 bool control_net_recv(const PacketType &type, BufferPtr &&net_bp)
4271 {
4272 Packet pkt(std::move(net_bp), type.opcode);
4273 if (type.is_soft_reset() && !renegotiate_request(pkt))
4274 return false;
4275 return select_key_context(type, true).net_recv(std::move(pkt));
4276 }
4277
4285 bool control_net_recv(const PacketType &type, BufferAllocated &&net_buf)
4286 {
4287 return control_net_recv(type, BufferAllocatedRc::Create(std::move(net_buf)));
4288 }
4289
4290 // encrypt a data channel packet using primary KeyContext
4292 {
4293 OVPN_LOG_DEBUG(debug_prefix() << " DATA ENCRYPT size=" << in_out.size());
4294 if (!primary)
4295 throw proto_error("data_encrypt: no primary key");
4296 primary->encrypt(in_out);
4297 }
4298
4299 // decrypt a data channel packet (automatically select primary
4300 // or secondary KeyContext based on packet content)
4301 bool data_decrypt(const PacketType &type, BufferAllocated &in_out)
4302 {
4303 bool ret = false;
4304
4305 OVPN_LOG_DEBUG(debug_prefix() << " DATA DECRYPT key_id=" << select_key_context(type, false).key_id() << " size=" << in_out.size());
4306
4307 select_key_context(type, false).decrypt(in_out);
4308
4309 // update time of most recent packet received
4310 if (!in_out.empty())
4311 {
4313 ret = true;
4314 }
4315
4316 // discard keepalive packets
4317 if (proto_context_private::is_keepalive(in_out))
4318 {
4319 in_out.reset_size();
4320 }
4321
4322 return ret;
4323 }
4324
4325 // enter disconnected state
4326 void disconnect(const Error::Type reason)
4327 {
4328 if (primary)
4329 primary->invalidate(reason);
4330 if (secondary)
4331 secondary->invalidate(reason);
4332 }
4333
4334 // normally used by UDP clients to tell the server that
4335 // they are disconnecting
4337 {
4338#ifndef OPENVPN_DISABLE_EXPLICIT_EXIT // explicit exit should always be enabled in production
4339 if (!is_client() || !is_udp() || !primary)
4340 {
4341 return;
4342 }
4343
4344 if (config->cc_exit_notify)
4345 {
4346 write_control_string(std::string("EXIT"));
4347 primary->flush();
4348 }
4349 else
4350 {
4351 primary->send_explicit_exit_notify();
4352 }
4353#endif // OPENVPN_DISABLE_EXPLICIT_EXIT
4354 }
4355
4356 // should be called after a successful network packet transmit
4358 {
4359 keepalive_xmit = *now_ + config->keepalive_ping;
4360 }
4361
4362 // Can we call data_encrypt or data_decrypt yet?
4363 // Returns true if primary data channel is in ACTIVE state.
4365 {
4366 return primary && primary->data_channel_ready();
4367 }
4368
4369 // total number of SSL/TLS negotiations during lifetime of ProtoContext object
4370 unsigned int negotiations() const
4371 {
4372 return n_key_ids;
4373 }
4374
4375 // worst-case handshake time
4376 const Time::Duration &slowest_handshake()
4377 {
4378 return slowest_handshake_;
4379 }
4380
4381 // was primary context invalidated by an exception?
4382 bool invalidated() const
4383 {
4384 return primary && primary->invalidated();
4385 }
4386
4387 // reason for invalidation if invalidated() above returns true
4389 {
4390 return primary->invalidation_reason();
4391 }
4392
4393 // Do late initialization of data channel, for example
4394 // on client after server push, or on server after client
4395 // capabilities are known.
4397 {
4398 dc_deferred = false;
4399
4400 // initialize data channel (crypto & compression)
4401 if (primary)
4402 primary->init_data_channel();
4403 if (secondary)
4404 secondary->init_data_channel();
4405 }
4406
4407 // Call on client with server-pushed options
4409 {
4410 // modify config with pushed options
4411 config->process_push(opt, pco);
4412
4413 // in case keepalive parms were modified by push
4415 }
4416
4417 // Return the current transport alignment adjustment
4418 size_t align_adjust_hint() const
4419 {
4420 return config->enable_op32 ? 0 : 1;
4421 }
4422
4423 // Return true if keepalive parameter(s) are enabled
4425 {
4426 return config->keepalive_ping.enabled()
4427 || config->keepalive_timeout.enabled();
4428 }
4429
4430 // Disable keepalive for rest of session,
4431 // but return the previous keepalive parameters.
4432 void disable_keepalive(unsigned int &keepalive_ping,
4433 unsigned int &keepalive_timeout)
4434 {
4435 keepalive_ping = config->keepalive_ping.enabled()
4436 ? clamp_to_typerange<std::remove_reference_t<decltype(keepalive_ping)>>(config->keepalive_ping.to_seconds())
4437 : 0;
4438 keepalive_timeout = config->keepalive_timeout.enabled()
4439 ? clamp_to_typerange<std::remove_reference_t<decltype(keepalive_timeout)>>(config->keepalive_timeout.to_seconds())
4440 : 0;
4441 config->keepalive_ping = Time::Duration::infinite();
4442 config->keepalive_timeout = Time::Duration::infinite();
4443 config->keepalive_timeout_early = Time::Duration::infinite();
4445 }
4446
4447 // Notify our component KeyContext when per-key Data Limits have been reached
4448 void data_limit_notify(const unsigned int key_id,
4449 const DataLimit::Mode cdl_mode,
4450 const DataLimit::State cdl_status)
4451 {
4452 if (primary && key_id == primary->key_id())
4453 primary->data_limit_notify(cdl_mode, cdl_status);
4454 else if (secondary && key_id == secondary->key_id())
4455 secondary->data_limit_notify(cdl_mode, cdl_status);
4456 }
4457
4458 // access the data channel settings
4460 {
4461 return config->dc;
4462 }
4463
4464 // reset the data channel factory
4466 {
4467 config->dc.reset();
4468 }
4469
4470 // set the local peer ID (or -1 to disable)
4471 void set_local_peer_id(const int local_peer_id)
4472 {
4473 config->local_peer_id = local_peer_id;
4474 }
4475
4476 // current time
4477 const Time &now() const
4478 {
4479 return *now_;
4480 }
4482 {
4483 now_->update();
4484 }
4485
4486 // frame
4487 const Frame &frame() const
4488 {
4489 return *config->frame;
4490 }
4491 const Frame::Ptr &frameptr() const
4492 {
4493 return config->frame;
4494 }
4495
4496 // client or server?
4497 const Mode &mode() const
4498 {
4499 return mode_;
4500 }
4501 bool is_server() const
4502 {
4503 return mode_.is_server();
4504 }
4505 bool is_client() const
4506 {
4507 return mode_.is_client();
4508 }
4509
4510 // tcp/udp mode
4511 bool is_tcp()
4512 {
4513 return config->protocol.is_tcp();
4514 }
4515 bool is_udp()
4516 {
4517 return config->protocol.is_udp();
4518 }
4519
4520 // configuration
4521 const ProtoConfig &conf() const
4522 {
4523 return *config;
4524 }
4526 {
4527 return *config;
4528 }
4530 {
4531 return config;
4532 }
4533
4534 // stats
4536 {
4537 return *stats;
4538 }
4539
4540 // debugging
4542 {
4543 return primary_state() == C_WAIT_RESET_ACK;
4544 }
4545
4546 protected:
4547 int primary_state() const
4548 {
4549 if (primary)
4550 return primary->get_state();
4551 return STATE_UNDEF;
4552 }
4553
4554 private:
4555 // TLS wrapping mode for the control channel
4563
4564 static constexpr PacketIDControl::id_t EARLY_NEG_START = 0x0f000000;
4565 static constexpr PacketIDControl::id_t EARLY_NEG_MASK = 0xff000000;
4566
4568 {
4569 if (primary)
4571 primary.reset();
4572 secondary.reset();
4573 }
4574
4575 // Called on client to request username/password credentials.
4576 // delegated to the callback/parent
4578 {
4580 }
4581
4583 {
4584 keepalive_expire = *now_ + (data_channel_ready() ? config->keepalive_timeout : config->keepalive_timeout_early);
4585 }
4586
4587 void net_send(const unsigned int key_id, const Packet &net_pkt)
4588 {
4590 }
4591
4592 void app_recv(const unsigned int key_id, BufferPtr &&to_app_buf)
4593 {
4595 }
4596
4597 // we're getting a request from peer to renegotiate.
4599 {
4600 // set up dynamic tls-crypt keys when the first rekeying happens
4601 // primary key_id 0 indicates that it is the first rekey
4602 if (conf().dynamic_tls_crypt_enabled() && primary && primary->key_id() == 0)
4604
4605 if (KeyContext::validate(pkt.buffer(), *this, now_))
4606 {
4607 new_secondary_key(false);
4608 return true;
4609 }
4610 return false;
4611 }
4612
4613 // select a KeyContext (primary or secondary) for received network packets
4614 KeyContext &select_key_context(const PacketType &type, const bool control)
4615 {
4617 if (!control)
4618 {
4619 if (flags == (PacketType::DEFINED) && primary)
4620 return *primary;
4622 return *secondary;
4623 }
4624 else
4625 {
4627 {
4628 return *primary;
4629 }
4631 && secondary)
4632 {
4633 return *secondary;
4634 }
4635 }
4636 throw select_key_context_error();
4637 }
4638
4639 // Select a KeyContext (primary or secondary) for control channel sends.
4640 // Even after new key context goes active, we still wait for
4641 // KEV_BECOME_PRIMARY event (controlled by the become_primary duration
4642 // in Config) before we use it for app-level control-channel
4643 // transmissions. Simulations have found this method to be more reliable
4644 // than the immediate rollover practiced by OpenVPN 2.x.
4646 {
4647 OVPN_LOG_VERBOSE(debug_prefix() << " CONTROL SEND");
4648 if (!primary)
4649 throw proto_error("select_control_send_context: no primary key");
4650 return *primary;
4651 }
4652
4653 // Possibly send a keepalive message, and check for expiration
4654 // of session due to lack of received packets from peer.
4656 {
4657 const Time now = *now_;
4658
4659 // check for keepalive timeouts
4660 if (now >= keepalive_xmit && primary)
4661 {
4662 primary->send_keepalive();
4664 }
4665 if (now >= keepalive_expire)
4666 {
4667 // no contact with peer, disconnect
4670 }
4671 }
4672
4673 // Process KEV_x events
4674 // Return true if any events were processed.
4676 {
4677 bool did_work = false;
4678
4679 // primary
4680 if (primary && primary->event_pending())
4681 {
4683 did_work = true;
4684 }
4685
4686 // secondary
4687 if (secondary && secondary->event_pending())
4688 {
4690 did_work = true;
4691 }
4692
4693 return did_work;
4694 }
4695
4696 // Create a new secondary key.
4697 // initiator --
4698 // false : remote renegotiation request
4699 // true : local renegotiation request
4700 void new_secondary_key(const bool initiator)
4701 {
4702 // Create the secondary
4703 secondary.reset(new KeyContext(*this, initiator));
4705 << " New KeyContext SECONDARY id=" << secondary->key_id()
4706 << (initiator ? " local-triggered" : " remote-triggered"));
4707 }
4708
4709 // Promote a newly renegotiated KeyContext to primary status.
4710 // This is usually triggered by become_primary variable (Time::Duration)
4711 // in Config.
4713 {
4715 if (primary)
4717 if (secondary)
4718 secondary->prepare_expire();
4719 OVPN_LOG_VERBOSE(debug_prefix() << " PRIMARY_SECONDARY_SWAP");
4720 }
4721
4723 {
4724 const KeyContext::EventType ev = primary->get_event();
4725 if (ev != KeyContext::KEV_NONE)
4726 {
4727 primary->reset_event();
4728 switch (ev)
4729 {
4731 OVPN_LOG_VERBOSE(debug_prefix() << " SESSION_ACTIVE");
4733 proto_callback->active(true);
4734 break;
4737 renegotiate();
4738 break;
4740 if (secondary && !secondary->invalidated())
4742 else
4743 {
4745 // primary context expired and no secondary context available
4747 }
4748 break;
4751 // primary negotiation failed
4753 break;
4754 default:
4755 break;
4756 }
4757 }
4758 primary->set_next_event_if_unspecified();
4759 }
4760
4762 {
4763 const KeyContext::EventType ev = secondary->get_event();
4764 if (ev != KeyContext::KEV_NONE)
4765 {
4766 secondary->reset_event();
4767 switch (ev)
4768 {
4771 if (primary)
4772 primary->prepare_expire();
4773 proto_callback->active(false);
4774 break;
4776 if (!secondary->invalidated())
4778 break;
4781 secondary.reset();
4782 break;
4784 if (primary)
4786 secondary->become_primary_time());
4787 break;
4790 [[fallthrough]];
4793 renegotiate();
4794 break;
4795 default:
4796 break;
4797 }
4798 }
4799 if (secondary)
4800 secondary->set_next_event_if_unspecified();
4801 }
4802
4803 std::string debug_prefix()
4804 {
4805 std::string ret = openvpn::to_string(now_->raw());
4806 ret += is_server() ? " SERVER[" : " CLIENT[";
4807 if (primary)
4808 ret += openvpn::to_string(primary->key_id());
4809 if (secondary)
4810 {
4811 ret += '/';
4812 ret += openvpn::to_string(secondary->key_id());
4813 }
4814 ret += ']';
4815 return ret;
4816 }
4817
4818 // key_id starts at 0, increments to KEY_ID_MASK, then recycles back to 1.
4819 // Therefore, if key_id is 0, it is the first key.
4820 unsigned int next_key_id()
4821 {
4822 ++n_key_ids;
4823 unsigned int ret = upcoming_key_id;
4824 if ((upcoming_key_id = (upcoming_key_id + 1) & KEY_ID_MASK) == 0)
4825 upcoming_key_id = 1;
4826 return ret;
4827 }
4828
4829 // call whenever keepalive parms are modified,
4830 // to reset timers
4832 {
4834
4835 // For keepalive_xmit timer, don't reschedule current cycle
4836 // unless it would fire earlier. Subsequent cycles will
4837 // time according to new keepalive_ping value.
4838 const Time kx = *now_ + config->keepalive_ping;
4839 if (kx < keepalive_xmit)
4840 keepalive_xmit = kx;
4841 }
4842
4844 {
4845 if (!config->wkc.defined())
4846 throw proto_error("Client Key Wrapper undefined");
4847 dst.append(config->wkc);
4848 }
4849
4850 // BEGIN ProtoContext data members
4851
4858
4861
4864 Mode mode_; // client or server
4865 unsigned int upcoming_key_id = 0;
4866 unsigned int n_key_ids;
4867
4868 TimePtr now_; // pointer to current time (a clone of config->now)
4869 Time keepalive_xmit; // time in future when we will transmit a keepalive (subject to continuous change)
4870 Time keepalive_expire; // time in future when we must have received a packet from peer or we will timeout session
4871
4872 Time::Duration slowest_handshake_; // longest time to reach a successful handshake
4873
4876
4879
4882
4885
4888
4891 bool dc_deferred = false;
4892
4893 // END ProtoContext data members
4894};
4895
4896} // namespace openvpn
4897
4898#endif // OPENVPN_SSL_PROTO_H
#define OPENVPN_BS64_DATA_LIMIT
void swap(BufferAllocatedType< T_ > &other)
Swaps the contents of this BufferAllocatedType object with another BufferAllocatedType object.
Definition buffer.hpp:1796
bool advance(size_t size)
void put(BufferPtr bp)
report various types of exceptions or errors that may occur when working with buffers
Definition buffer.hpp:115
static Type parse_method(const std::string &method)
Definition compress.hpp:467
const char * options_string() const
Definition compress.hpp:391
unsigned int extra_payload_bytes() const
Definition compress.hpp:186
const char * str() const
Definition compress.hpp:411
static Type stub(const Type t)
Definition compress.hpp:488
const char * peer_info_string() const
Definition compress.hpp:278
static bool is_any_stub(const Type t)
Definition compress.hpp:507
virtual void decompress(BufferAllocated &buf)=0
virtual void compress(BufferAllocated &buf, const bool hint)=0
const T * c_data() const
Returns a const pointer to the start of the buffer.
Definition buffer.hpp:1193
T * prepend_alloc(const size_t size)
Allocate space for prepending data to the buffer.
Definition buffer.hpp:1594
void append(const B &other)
Append data from another buffer to this buffer.
Definition buffer.hpp:1623
void inc_size(const size_t delta)
Increment the size of the array (usually used in a similar context to set_size such as after mutable_...
Definition buffer.hpp:1389
size_t max_size() const
Return the maximum allowable size value in T objects given the current offset (without considering re...
Definition buffer.hpp:1374
void prepend(const T *data, const size_t size)
Prepend data to the buffer.
Definition buffer.hpp:1572
size_t size() const
Returns the size of the buffer in T objects.
Definition buffer.hpp:1241
T * data()
Get a mutable pointer to the start of the array.
Definition buffer.hpp:1447
void advance(const size_t delta)
Advances the buffer by the specified delta.
Definition buffer.hpp:1276
bool empty() const
Returns true if the buffer is empty.
Definition buffer.hpp:1235
void write(const T *data, const size_t size)
Write data to the buffer.
Definition buffer.hpp:1560
auto * read_alloc(const size_t size)
Allocate memory and read data from the buffer into the allocated memory.
Definition buffer.hpp:1342
T pop_front()
Removes and returns the first element from the buffer.
Definition buffer.hpp:1255
void push_front(const T &value)
Append a T object to the array, with possible resize.
Definition buffer.hpp:1487
void set_size(const size_t size)
After an external method, operating on the array as a mutable unsigned char buffer,...
Definition buffer.hpp:1381
void null_terminate()
Null-terminate the array.
Definition buffer.hpp:1505
void reset_size()
Resets the size of the buffer to zero.
Definition buffer.hpp:1169
void read(NCT *data, const size_t size)
Read data from the buffer into the specified memory location.
Definition buffer.hpp:1330
const char * name() const
virtual CryptoDCInstance::Ptr new_obj(const unsigned int key_id)=0
virtual size_t encap_overhead() const =0
virtual void explicit_exit_notify()
Definition cryptodc.hpp:78
virtual void init_pid(const char *recv_name, const int recv_unit, const SessionStats::Ptr &recv_stats_arg)=0
virtual unsigned int defined() const =0
virtual void init_remote_peer_id(const int remote_peer_id)
Definition cryptodc.hpp:72
virtual void init_hmac(StaticKey &&encrypt_key, StaticKey &&decrypt_key)=0
virtual void rekey(const RekeyType type)=0
virtual bool encrypt(BufferAllocated &buf, const unsigned char *op32)=0
virtual Error::Type decrypt(BufferAllocated &buf, std::time_t now, const unsigned char *op32)=0
virtual bool consider_compression(const CompressContext &comp_ctx)=0
virtual void init_cipher(StaticKey &&encrypt_key, StaticKey &&decrypt_key)=0
CryptoAlgs::Type cipher() const
Definition cryptodc.hpp:118
CryptoAlgs::KeyDerivation key_derivation() const
Definition cryptodc.hpp:145
CryptoAlgs::Type digest() const
Definition cryptodc.hpp:130
void set_key_derivation(CryptoAlgs::KeyDerivation method)
Definition cryptodc.hpp:140
CryptoDCContext & context()
Definition cryptodc.hpp:230
void set_use_epoch_keys(bool at_the_end)
Definition cryptodc.hpp:221
void set_digest(const CryptoAlgs::Type new_digest)
Definition cryptodc.hpp:212
void set_cipher(const CryptoAlgs::Type new_cipher)
Definition cryptodc.hpp:203
static const char * mode_str(const Mode m)
Definition datalimit.hpp:67
static const char * state_str(const State s)
Definition datalimit.hpp:80
unsigned int size_type
Definition datalimit.hpp:25
@ WRITE_SSL_CLEARTEXT
Definition frame.hpp:44
size_t prepare(const unsigned int context, Buffer &buf) const
Definition frame.hpp:263
const char * dev_type() const
Definition layer.hpp:48
static void mssfix(BufferAllocated &buf, uint16_t mss_fix)
Definition mssfix.hpp:31
bool is_server() const
Definition mode.hpp:36
bool is_client() const
Definition mode.hpp:40
const char * str() const
Definition mode.hpp:55
void XOR(const OpenVPNStaticKey &other)
unsigned char * raw_alloc()
void parse(const std::string &key_text)
StaticKey slice(unsigned int key_specifier) const
const Option * get_ptr(const std::string &name) const
Definition options.hpp:1174
bool exists(const std::string &name) const
Definition options.hpp:1308
const std::string & get(const size_t index, const size_t max_len) const
Definition options.hpp:184
T get_num(const size_t idx) const
Definition options.hpp:216
size_t size() const
Definition options.hpp:320
void min_args(const size_t n) const
Definition options.hpp:128
const std::string & ref(const size_t i) const
Definition options.hpp:346
virtual OvpnHMACInstance::Ptr new_obj()=0
virtual size_t size() const =0
virtual OvpnHMACContext::Ptr new_obj(const CryptoAlgs::Type digest_type)=0
virtual void ovpn_hmac_gen(unsigned char *data, const size_t data_size, const size_t l1, const size_t l2, const size_t l3)=0
virtual void init(const StaticKey &key)=0
virtual bool ovpn_hmac_cmp(const unsigned char *data, const size_t data_size, const size_t l1, const size_t l2, const size_t l3)=0
void init(const char *name_arg, const int unit_arg, const SessionStats::Ptr &stats_arg)
PacketIDControl read_next(Buffer &buf) const
bool test_add(const PacketIDControl &pin, const PacketIDControl::time_t now, const bool mod)
void init(PacketIDControl::id_t start_at=0)
void write_next(Buffer &buf, const bool prepend, const PacketIDControl::time_t now)
virtual void control_net_send(const Buffer &net_buf)=0
static void write_empty_string(Buffer &buf)
Definition proto.hpp:190
virtual void client_auth(Buffer &buf)
Definition proto.hpp:171
virtual void control_recv(BufferPtr &&app_bp)=0
virtual void server_auth(const std::string &username, const SafeString &password, const std::string &peer_info, const AuthCert::Ptr &auth_cert)
Definition proto.hpp:179
virtual void active(bool primary)=0
Called when KeyContext transitions to ACTIVE state.
virtual ~ProtoContextCallbackInterface()=default
bool client_supports_dns_option() const
Checks if the client can handle dns (as opposed to dhcp-option).
Definition proto.hpp:3723
bool client_supports_auth_pending_kwargs() const
Definition proto.hpp:3695
IvProtoHelper(const OptionList &peer_info)
Definition proto.hpp:3675
bool client_supports_temp_auth_failed() const
Definition proto.hpp:3685
bool client_supports_exit_notify() const
Checks if the client is able to send an explicit EXIT message before exiting.
Definition proto.hpp:3711
bool client_supports_dynamic_tls_crypt() const
Checks if the client can handle dynamic TLS-crypt.
Definition proto.hpp:3717
void encapsulate(id_t id, Packet &pkt)
Definition proto.hpp:3238
static const char * event_type_string(const EventType et)
Definition proto.hpp:1775
bool decapsulate_post_process(Packet &pkt, ProtoSessionID &src_psid, const PacketIDControl pid)
Definition proto.hpp:3268
void kev_error(const EventType ev, const Error::Type reason)
Definition proto.hpp:2849
static BufferAllocated static_work
Definition proto.hpp:3616
static bool validate(const Buffer &net_buf, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2136
void set_protocol(const Protocol &p)
Definition proto.hpp:1835
void prepend_dest_psid_and_acks(Buffer &buf, unsigned int opcode)
Definition proto.hpp:3097
TLSPRFInstance::Ptr tlsprf
Definition proto.hpp:3603
bool net_recv(Packet &&pkt)
Definition proto.hpp:1920
void set_state(const int newstate)
Definition proto.hpp:2697
std::deque< BufferPtr > app_pre_write_queue
Definition proto.hpp:3609
void recv_auth(BufferPtr buf)
Definition proto.hpp:3037
bool decapsulate_tls_plain(Packet &pkt)
Definition proto.hpp:3425
static bool validate_tls_plain(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2627
void app_recv(BufferPtr &&to_app_buf)
Definition proto.hpp:2944
void net_send(const Packet &net_pkt, const Base::NetSendType nstype)
Definition proto.hpp:2977
void app_send(BufferPtr &&bp)
Definition proto.hpp:1908
void set_event(const EventType current)
Definition proto.hpp:2705
void raw_recv(Packet &&raw_pkt)
Definition proto.hpp:2923
void gen_head(const unsigned int opcode, BufferAllocated &buf)
Definition proto.hpp:3221
std::unique_ptr< DataLimit > data_limit
Definition proto.hpp:3612
void prepare_expire(const EventType current_ev=KeyContext::KEV_NONE)
Definition proto.hpp:1999
void decrypt(BufferAllocated &buf)
Definition proto.hpp:1949
void send_data_channel_message(const unsigned char *data, const size_t size)
Definition proto.hpp:2114
void gen_head_tls_crypt(const unsigned int opcode, BufferAllocated &buf)
Definition proto.hpp:3169
void gen_head_tls_plain(const unsigned int opcode, Buffer &buf)
Definition proto.hpp:3213
void encrypt(BufferAllocated &buf)
Definition proto.hpp:1928
bool recv_auth_complete(BufferComplete &bc) const
Definition proto.hpp:3054
bool verify_src_psid(const ProtoSessionID &src_psid)
Definition proto.hpp:3115
void generate_ack(Packet &pkt)
Definition proto.hpp:3258
bool verify_dest_psid(Buffer &buf)
Definition proto.hpp:3134
Error::Type invalidation_reason() const
Definition proto.hpp:2055
bool parse_early_negotiation(const Packet &pkt)
Definition proto.hpp:2879
void calculate_mssfix(ProtoConfig &c)
Definition proto.hpp:2197
bool decapsulate_tls_crypt(Packet &pkt)
Definition proto.hpp:3369
static bool validate_tls_crypt(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2558
void start(const ProtoSessionID cookie_psid=ProtoSessionID())
Initialize the state machine and start protocol negotiation.
Definition proto.hpp:1852
void invalidate(const Error::Type reason)
Definition proto.hpp:1879
uint32_t get_tls_warnings() const
Definition proto.hpp:1840
static Error::Type unwrap_tls_crypt_wkc(Buffer &recv, ProtoConfig &proto_config, TLSCryptInstance &tls_crypt_server, TLSCryptMetadata::Ptr tls_crypt_metadata=nullptr)
Extract and process the TLS crypt WKc information.
Definition proto.hpp:2371
void gen_head_tls_auth(const unsigned int opcode, Buffer &buf)
Definition proto.hpp:3147
void app_send_validate(BufferPtr &&bp)
Definition proto.hpp:1900
OPENVPN_SIMPLE_EXCEPTION(tls_crypt_unwrap_wkc_error)
void data_limit_event(const DataLimit::Mode mode, const DataLimit::State state)
Definition proto.hpp:2770
CryptoDCInstance::Ptr crypto
Definition proto.hpp:3602
KeyContext(ProtoContext &p, const bool initiator, bool psid_cookie_mode=false)
Definition proto.hpp:1802
unsigned int key_id() const
Definition proto.hpp:2061
static bool validate_tls_auth(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2510
unsigned int initial_op(const bool sender, const bool tls_crypt_v2) const
Definition proto.hpp:2856
int seconds_until(const Time &next_time)
Definition proto.hpp:3578
static const char * state_string(const int s)
Definition proto.hpp:3546
void data_limit_notify(const DataLimit::Mode cdl_mode, const DataLimit::State cdl_status)
Definition proto.hpp:2348
bool do_encrypt(BufferAllocated &buf, const bool compress_hint)
Definition proto.hpp:2647
std::unique_ptr< DataChannelKey > data_channel_key
Definition proto.hpp:3610
bool data_limit_add(const DataLimit::Mode mode, const size_t size)
Definition proto.hpp:2759
void set_event(const EventType current, const EventType next, const Time &next_time)
Definition proto.hpp:2713
void rekey(const CryptoDCInstance::RekeyType type)
Definition proto.hpp:2078
bool decapsulate(Packet &pkt)
Definition proto.hpp:3468
void key_limit_reneg(const EventType ev, const Time &t)
Definition proto.hpp:2014
bool decapsulate_tls_auth(Packet &pkt)
Definition proto.hpp:3335
PacketType(const Buffer &buf, class ProtoContext &proto)
Definition proto.hpp:1319
bool contains_tls_ciphertext() const
Definition proto.hpp:1653
Packet(BufferPtr &&buf_arg, const unsigned int opcode_arg=CONTROL_V1)
Definition proto.hpp:1622
void frame_prepare(const Frame &frame, const unsigned int context)
Definition proto.hpp:1642
const Buffer & buffer() const
Definition proto.hpp:1665
const BufferPtr & buffer_ptr()
Definition proto.hpp:1661
void parse_pushed_peer_id(const OptionList &opt)
Definition proto.hpp:797
PeerInfo::Set::Ptr extra_peer_info
extra peer info key/value pairs generated by client app
Definition proto.hpp:441
std::string peer_info_string(bool supports_epoch_data) const
Definition proto.hpp:1115
void build_connect_time_peer_info_string(TransportClient::Ptr transport)
Definition proto.hpp:1097
std::string relay_prefix(const char *optname) const
Definition proto.hpp:1272
void load_common(const OptionList &opt, const ProtoContextCompressionOptions &pco, const LoadCommonType type)
Definition proto.hpp:1222
SSLFactoryAPI::Ptr ssl_factory
Definition proto.hpp:342
void set_protocol(const Protocol &p)
Definition proto.hpp:988
TLSCryptContext::Ptr tls_crypt_context
Definition proto.hpp:424
TLSCryptFactory::Ptr tls_crypt_factory
Definition proto.hpp:423
TLSCryptMetadataFactory::Ptr tls_crypt_metadata_factory
Definition proto.hpp:426
bool tls_crypt_v2_serverkey_id
do we expect keys to contain a server key ID?
Definition proto.hpp:411
std::string tls_crypt_v2_serverkey_dir
server keys location, if tls_crypt_v2_serverkey_id is true
Definition proto.hpp:414
void show_cc_enc_option(std::ostringstream &os) const
Definition proto.hpp:949
BufferAllocated wkc
leave this undefined to disable tls-crypt-v2 on client
Definition proto.hpp:417
void set_tls_auth_digest(const CryptoAlgs::Type digest)
Definition proto.hpp:994
void parse_pushed_data_channel_options(const OptionList &opt)
Definition proto.hpp:760
AppControlMessageReceiver app_control_recv
Definition proto.hpp:445
void get_data_channel_options(std::ostringstream &os) const
Definition proto.hpp:934
void set_xmit_creds(const bool xmit_creds_arg)
Definition proto.hpp:1016
void process_push(const OptionList &opt, const ProtoContextCompressionOptions &pco)
Definition proto.hpp:701
AppControlMessageConfig app_control_config
Definition proto.hpp:444
OpenVPNStaticKey tls_crypt_key
leave this undefined to disable tls-crypt/tls-crypt-v2
Definition proto.hpp:402
void load(const OptionList &opt, const ProtoContextCompressionOptions &pco, const int default_key_direction, const bool server)
Definition proto.hpp:471
void parse_pushed_protocol_flags(const OptionList &opt)
Definition proto.hpp:820
OpenVPNStaticKey tls_auth_key
leave this undefined to disable tls_auth
Definition proto.hpp:399
PeerInfo::Set::Ptr extra_peer_info_transport
Definition proto.hpp:448
OpenVPNStaticKey wrapped_tls_crypt_key
For TLS crypt V2, this (if defined()) is the wrapped WKc client key.
Definition proto.hpp:405
std::string show_options() const
Definition proto.hpp:969
Time::Duration keepalive_timeout_early
Definition proto.hpp:438
unsigned tls_crypt_
needed to distinguish between tls-crypt and tls-crypt-v2 server mode
Definition proto.hpp:408
void parse_custom_app_control(const OptionList &opt)
Definition proto.hpp:732
void parse_pushed_compression(const OptionList &opt, const ProtoContextCompressionOptions &pco)
Definition proto.hpp:882
OvpnHMACContext::Ptr tls_auth_context
Definition proto.hpp:420
TLSPRFFactory::Ptr tlsprf_factory
Definition proto.hpp:348
StrongRandomAPI::Ptr rng
Definition proto.hpp:359
OvpnHMACFactory::Ptr tls_auth_factory
Definition proto.hpp:419
static unsigned char get_server_hard_reset_opfield()
Definition proto.hpp:3662
bool supports_early_negotiation(const PacketIDControl &pidc) const noexcept
Returns true if the peer supports early negotiation (i.e. is able to reply with CONTROL_WKC_V1).
Definition proto.hpp:3639
PsidCookieHelper(unsigned int op_field)
Definition proto.hpp:3622
static void prepend_TLV(Buffer &payload)
Adds an {EARLY_NEG_FLAGS, 2, EARLY_NEG_FLAG_RESEND_WKC} TLV to a payload buffer (use with TLS crypt V...
Definition proto.hpp:3650
bool is_tls_crypt_v2() const noexcept
Returns true if this is a TLS crypt V2 protocol packet.
Definition proto.hpp:3633
TLSAuthPreValidate(const ProtoConfig &c, const bool server)
Definition proto.hpp:3746
OPENVPN_SIMPLE_EXCEPTION(tls_auth_pre_validate)
bool validate(const BufferAllocated &net_buf)
Definition proto.hpp:3773
OPENVPN_SIMPLE_EXCEPTION(tls_crypt_pre_validate)
TLSCryptPreValidate(const ProtoConfig &c, const bool server)
Definition proto.hpp:3807
bool validate(const BufferAllocated &net_buf)
Definition proto.hpp:3844
virtual bool validate(const BufferAllocated &net_buf)=0
void data_limit_notify(const unsigned int key_id, const DataLimit::Mode cdl_mode, const DataLimit::State cdl_status)
Definition proto.hpp:4448
bool control_net_recv(const PacketType &type, BufferPtr &&net_bp)
Definition proto.hpp:4270
void set_local_peer_id(const int local_peer_id)
Definition proto.hpp:4471
uint32_t get_tls_warnings() const
Definition proto.hpp:3950
void send_explicit_exit_notify()
Definition proto.hpp:4336
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, process_server_push_error)
bool is_client() const
Definition proto.hpp:4505
void net_send(const unsigned int key_id, const Packet &net_pkt)
Definition proto.hpp:4587
const Time::Duration & slowest_handshake()
Definition proto.hpp:4376
const Time & now() const
Definition proto.hpp:4477
CryptoDCSettings & dc_settings()
Definition proto.hpp:4459
void flush(const bool control_channel)
Definition proto.hpp:4197
void set_dynamic_tls_crypt(const ProtoConfig &c, const KeyContext::Ptr &key_ctx)
Definition proto.hpp:3980
OPENVPN_SIMPLE_EXCEPTION(select_key_context_error)
void control_send(BufferPtr &&app_bp)
Definition proto.hpp:4253
KeyContext & select_control_send_context()
Definition proto.hpp:4645
bool uses_bs64_cipher() const
Definition proto.hpp:3959
void process_secondary_event()
Definition proto.hpp:4761
void reset_tls_crypt(const ProtoConfig &c, const OpenVPNStaticKey &key)
Definition proto.hpp:3964
PacketType packet_type(const Buffer &buf)
Definition proto.hpp:4158
TLSCryptMetadata::Ptr tls_crypt_metadata
Definition proto.hpp:4881
void data_encrypt(BufferAllocated &in_out)
Definition proto.hpp:4291
void reset_tls_crypt_server(const ProtoConfig &c)
Definition proto.hpp:4001
TLSCryptInstance::Ptr tls_crypt_recv
Definition proto.hpp:4878
bool is_keepalive_enabled() const
Definition proto.hpp:4424
KeyContext::Ptr primary
Definition proto.hpp:4889
TLSCryptInstance::Ptr tls_crypt_server
Definition proto.hpp:4880
const Frame & frame() const
Definition proto.hpp:4487
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_error)
static unsigned char op_compose(const unsigned int opcode, const unsigned int key_id)
Definition proto.hpp:316
static S read_auth_string(Buffer &buf)
Definition proto.hpp:1555
ProtoConfig::Ptr conf_ptr() const
Definition proto.hpp:4529
ProtoSessionID psid_peer
Definition proto.hpp:4887
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_option_error)
void process_primary_event()
Definition proto.hpp:4722
const Mode & mode() const
Definition proto.hpp:4497
TLSCryptInstance::Ptr tls_crypt_send
Definition proto.hpp:4877
void process_push(const OptionList &opt, const ProtoContextCompressionOptions &pco)
Definition proto.hpp:4408
static void write_auth_string(const S &str, Buffer &buf)
Definition proto.hpp:1541
void client_auth(Buffer &buf)
Definition proto.hpp:4577
ProtoConfig & conf()
Definition proto.hpp:4525
static const char * opcode_name(const unsigned int opcode)
Definition proto.hpp:1400
static unsigned int opcode_extract(const unsigned int op)
Definition proto.hpp:301
void set_protocol(const Protocol &p)
Definition proto.hpp:4133
static unsigned int key_id_extract(const unsigned int op)
Definition proto.hpp:306
ProtoSessionID psid_self
Definition proto.hpp:4886
static S read_control_string(const Buffer &buf)
Definition proto.hpp:1581
void write_control_string(const S &str)
Definition proto.hpp:1602
bool data_channel_ready() const
Definition proto.hpp:4364
void keepalive_housekeeping()
Definition proto.hpp:4655
Time::Duration slowest_handshake_
Definition proto.hpp:4872
unsigned int upcoming_key_id
Definition proto.hpp:4865
static unsigned int op32_compose(const unsigned int opcode, const unsigned int key_id, const int op_peer_id)
Definition proto.hpp:323
size_t align_adjust_hint() const
Definition proto.hpp:4418
PacketIDControlReceive ta_pid_recv
Definition proto.hpp:4884
ProtoContextCallbackInterface * proto_callback
Definition proto.hpp:4857
void reset_tls_wrap_mode(const ProtoConfig &c)
Definition proto.hpp:3912
SessionStats & stat() const
Definition proto.hpp:4535
bool is_server() const
Definition proto.hpp:4501
OvpnHMACInstance::Ptr ta_hmac_recv
Definition proto.hpp:4875
std::string dump_packet(const Buffer &buf)
Definition proto.hpp:1426
void disconnect(const Error::Type reason)
Definition proto.hpp:4326
static constexpr int OPCODE_SIZE
Definition proto.hpp:215
static uint16_t read_uint16_length(Buffer &buf)
Definition proto.hpp:1529
bool control_net_validate(const PacketType &type, const Buffer &net_buf)
Definition proto.hpp:4264
KeyContext & select_key_context(const PacketType &type, const bool control)
Definition proto.hpp:4614
static void write_empty_string(Buffer &buf)
Definition proto.hpp:1575
TLSWrapMode tls_wrap_mode
Definition proto.hpp:4863
void app_recv(const unsigned int key_id, BufferPtr &&to_app_buf)
Definition proto.hpp:4592
void keepalive_parms_modified()
Definition proto.hpp:4831
int primary_state() const
Definition proto.hpp:4547
static void write_control_string(const S &str, Buffer &buf)
Definition proto.hpp:1568
void control_send(BufferAllocated &&app_buf)
Definition proto.hpp:4258
bool data_decrypt(const PacketType &type, BufferAllocated &in_out)
Definition proto.hpp:4301
void disable_keepalive(unsigned int &keepalive_ping, unsigned int &keepalive_timeout)
Definition proto.hpp:4432
static constexpr PacketIDControl::id_t EARLY_NEG_MASK
Definition proto.hpp:4565
static constexpr PacketIDControl::id_t EARLY_NEG_START
Definition proto.hpp:4564
Error::Type invalidation_reason() const
Definition proto.hpp:4388
static size_t op_head_size(const unsigned int op)
Definition proto.hpp:311
void new_secondary_key(const bool initiator)
Definition proto.hpp:4700
void update_last_received()
Definition proto.hpp:4582
void promote_secondary_to_primary()
Definition proto.hpp:4712
bool is_state_client_wait_reset_ack() const
Definition proto.hpp:4541
unsigned int negotiations() const
Definition proto.hpp:4370
PacketIDControlSend ta_pid_send
Definition proto.hpp:4883
Time next_housekeeping() const
Definition proto.hpp:4235
ProtoContext(ProtoContextCallbackInterface *cb_arg, const ProtoConfig::Ptr &config_arg, const SessionStats::Ptr &stats_arg)
Definition proto.hpp:3899
static void write_uint16_length(const size_t size, Buffer &buf)
Definition proto.hpp:1521
SessionStats::Ptr stats
Definition proto.hpp:4860
unsigned int n_key_ids
Definition proto.hpp:4866
void tls_crypt_append_wkc(BufferAllocated &dst)
Definition proto.hpp:4843
ProtoConfig::Ptr config
Definition proto.hpp:4859
bool control_net_recv(const PacketType &type, BufferAllocated &&net_buf)
pass received control channel network packets (ciphertext) into protocol object
Definition proto.hpp:4285
virtual ~ProtoContext()=default
std::string debug_prefix()
Definition proto.hpp:4803
static constexpr size_t APP_MSG_MAX
Definition proto.hpp:214
const Frame::Ptr & frameptr() const
Definition proto.hpp:4491
bool invalidated() const
Definition proto.hpp:4382
void reset(const ProtoSessionID cookie_psid=ProtoSessionID())
Resets ProtoContext *this to it's initial state.
Definition proto.hpp:4042
void start(const ProtoSessionID cookie_psid=ProtoSessionID())
Initialize the state machine and start protocol negotiation.
Definition proto.hpp:4171
bool renegotiate_request(Packet &pkt)
Definition proto.hpp:4598
KeyContext::Ptr secondary
Definition proto.hpp:4890
unsigned int next_key_id()
Definition proto.hpp:4820
OvpnHMACInstance::Ptr ta_hmac_send
Definition proto.hpp:4874
const ProtoConfig & conf() const
Definition proto.hpp:4521
bool match(const ProtoSessionID &other) const
Definition psid.hpp:90
std::string str() const
Definition psid.hpp:95
constexpr bool defined() const
Definition psid.hpp:85
void randomize(StrongRandomAPI &rng)
Definition psid.hpp:52
void prepend(Buffer &buf) const
Definition psid.hpp:70
ReliableSendTemplate< Packet > ReliableSend
const AuthCert::Ptr & auth_cert() const
void export_key_material(OpenVPNStaticKey &key, const std::string &label) const
void invalidate(const Error::Type reason)
ReliableRecvTemplate< Packet > ReliableRecv
const char * occ_str(const bool server) const
Definition protocol.hpp:284
unsigned int extra_transport_bytes() const
Definition protocol.hpp:127
bool is_reliable() const
Definition protocol.hpp:87
bool is_ipv6() const
Definition protocol.hpp:95
Reference count base class for objects tracked by RCPtr. Allows copying and assignment.
Definition rc.hpp:975
void reset() noexcept
Points this RCPtr<T> to nullptr safely.
Definition rc.hpp:290
void swap(RCPtr &rhs) noexcept
swaps the contents of two RCPtr<T>
Definition rc.hpp:311
Reference count base class for objects tracked by RCPtr. Disallows copying and assignment.
Definition rc.hpp:908
static Ptr Create(ArgsT &&...args)
Creates a new instance of RcEnable with the given arguments.
Definition make_rc.hpp:43
static void prepend_id(Buffer &buf, const id_t id)
Definition relack.hpp:119
bool acks_ready() const
Definition relack.hpp:166
void push_back(id_t value)
Definition relack.hpp:39
void prepend(Buffer &buf, bool ackv1)
Definition relack.hpp:93
static id_t read_id(Buffer &buf)
Definition relack.hpp:125
static size_t ack_skip(Buffer &buf)
Definition relack.hpp:68
static size_t ack(REL_SEND &rel_send, Buffer &buf, const bool live)
Definition relack.hpp:56
void read(Buffer &buf)
Definition relack.hpp:77
unsigned int receive(const PACKET &packet, const id_t id)
Definition relrecv.hpp:57
virtual SSLLib::Ctx libctx()=0
virtual const Mode & mode() const =0
A string-like type that clears the buffer contents on delete.
Definition safestr.hpp:27
virtual void error(const size_t type, const std::string *text=nullptr)
virtual TLSCryptInstance::Ptr new_obj_send()=0
virtual TLSCryptInstance::Ptr new_obj_recv()=0
constexpr static const size_t hmac_offset
virtual size_t digest_size() const =0
virtual TLSCryptContext::Ptr new_obj(SSLLib::Ctx libctx, const CryptoAlgs::Type digest_type, const CryptoAlgs::Type cipher_type)=0
virtual bool hmac_cmp(const unsigned char *header, const size_t header_len, const unsigned char *payload, const size_t payload_len)=0
virtual bool hmac_gen(unsigned char *header, const size_t header_len, const unsigned char *payload, const size_t payload_len)=0
virtual size_t encrypt(const unsigned char *iv, unsigned char *out, const size_t olen, const unsigned char *in, const size_t ilen)=0
virtual void init(SSLLib::Ctx libctx, const StaticKey &key_hmac, const StaticKey &key_crypt)=0
virtual size_t decrypt(const unsigned char *iv, unsigned char *out, const size_t olen, const unsigned char *in, const size_t ilen)=0
virtual TLSCryptMetadata::Ptr new_obj()=0
virtual bool verify(int type, Buffer &metadata) const
void parse(const std::string &key_text)
void extract_wkc(BufferAllocated &wkc_out) const
void extract_key(OpenVPNStaticKey &tls_key)
void extract_key(OpenVPNStaticKey &tls_key)
void parse(const std::string &key_text)
virtual void self_write(Buffer &buf)=0
virtual void peer_read(Buffer &buf)=0
virtual void self_randomize(StrongRandomAPI &rng)=0
virtual void erase()=0
virtual void generate_key_expansion(OpenVPNStaticKey &dest, const ProtoSessionID &psid_self, const ProtoSessionID &psid_peer) const =0
virtual bool peer_read_complete(BufferComplete &bc)=0
T raw() const
Definition time.hpp:404
static TimeType infinite()
Definition time.hpp:254
base_type seconds_since_epoch() const
Definition time.hpp:289
bool defined() const
Definition time.hpp:280
#define OPENVPN_THROW_ARG1(exc, arg, stuff)
#define OPENVPN_THROW(exc, stuff)
#define likely(x)
Definition likely.hpp:21
#define unlikely(x)
Definition likely.hpp:22
#define OPENVPN_LOG(args)
#define OVPN_LOG_DEBUG(args)
Definition logger.hpp:226
#define OVPN_LOG_INFO(args)
Definition logger.hpp:224
#define OVPN_LOG_VERBOSE(args)
Definition logger.hpp:225
void work(openvpn_io::io_context &io_context, ThreadCommon &tc, MyRunContext &runctx, const unsigned int unit)
constexpr BufferFlags DESTRUCT_ZERO(1U<< 1)
if enabled, destructor will zero data before deletion
constexpr BufferFlags CONSTRUCT_ZERO(1U<< 0)
if enabled, constructors/init will zero allocated space
Mode mode(const Type type)
Type lookup(const std::string &name)
size_t key_length(const Type type)
const char * name(const KeyDerivation kd)
size_t size(const Type type)
std::size_t for_each(std::function< bool(Type, const Alg &)> fn)
@ KEV_NEGOTIATE_ERROR
Definition error.hpp:99
@ KEEPALIVE_TIMEOUT
Definition error.hpp:61
@ N_KEY_LIMIT_RENEG
Definition error.hpp:88
@ HANDSHAKE_TIMEOUT
Definition error.hpp:60
@ TLS_CRYPT_META_FAIL
Definition error.hpp:78
@ EARLY_NEG_INVALID
Definition error.hpp:92
bool is_safe_conversion(InT inVal)
Returns true if the given value can be contained by the out type.
OutT clamp_to_typerange(InT inVal)
Clamps the input value to the legal range for the output type.
std::vector< T > split(const T &str, const typename T::value_type sep, const int maxsplit=-1)
Definition string.hpp:452
std::string trim_crlf_copy(std::string str)
Definition string.hpp:180
const Option * load_duration_parm(Time::Duration &dur, const std::string &name, const OptionList &opt, const unsigned int min_value, const bool x2, const bool allow_ms)
Definition durhelper.hpp:41
void set_duration_parm(Time::Duration &dur, const std::string &name, const std::string &valstr, const unsigned int min_value, const bool x2, const bool ms)
Definition durhelper.hpp:20
std::string read_text(const std::string &filename, const std::uint64_t max_size=0)
Definition file.hpp:127
std::string to_string(const T &t)
Convert a value to a string.
Definition to_string.hpp:45
const char * platform_name()
std::string render_hex(const unsigned char *data, size_t size, const bool caps=false)
Definition hexstr.hpp:133
TimeType< oulong > Time
Definition time.hpp:487
unsigned int parse_tun_mtu_max(const OptionList &opt, unsigned int default_value)
Definition tunmtu.hpp:28
@ TUN_MTU_DEFAULT
Definition tunmtu.hpp:20
bool is_bs64_cipher(const CryptoAlgs::Type cipher)
unsigned int parse_tun_mtu(const OptionList &opt, unsigned int default_value)
Definition tunmtu.hpp:23
std::string get_hwaddr(IP::Addr server_addr)
Definition hwaddr.hpp:31
std::string dump_hex(const unsigned char *data, size_t size)
Definition hexstr.hpp:253
Implementation of the base classes for random number generators.
std::vector< std::string > supported_protocols
List of supported protocols.
int max_msg_size
Maximum size of each individual message/message fragment.
void parse_flags(const std::string &flags)
void parse(const OptionList &opt, bool nothrow=false)
Definition mssparms.hpp:26
unsigned int mssfix
Definition mssparms.hpp:71
static constexpr size_t size()
constexpr std::size_t size() const
std::optional< CryptoDCInstance::RekeyType > rekey_type
Definition proto.hpp:1705
virtual IP::Addr server_endpoint_addr() const =0
reroute_gw flags
os<< "Session Name: "<< tbc-> session_name<< '\n';os<< "Layer: "<< tbc-> layer str()<< '\n'
std::string ret
std::ostringstream os
if(flags &RedirectGatewayFlags::RG_ENABLE) ret+
static std::stringstream out
Definition test_path.cpp:10
const std::string optname
#define OPENVPN_VERSION
Definition version.hpp:17