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 else
1538 return 0;
1539 }
1540
1541 template <typename S>
1542 static void write_auth_string(const S &str, Buffer &buf)
1543 {
1544 const size_t len = str.length();
1545 if (len)
1546 {
1547 write_uint16_length(len + 1, buf);
1548 buf.write((const unsigned char *)str.c_str(), len);
1549 buf.null_terminate();
1550 }
1551 else
1552 write_uint16_length(0, buf);
1553 }
1554
1555 template <typename S>
1557 {
1558 const size_t len = read_uint16_length(buf);
1559 if (len)
1560 {
1561 const char *data = (const char *)buf.read_alloc(len);
1562 if (len > 1)
1563 return S(data, len - 1);
1564 }
1565 return S();
1566 }
1567
1568 template <typename S>
1569 static void write_control_string(const S &str, Buffer &buf)
1570 {
1571 const size_t len = str.length();
1572 buf.write((const unsigned char *)str.c_str(), len);
1573 buf.null_terminate();
1574 }
1575
1576 static void write_empty_string(Buffer &buf)
1577 {
1578 write_uint16_length(0, buf);
1579 }
1580
1581 template <typename S>
1582 static S read_control_string(const Buffer &buf)
1583 {
1584 size_t size = buf.size();
1585 if (size)
1586 {
1587 /* Trim any trailing \n or \r or 0x00 characters. Scripts plugin sometimes accidentally include a \n or \r\n in AUTH_FAILED
1588 * or similar messages */
1589 while (size > 0 && (buf[size - 1] == 0 || buf[size - 1] == '\r' || buf[size - 1] == '\n'))
1590 {
1591 --size;
1592 }
1593
1594 if (size)
1595 {
1596 return S{reinterpret_cast<const char *>(buf.c_data()), size};
1597 }
1598 }
1599 return {};
1600 }
1601
1602 template <typename S>
1604 {
1605 const size_t len = str.length();
1606 auto bp = BufferAllocatedRc::Create(len + 1);
1608 control_send(std::move(bp));
1609 }
1610
1611 // Packet structure for managing network packets, passed as a template
1612 // parameter to ProtoStackBase
1614 {
1615 friend class ProtoContext;
1616
1617 public:
1619 {
1620 reset_non_buf();
1621 }
1622
1623 Packet(BufferPtr &&buf_arg, const unsigned int opcode_arg = CONTROL_V1)
1624 : opcode(opcode_arg), buf(std::move(buf_arg))
1625 {
1626 }
1627
1628 // clone packet, including buffer content
1630 {
1631 Packet pkt;
1632 pkt.opcode = opcode;
1634 return pkt;
1635 }
1636
1637 void reset()
1638 {
1639 reset_non_buf();
1640 buf.reset();
1641 }
1642
1643 void frame_prepare(const Frame &frame, const unsigned int context)
1644 {
1645 if (!buf)
1647 frame.prepare(context, *buf);
1648 }
1649
1655 {
1656 return opcode == CONTROL_V1 || opcode == CONTROL_WKC_V1;
1657 }
1658 operator bool() const
1659 {
1660 return bool(buf);
1661 }
1663 {
1664 return buf;
1665 }
1666 const Buffer &buffer() const
1667 {
1668 return *buf;
1669 }
1670
1671 private:
1673 {
1675 }
1676
1677 unsigned int opcode;
1679 };
1680
1681 // KeyContext encapsulates a single SSL/TLS session.
1682 // ProtoStackBase uses CRTP-based static polymorphism for method callbacks.
1683 class KeyContext : ProtoStackBase<Packet, KeyContext>, public RC<thread_unsafe_refcount>
1684 {
1686 friend Base;
1689
1690 // ProtoStackBase protected vars
1691 using Base::now;
1692 using Base::rel_recv;
1693 using Base::rel_send;
1694 using Base::xmit_acks;
1695
1696 // ProtoStackBase member functions
1697 using Base::raw_send;
1700
1701 // Helper for handling deferred data channel setup,
1702 // for example if cipher/digest are pushed.
1704 {
1706 std::optional<CryptoDCInstance::RekeyType> rekey_type;
1707 };
1708
1709 public:
1711
1712 // ProtoStackBase member functions
1714
1715 OPENVPN_SIMPLE_EXCEPTION(tls_crypt_unwrap_wkc_error);
1716
1717 // KeyContext events occur on two basic key types:
1718 // Primary Key -- the key we transmit/encrypt on.
1719 // Secondary Key -- new keys and retiring keys.
1720 //
1721 // The very first key created (key_id == 0) is a
1722 // primary key. Subsequently created keys are always,
1723 // at least initially, secondary keys. Secondary keys
1724 // promote to primary via the KEV_BECOME_PRIMARY event
1725 // (actually KEV_BECOME_PRIMARY swaps the primary and
1726 // secondary keys, so the old primary is demoted
1727 // to secondary and marked for expiration).
1728 //
1729 // Secondary keys are created by:
1730 // 1. locally-generated soft renegotiation requests, and
1731 // 2. peer-requested soft renegotiation requests.
1732 // In each case, any previous secondary key will be
1733 // wiped (including a secondary key that exists due to
1734 // demotion of a previous primary key that has been marked
1735 // for expiration).
1737 {
1739
1740 // KeyContext has reached the ACTIVE state, occurs on both
1741 // primary and secondary.
1743
1744 // SSL/TLS negotiation must complete by this time. If this
1745 // event is hit on the first primary (i.e. first KeyContext
1746 // with key_id == 0), it is fatal to the session and will
1747 // trigger a disconnect/reconnect. If it's hit on the
1748 // secondary, it will trigger a soft renegotiation.
1750
1751 // When a KeyContext (normally the secondary) is scheduled
1752 // to transition to the primary state.
1754
1755 // Waiting for condition on secondary (usually
1756 // dataflow-based) to trigger KEV_BECOME_PRIMARY.
1758
1759 // Start renegotiating a new KeyContext on secondary
1760 // (ignored unless originating on primary).
1762
1763 // Trigger a renegotiation originating from either
1764 // primary or secondary.
1766
1767 // Queue delayed renegotiation request from secondary
1768 // to take effect after KEV_BECOME_PRIMARY.
1770
1771 // Expiration of KeyContext.
1773 };
1774
1775 // for debugging
1776 static const char *event_type_string(const EventType et)
1777 {
1778 switch (et)
1779 {
1780 case KEV_NONE:
1781 return "KEV_NONE";
1782 case KEV_ACTIVE:
1783 return "KEV_ACTIVE";
1784 case KEV_NEGOTIATE:
1785 return "KEV_NEGOTIATE";
1786 case KEV_BECOME_PRIMARY:
1787 return "KEV_BECOME_PRIMARY";
1789 return "KEV_PRIMARY_PENDING";
1790 case KEV_RENEGOTIATE:
1791 return "KEV_RENEGOTIATE";
1793 return "KEV_RENEGOTIATE_FORCE";
1795 return "KEV_RENEGOTIATE_QUEUE";
1796 case KEV_EXPIRE:
1797 return "KEV_EXPIRE";
1798 default:
1799 return "KEV_?";
1800 }
1801 }
1802
1803 KeyContext(ProtoContext &p, const bool initiator, bool psid_cookie_mode = false)
1804 : Base(*p.config->ssl_factory,
1805 p.config->now,
1807 p.config->frame,
1808 p.stats,
1809 psid_cookie_mode),
1810 proto(p),
1812 crypto_flags(0),
1813 dirty(0),
1815 tlsprf(p.config->tlsprf_factory->new_obj(p.is_server()))
1816 {
1817 // reliable protocol?
1818 set_protocol(proto.config->protocol);
1819
1820 // get key_id from parent
1822
1823 // set initial state
1824 set_state((proto.is_server() ? S_INITIAL : C_INITIAL) + (initiator ? 0 : 1));
1825
1826 // cache stuff that we need to access in hot path
1827 cache_op32();
1828
1829 // remember when we were constructed
1831
1832 // set must-negotiate-by time
1834 }
1835
1836 void set_protocol(const Protocol &p)
1837 {
1838 is_reliable = p.is_reliable(); // cache is_reliable state locally
1839 }
1840
1841 uint32_t get_tls_warnings() const
1842 {
1843 return Base::get_tls_warnings();
1844 }
1845
1853 void start(const ProtoSessionID cookie_psid = ProtoSessionID())
1854 {
1855 if (cookie_psid.defined())
1856 {
1858 dirty = true;
1859 }
1860 if (state == C_INITIAL || state == S_INITIAL)
1861 {
1862 send_reset();
1863 set_state(state + 1);
1864 dirty = true;
1865 }
1866 }
1867
1868 // control channel flush
1869 void flush()
1870 {
1871 if (dirty)
1872 {
1874 Base::flush();
1876 dirty = false;
1877 }
1878 }
1879
1880 void invalidate(const Error::Type reason)
1881 {
1882 Base::invalidate(reason);
1883 }
1884
1885 // retransmit packets as part of reliability layer
1887 {
1888 // note that we don't set dirty here
1890 }
1891
1892 // when should we next call retransmit method
1894 {
1895 const Time t = Base::next_retransmit();
1896 if (t <= next_event_time)
1897 return t;
1898 else
1899 return next_event_time;
1900 }
1901
1903 {
1904 if (bp->size() > APP_MSG_MAX)
1905 throw proto_error("app_send: sent control message is too large");
1906 Base::app_send(std::move(bp));
1907 }
1908
1909 // send app-level cleartext data to peer via SSL
1911 {
1912 if (state >= ACTIVE)
1913 {
1914 app_send_validate(std::move(bp));
1915 dirty = true;
1916 }
1917 else
1918 app_pre_write_queue.push_back(bp);
1919 }
1920
1921 // pass received ciphertext packets on network to SSL/reliability layers
1922 bool net_recv(Packet &&pkt)
1923 {
1924 const bool ret = Base::net_recv(std::move(pkt));
1925 dirty = true;
1926 return ret;
1927 }
1928
1929 // data channel encrypt
1931 {
1932 if (state >= ACTIVE
1934 && !invalidated())
1935 {
1936 // compress and encrypt packet and prepend op header
1937 const bool pid_wrap = do_encrypt(buf, true);
1938
1939 // Trigger a new SSL/TLS negotiation if packet ID (a 32-bit unsigned int)
1940 // is getting close to wrapping around. If it wraps back to 0 without
1941 // a renegotiation, it would cause the replay protection logic to wrongly
1942 // think that all further packets are replays.
1943 if (pid_wrap)
1945 }
1946 else
1947 buf.reset_size(); // no crypto context available
1948 }
1949
1950 // data channel decrypt
1952 {
1953 try
1954 {
1955 if (state >= ACTIVE
1957 && !invalidated())
1958 {
1959 // Knock off leading op from buffer, but pass the 32-bit version to
1960 // decrypt so it can be used as Additional Data for packet authentication.
1961 const size_t head_size = op_head_size(buf[0]);
1962 const unsigned char *op32 = (head_size == OP_SIZE_V2) ? buf.c_data() : nullptr;
1963 buf.advance(head_size);
1964
1965 // decrypt packet
1966 const Error::Type err = crypto->decrypt(buf, now->seconds_since_epoch(), op32);
1967 if (err)
1968 {
1969 proto.stats->error(err);
1970 if (proto.is_tcp() && (err == Error::DECRYPT_ERROR || err == Error::HMAC_ERROR))
1971 invalidate(err);
1972 }
1973
1974 // trigger renegotiation if we hit decrypt data limit
1975 if (data_limit)
1977 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "Unable to add data limit");
1978
1979 // decompress packet
1980 if (compress)
1981 compress->decompress(buf);
1982
1983 // set MSS for segments server can receive
1984 if (proto.config->mss_fix > 0)
1985 MSSFix::mssfix(buf, numeric_cast<uint16_t>(proto.config->mss_fix));
1986 }
1987 else
1988 buf.reset_size(); // no crypto context available
1989 }
1990 catch (std::exception &)
1991 {
1993 buf.reset_size();
1994 if (proto.is_tcp())
1996 }
1997 }
1998
1999 // usually called by parent ProtoContext object when this KeyContext
2000 // has been retired.
2002 {
2003 set_event(current_ev,
2004 KEV_EXPIRE,
2006 }
2007
2008 // set a default next event, if unspecified
2010 {
2011 if (next_event == KEV_NONE && !invalidated())
2013 }
2014
2015 // set a key limit renegotiation event at time t
2016 void key_limit_reneg(const EventType ev, const Time &t)
2017 {
2018 if (t.defined())
2019 set_event(KEV_NONE, ev, t + Time::Duration::seconds(proto.is_server() ? 2 : 1));
2020 }
2021
2022 // return time of upcoming KEV_BECOME_PRIMARY event
2024 {
2026 return next_event_time;
2027 else
2028 return Time();
2029 }
2030
2031 // is an KEV_x event pending?
2033 {
2036 return current_event != KEV_NONE;
2037 }
2038
2039 // get KEV_x event
2041 {
2042 return current_event;
2043 }
2044
2045 // clear KEV_x event
2047 {
2049 }
2050
2051 // was session invalidated by an exception?
2052 bool invalidated() const
2053 {
2054 return Base::invalidated();
2055 }
2056
2057 // Reason for invalidation
2059 {
2061 }
2062
2063 // our Key ID in the OpenVPN protocol
2064 unsigned int key_id() const
2065 {
2066 return key_id_;
2067 }
2068
2069 // indicates that data channel is keyed and ready to encrypt/decrypt packets
2071 {
2072 return state >= ACTIVE;
2073 }
2074
2075 bool is_dirty() const
2076 {
2077 return dirty;
2078 }
2079
2080 // notification from parent of rekey operation
2082 {
2083 if (crypto)
2084 crypto->rekey(type);
2085 else if (data_channel_key)
2086 {
2087 // save for deferred processing
2088 data_channel_key->rekey_type = type;
2089 }
2090 }
2091
2092 // time that our state transitioned to ACTIVE
2094 {
2095 return reached_active_time_;
2096 }
2097
2098 // transmit a keepalive message to peer
2100 {
2101 send_data_channel_message(proto_context_private::keepalive_message,
2102 sizeof(proto_context_private::keepalive_message));
2103 }
2104
2105 // send explicit-exit-notify message to peer
2107 {
2110 else
2111 send_data_channel_message(proto_context_private::explicit_exit_notify_message,
2112 sizeof(proto_context_private::explicit_exit_notify_message));
2113 }
2114
2115 // general purpose method for sending constant string messages
2116 // to peer via data channel
2117 void send_data_channel_message(const unsigned char *data, const size_t size)
2118 {
2119 if (state >= ACTIVE
2121 && !invalidated())
2122 {
2123 // allocate packet
2124 Packet pkt;
2126
2127 // write keepalive message
2128 pkt.buf->write(data, size);
2129
2130 // process packet for transmission
2131 do_encrypt(*pkt.buf, false); // set compress hint to "no"
2132
2133 // send it
2134 proto.net_send(key_id_, pkt);
2135 }
2136 }
2137
2138 // validate the integrity of a packet
2139 static bool validate(const Buffer &net_buf, ProtoContext &proto, TimePtr now)
2140 {
2141 try
2142 {
2143 Buffer recv(net_buf);
2144
2145 switch (proto.tls_wrap_mode)
2146 {
2147 case TLS_AUTH:
2148 return validate_tls_auth(recv, proto, now);
2149 case TLS_CRYPT_V2:
2151 {
2152 // skip validation of HARD_RESET_V3 because the tls-crypt
2153 // engine has not been initialized yet
2154 OVPN_LOG_VERBOSE("SKIPPING VALIDATION OF HARD_RESET_V3");
2155 return true;
2156 }
2157 /* no break */
2158 case TLS_CRYPT:
2159 return validate_tls_crypt(recv, proto, now);
2160 case TLS_PLAIN:
2161 return validate_tls_plain(recv, proto, now);
2162 }
2163 }
2164 catch ([[maybe_unused]] BufferException &e)
2165 {
2166 OVPN_LOG_VERBOSE("validate() exception: " << e.what());
2167 }
2168 return false;
2169 }
2170
2171 // Resets data_channel_key but also retains old
2172 // rekey_defined and rekey_type from previous instance.
2174 {
2175 std::unique_ptr<DataChannelKey> dck(new DataChannelKey());
2176
2177 if (proto.config->dc.key_derivation() == CryptoAlgs::KeyDerivation::TLS_EKM)
2178 {
2179 // USE RFC 5705 key material export
2180 export_key_material(dck->key, "EXPORTER-OpenVPN-datakeys");
2181 }
2182 else
2183 {
2184 // use the TLS PRF construction to exchange session keys for building
2185 // the data channel crypto context
2187 }
2188 tlsprf->erase();
2190 << " KEY " << CryptoAlgs::name(proto.config->dc.key_derivation())
2191 << " " << proto.mode().str() << ' ' << dck->key.render());
2192
2193 if (data_channel_key)
2194 {
2195 dck->rekey_type = data_channel_key->rekey_type;
2196 }
2197 dck.swap(data_channel_key);
2198 }
2199
2201 {
2202 if (c.mss_parms.fixed)
2203 {
2204 // substract IPv4 and TCP overhead, mssfix method will add extra 20 bytes for IPv6
2205 c.mss_fix = c.mss_parms.mssfix - (20 + 20);
2206 OPENVPN_LOG("fixed mssfix=" << c.mss_fix);
2207 return;
2208 }
2209
2210 /* If we are running default mssfix but have a different tun-mtu pushed
2211 * disable mssfix */
2212 if (c.tun_mtu != TUN_MTU_DEFAULT && c.tun_mtu != 0 && c.mss_parms.mssfix_default)
2213 {
2214 c.mss_fix = 0;
2215 OPENVPN_LOG("mssfix disabled since tun-mtu is non-default ("
2216 << c.tun_mtu << ")");
2217 return;
2218 }
2219
2220 auto payload_overhead = size_t(0);
2221
2222 // compv2 doesn't increase payload size
2223 switch (c.comp_ctx.type())
2224 {
2228 break;
2229 default:
2230 payload_overhead += 1;
2231 }
2232
2234 payload_overhead += PacketIDData::size(false);
2235
2236 // account for IPv4 and TCP headers of the payload, mssfix method
2237 // will add 20 extra bytes if payload is IPv6
2238 payload_overhead += 20 + 20;
2239
2240 auto overhead = c.protocol.extra_transport_bytes()
2241 + (enable_op32 ? OP_SIZE_V2 : 1)
2242 + c.dc.context().encap_overhead();
2243
2244 // in CBC mode, the packet id is part of the payload size / overhead
2246 overhead += PacketIDData::size(false);
2247
2248 if (c.mss_parms.mtu)
2249 {
2250 overhead += c.protocol.is_ipv6()
2251 ? sizeof(struct IPv6Header)
2252 : sizeof(struct IPv4Header);
2253 overhead += proto.is_tcp()
2254 ? sizeof(struct TCPHeader)
2255 : sizeof(struct UDPHeader);
2256 }
2257
2258 auto target = c.mss_parms.mssfix - overhead;
2259 if (CryptoAlgs::mode(c.dc.cipher()) == CryptoAlgs::CBC_HMAC)
2260 {
2261 // openvpn3 crypto includes blocksize in overhead, but we can
2262 // be a bit smarter here and instead make sure that resulting
2263 // ciphertext size (which is always multiple blocksize) is not
2264 // larger than target by running down target to the nearest
2265 // multiple of multiple and substracting 1.
2266
2267 auto block_size = CryptoAlgs::block_size(c.dc.cipher());
2268 target += block_size;
2269 target = (target / block_size) * block_size;
2270 target -= 1;
2271 }
2272
2273 if (!is_safe_conversion<decltype(c.mss_fix)>(target - payload_overhead))
2274 {
2275 OPENVPN_LOG("mssfix disabled since computed value is outside type bounds ("
2276 << c.mss_fix << ")");
2277 c.mss_fix = 0;
2278 return;
2279 }
2280
2281 c.mss_fix = static_cast<decltype(c.mss_fix)>(target - payload_overhead);
2282 OVPN_LOG_VERBOSE("mssfix=" << c.mss_fix
2283 << " (upper bound=" << c.mss_parms.mssfix
2284 << ", overhead=" << overhead
2285 << ", payload_overhead=" << payload_overhead
2286 << ", target=" << target << ")");
2287 }
2288
2289 // Initialize the components of the OpenVPN data channel protocol
2291 {
2292 // don't run until our prerequisites are satisfied
2293 if (!data_channel_key)
2294 return;
2296
2297 // set up crypto for data channel
2298 bool enable_compress = true;
2299 ProtoConfig &c = *proto.config;
2300 const unsigned int key_dir = proto.is_server() ? OpenVPNStaticKey::INVERSE : OpenVPNStaticKey::NORMAL;
2301 const OpenVPNStaticKey &key = data_channel_key->key;
2302
2303 // special data limits for 64-bit block-size ciphers (CVE-2016-6329)
2304 if (is_bs64_cipher(c.dc.cipher()))
2305 {
2309 OVPN_LOG_INFO("Per-Key Data Limit: "
2310 << dp.encrypt_red_limit << '/' << dp.decrypt_red_limit);
2311 data_limit.reset(new DataLimit(dp));
2312 }
2313
2314 // build crypto context for data channel encryption/decryption
2317
2322
2326
2327 crypto->init_pid("DATA",
2328 int(key_id_),
2329 proto.stats);
2330
2332
2333 enable_compress = crypto->consider_compression(proto.config->comp_ctx);
2334
2335 if (data_channel_key->rekey_type.has_value())
2336 crypto->rekey(data_channel_key->rekey_type.value());
2337 data_channel_key.reset();
2338
2339 // set up compression for data channel
2340 if (enable_compress)
2341 compress = proto.config->comp_ctx.new_compressor(proto.config->frame, proto.stats);
2342 else
2343 compress.reset();
2344
2345 // cache op32 for hot path in do_encrypt
2346 cache_op32();
2347
2349 }
2350
2352 const DataLimit::State cdl_status)
2353 {
2354 if (data_limit)
2355 data_limit_event(cdl_mode, data_limit->update_state(cdl_mode, cdl_status));
2356 }
2357
2358 int get_state() const
2359 {
2360 return state;
2361 }
2362
2375 ProtoConfig &proto_config,
2378 {
2379 // the ``WKc`` is located at the end of the packet, after the tls-crypt
2380 // payload.
2381 //
2382 // K_id is optional, and controlled by proto_config.tls_crypt_v2_serverkey_id.
2383 // If it is missing, we will use a single server key for all clients.
2384 //
2385 // Format is as follows:
2386 //
2387 // ``len = len(WKc)`` (16 bit, network byte order)
2388 // ``T = HMAC-SHA256(Ka, len || K_id || Kc || metadata)``
2389 // ``IV = 128 most significant bits of T``
2390 // ``WKc = T || AES-256-CTR(Ke, IV, Kc || metadata) || K_id || len``
2391
2392 const unsigned char *orig_data = recv.data();
2393 const size_t orig_size = recv.size();
2394 const size_t hmac_size = proto_config.tls_crypt_context->digest_size();
2395 const size_t tls_frame_size = OPCODE_SIZE + ProtoSessionID::SIZE
2397 + hmac_size
2398 // the following is the tls-crypt payload
2399 + sizeof(char) // length of ACK array
2400 + sizeof(id_t); // reliable ID
2401
2402 // check that at least the authentication tag ``T`` is present
2403 if (orig_size < (tls_frame_size + hmac_size))
2404 return Error::CC_ERROR;
2405
2406 // the ``WKc`` is just appended after the standard tls-crypt frame
2407 const unsigned char *wkc_raw = orig_data + tls_frame_size;
2408 size_t wkc_raw_size = orig_size - tls_frame_size - sizeof(uint16_t);
2409 // retrieve the ``WKc`` len from the bottom of the packet and convert it to Host Order
2410 uint16_t wkc_len;
2411 // avoid unaligned access
2412 std::memcpy(&wkc_len, wkc_raw + wkc_raw_size, sizeof(wkc_len));
2413 wkc_len = ntohs(wkc_len);
2414
2415 // There's also a payload here, so the assumption that the difference in size
2416 // from the TLS frame's end to the end of the packet constitutes the WKc no
2417 // longer holds. We can only rely on wkc_len for P_CONTROL_WKC_V1 packets.
2418 if (opcode_extract(orig_data[0]) != CONTROL_HARD_RESET_CLIENT_V3)
2419 {
2420 wkc_raw = orig_data + orig_size - wkc_len;
2421 wkc_raw_size = wkc_len - sizeof(uint16_t);
2422 }
2423
2424 uint32_t k_id = 0;
2425 const size_t serverkey_id_size = proto_config.tls_crypt_v2_serverkey_id ? sizeof(k_id) : 0;
2426
2427 if (proto_config.tls_crypt_v2_serverkey_id)
2428 {
2429 std::memcpy(&k_id, wkc_raw + wkc_raw_size - serverkey_id_size, sizeof(k_id));
2430 k_id = ntohl(k_id);
2431 }
2432
2433 // length sanity check (the size of the ``len`` field is included in the value)
2434 if ((wkc_len - sizeof(uint16_t)) != wkc_raw_size)
2435 return Error::CC_ERROR;
2436
2438 // plaintext will be used to compute the Auth Tag, therefore start by prepending
2439 // the WKc length in network order
2440 const uint16_t net_wkc_len = htons(wkc_len);
2441 plaintext.write(&net_wkc_len, sizeof(net_wkc_len));
2442
2443 if (proto_config.tls_crypt_v2_serverkey_id)
2444 {
2445 std::stringstream ss;
2446 ss << std::hex << std::setfill('0') << std::uppercase << std::setw(8) << k_id;
2447
2448 const std::string serverkey_fn = ss.str() + ".key";
2449 const std::string serverkey_path = proto_config.tls_crypt_v2_serverkey_dir + "/"
2450 + serverkey_fn.substr(0, 2) + "/" + serverkey_fn;
2451
2452 // If the key is missing, an exception will be thrown here, for example:
2453 // "cannot open for read: <KEYS_DIR>/06/063FE634.key"
2454 const std::string serverkey = read_text(serverkey_path);
2455
2456 OVPN_LOG_VERBOSE("Using TLS-crypt-V2 server key " << serverkey_path);
2457
2458 TLSCryptV2ServerKey tls_crypt_v2_key;
2459 tls_crypt_v2_key.parse(serverkey);
2460 tls_crypt_v2_key.extract_key(proto_config.tls_crypt_key);
2461
2462 // the server key is composed by one key set only, therefore direction and
2463 // mode should not be specified when slicing
2464 tls_crypt_server.init(proto_config.ssl_factory->libctx(),
2467
2468 k_id = htonl(k_id);
2469 plaintext.write(&k_id, sizeof(k_id));
2470 }
2471
2472 if (plaintext.max_size() <= 2 + serverkey_id_size)
2473 return Error::DECRYPT_ERROR;
2474
2475 const size_t decrypt_bytes = tls_crypt_server.decrypt(wkc_raw,
2476 plaintext.data() + 2 + serverkey_id_size,
2477 plaintext.max_size() - 2 - serverkey_id_size,
2478 wkc_raw + hmac_size,
2479 wkc_raw_size - hmac_size - serverkey_id_size);
2480 plaintext.inc_size(decrypt_bytes);
2481 // decrypted data must at least contain a full 2048bits client key
2482 // (metadata is optional)
2483 if (plaintext.size() < OpenVPNStaticKey::KEY_SIZE)
2484 return Error::DECRYPT_ERROR;
2485
2486 if (!tls_crypt_server.hmac_cmp(wkc_raw, 0, plaintext.c_data(), plaintext.size()))
2487 return Error::HMAC_ERROR;
2488
2489 // we can now remove the WKc length (and the server key ID, if present)
2490 // from the plaintext, as they are not really part of the key material
2491 plaintext.advance(sizeof(wkc_len));
2492
2493 if (proto_config.tls_crypt_v2_serverkey_id)
2494 plaintext.advance(sizeof(k_id));
2495
2497
2498 // verify metadata
2499 int metadata_type = -1;
2500 if (!plaintext.empty())
2501 metadata_type = plaintext.pop_front();
2502
2503 if (tls_crypt_metadata && !tls_crypt_metadata->verify(metadata_type, plaintext))
2505
2506 // virtually remove the WKc from the packet
2507 recv.set_size(orig_size - wkc_len);
2508
2509 return Error::SUCCESS;
2510 }
2511
2512 private:
2514 {
2515 const unsigned char *orig_data = recv.data();
2516 const size_t orig_size = recv.size();
2517
2518 // advance buffer past initial op byte
2519 recv.advance(1);
2520
2521 // get source PSID
2522 ProtoSessionID src_psid(recv);
2523
2524 // verify HMAC
2525 {
2526 recv.advance(proto.hmac_size);
2527 if (!proto.ta_hmac_recv->ovpn_hmac_cmp(orig_data,
2528 orig_size,
2532 {
2533 return false;
2534 }
2535 }
2536
2537 // verify source PSID
2538 if (!proto.psid_peer.match(src_psid))
2539 return false;
2540
2541 // read tls_auth packet ID
2542 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
2543
2544 // get current time_t
2546
2547 // verify tls_auth packet ID
2548 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
2549
2550 // make sure that our own PSID is contained in packet received from peer
2551 if (ReliableAck::ack_skip(recv))
2552 {
2553 ProtoSessionID dest_psid(recv);
2554 if (!proto.psid_self.match(dest_psid))
2555 return false;
2556 }
2557
2558 return pid_ok;
2559 }
2560
2562 {
2563 const unsigned char *orig_data = recv.data();
2564 const size_t orig_size = recv.size();
2565
2566 // advance buffer past initial op byte
2567 recv.advance(1);
2568 // get source PSID
2569 ProtoSessionID src_psid(recv);
2570 // read tls_auth packet ID
2571 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
2572
2573 recv.advance(proto.hmac_size);
2574
2575 const size_t head_size = OPCODE_SIZE + ProtoSessionID::SIZE + PacketIDControl::size();
2576 const size_t data_offset = head_size + proto.hmac_size;
2577 if (orig_size < data_offset)
2578 return false;
2579
2580 // we need a buffer to perform the payload decryption and being this a static
2581 // function we can't use the instance member like in decapsulate_tls_crypt()
2583 proto.config->frame->prepare(Frame::DECRYPT_WORK, work);
2584
2585 // decrypt payload from 'recv' into 'work'
2586 const size_t decrypt_bytes = proto.tls_crypt_recv->decrypt(orig_data + head_size,
2587 work.data(),
2588 work.max_size(),
2589 recv.c_data(),
2590 recv.size());
2591 if (!decrypt_bytes)
2592 return false;
2593
2594 work.inc_size(decrypt_bytes);
2595
2596 // verify HMAC
2597 if (!proto.tls_crypt_recv->hmac_cmp(orig_data,
2599 work.c_data(),
2600 work.size()))
2601 return false;
2602
2603 // verify source PSID
2604 if (proto.psid_peer.defined())
2605 {
2606 if (!proto.psid_peer.match(src_psid))
2607 return false;
2608 }
2609 else
2610 {
2611 proto.psid_peer = src_psid;
2612 }
2613
2614 // get current time_t
2616
2617 // verify tls_auth packet ID
2618 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
2619 // make sure that our own PSID is contained in packet received from peer
2621 {
2622 ProtoSessionID dest_psid(work);
2623 if (!proto.psid_self.match(dest_psid))
2624 return false;
2625 }
2626
2627 return pid_ok;
2628 }
2629
2631 {
2632 // advance buffer past initial op byte
2633 recv.advance(1);
2634
2635 // verify source PSID
2636 ProtoSessionID src_psid(recv);
2637 if (!proto.psid_peer.match(src_psid))
2638 return false;
2639
2640 // make sure that our own PSID is contained in packet received from peer
2641 if (ReliableAck::ack_skip(recv))
2642 {
2643 ProtoSessionID dest_psid(recv);
2644 if (!proto.psid_self.match(dest_psid))
2645 return false;
2646 }
2647 return true;
2648 }
2649
2650 bool do_encrypt(BufferAllocated &buf, const bool compress_hint)
2651 {
2652 if (!is_safe_conversion<uint16_t>(proto.config->mss_fix))
2653 return false;
2654
2655 // set MSS for segments client can receive
2656 if (proto.config->mss_fix > 0)
2657 MSSFix::mssfix(buf, static_cast<uint16_t>(proto.config->mss_fix));
2658
2659 // compress packet
2660 if (compress)
2661 compress->compress(buf, compress_hint);
2662
2663 // trigger renegotiation if we hit encrypt data limit
2664 if (data_limit)
2666 return false;
2667
2668 bool pid_wrap;
2669
2670 if (enable_op32)
2671 {
2672 const std::uint32_t op32 = htonl(op32_compose(DATA_V2, key_id_, remote_peer_id));
2673
2674 static_assert(sizeof(op32) == OP_SIZE_V2, "OP_SIZE_V2 inconsistency");
2675
2676 // encrypt packet
2677 pid_wrap = crypto->encrypt(buf, (const unsigned char *)&op32);
2678
2679 // prepend op
2680 buf.prepend((const unsigned char *)&op32, sizeof(op32));
2681 }
2682 else
2683 {
2684 // encrypt packet
2685 pid_wrap = crypto->encrypt(buf, nullptr);
2686
2687 // prepend op
2689 }
2690 return pid_wrap;
2691 }
2692
2693 // cache op32 and remote_peer_id
2695 {
2696 enable_op32 = proto.config->enable_op32;
2697 remote_peer_id = proto.config->remote_peer_id;
2698 }
2699
2700 void set_state(const int newstate)
2701 {
2703 << " KeyContext[" << key_id_ << "] "
2704 << state_string(state) << " -> " << state_string(newstate));
2705 state = newstate;
2706 }
2707
2708 void set_event(const EventType current)
2709 {
2711 << " KeyContext[" << key_id_ << "] "
2712 << event_type_string(current));
2713 current_event = current;
2714 }
2715
2716 void set_event(const EventType current, const EventType next, const Time &next_time)
2717 {
2719 << " KeyContext[" << key_id_ << "] "
2720 << event_type_string(current) << " -> " << event_type_string(next)
2721 << '(' << seconds_until(next_time) << ')');
2722 current_event = current;
2723 next_event = next;
2724 next_event_time = next_time;
2725 }
2726
2727 void invalidate_callback() // called by ProtoStackBase when session is invalidated
2728 {
2732 }
2733
2734 // Trigger a renegotiation based on data flow condition such
2735 // as per-key data limit or packet ID approaching wraparound.
2737 {
2739 {
2740 OVPN_LOG_VERBOSE(proto.debug_prefix() << " SCHEDULE KEY LIMIT RENEGOTIATION");
2741
2744
2745 // If primary, renegotiate now (within a second or two).
2746 // If secondary, queue the renegotiation request until
2747 // key reaches primary.
2748 if (next_event == KEV_BECOME_PRIMARY) // secondary key before transition to primary?
2749 {
2750 // reneg request crosses over to primary,
2751 // doesn't wipe next_event (KEV_BECOME_PRIMARY)
2753 }
2754 else
2755 {
2757 }
2758 }
2759 }
2760
2761 // Handle data-limited keys such as Blowfish and other 64-bit block-size ciphers.
2762 bool data_limit_add(const DataLimit::Mode mode, const size_t size)
2763 {
2764 if (is_safe_conversion<DataLimit::size_type>(size))
2765 return false;
2766 const DataLimit::State state = data_limit->add(mode, static_cast<DataLimit::size_type>(size));
2767 if (state > DataLimit::None)
2769 return true;
2770 }
2771
2772 // Handle a DataLimit event.
2774 {
2776 << " DATA LIMIT " << DataLimit::mode_str(mode)
2777 << ' ' << DataLimit::state_str(state)
2778 << " key_id=" << key_id_);
2779
2780 // State values:
2781 // DataLimit::Green -- first packet received and decrypted.
2782 // DataLimit::Red -- data limit has been exceeded, so trigger a renegotiation.
2783 if (state == DataLimit::Red)
2785
2786 // When we are in KEV_PRIMARY_PENDING state, we must receive at least
2787 // one packet from the peer on this key before we transition to
2788 // KEV_BECOME_PRIMARY so we can transmit on it.
2789 if (next_event == KEV_PRIMARY_PENDING && data_limit->is_decrypt_green())
2790 set_event(KEV_NONE, KEV_BECOME_PRIMARY, *now + Time::Duration::seconds(1));
2791 }
2792
2793 // Should we enter KEV_PRIMARY_PENDING state? Do it if:
2794 // 1. we are a client,
2795 // 2. data limit is enabled,
2796 // 3. this is a renegotiated key in secondary context, i.e. not the first key, and
2797 // 4. no data received yet from peer on this key.
2798 bool data_limit_defer() const
2799 {
2800 return !proto.is_server()
2801 && data_limit
2802 && key_id_
2803 && !data_limit->is_decrypt_green();
2804 }
2805
2806 // General expiration set when key hits data limit threshold.
2808 {
2809 return *now + (proto.config->handshake_window * 2);
2810 }
2811
2813 {
2816 reached_active() + proto.config->become_primary);
2817 }
2818
2820 {
2821 if (*now >= next_event_time)
2822 {
2823 switch (next_event)
2824 {
2825 case KEV_BECOME_PRIMARY:
2826 if (data_limit_defer())
2828 else
2831 construct_time + proto.config->renegotiate);
2832 break;
2833 case KEV_RENEGOTIATE:
2836 break;
2837 case KEV_NEGOTIATE:
2839 break;
2842 break;
2843 case KEV_EXPIRE:
2845 break;
2846 default:
2847 break;
2848 }
2849 }
2850 }
2851
2852 void kev_error(const EventType ev, const Error::Type reason)
2853 {
2854 proto.stats->error(reason);
2855 invalidate(reason);
2856 set_event(ev);
2857 }
2858
2859 unsigned int initial_op(const bool sender, const bool tls_crypt_v2) const
2860 {
2861 if (key_id_)
2862 {
2863 return CONTROL_SOFT_RESET_V1;
2864 }
2865 else
2866 {
2867 if (proto.is_server() == sender)
2869
2870 if (!tls_crypt_v2)
2872 else
2874 }
2875 }
2876
2878 {
2879 Packet pkt;
2882 raw_send(std::move(pkt));
2883 }
2884
2886 {
2887 /* The data in the early negotiation packet is structured as
2888 * TLV (type, length, value) */
2889
2890 Buffer buf = pkt.buffer();
2891 while (!buf.empty())
2892 {
2893 if (buf.size() < 4)
2894 {
2895 /* Buffer does not have enough bytes for type (uint16) and length (uint16) */
2896 return false;
2897 }
2898
2899 uint16_t type = read_uint16_length(buf);
2900 uint16_t len = read_uint16_length(buf);
2901
2902 /* TLV defines a length that is larger than the remainder in the buffer. */
2903 if (buf.size() < len)
2904 return false;
2905
2906 if (type == EARLY_NEG_FLAGS)
2907 {
2908 if (len != 2)
2909 return false;
2910 uint16_t flags = read_uint16_length(buf);
2911
2913 {
2914 resend_wkc = true;
2915 }
2916 }
2917 else
2918 {
2919 /* skip over unknown types. We rather ignore undefined TLV to
2920 * not needing to add bits initial reset message (where space
2921 * is really tight) for optional features. */
2922 buf.advance(len);
2923 }
2924 }
2925 return true;
2926 }
2927
2928
2929 void raw_recv(Packet &&raw_pkt) // called by ProtoStackBase
2930 {
2931 if (raw_pkt.opcode == initial_op(false, proto.tls_wrap_mode == TLS_CRYPT_V2))
2932 {
2933 switch (state)
2934 {
2935 case C_WAIT_RESET:
2937 if (!parse_early_negotiation(raw_pkt))
2938 {
2940 }
2941 break;
2942 case S_WAIT_RESET:
2943 send_reset();
2945 break;
2946 }
2947 }
2948 }
2949
2950 void app_recv(BufferPtr &&to_app_buf) // called by ProtoStackBase
2951 {
2952 app_recv_buf.put(std::move(to_app_buf));
2954 throw proto_error("app_recv: received control message is too large");
2956 switch (state)
2957 {
2958 case C_WAIT_AUTH:
2959 if (recv_auth_complete(bcc))
2960 {
2961 recv_auth(bcc.get());
2963 }
2964 break;
2965 case S_WAIT_AUTH:
2966 if (recv_auth_complete(bcc))
2967 {
2968 recv_auth(bcc.get());
2969 send_auth();
2971 }
2972 break;
2973 case S_WAIT_AUTH_ACK:
2974 // rare case where client receives auth, goes ACTIVE,
2975 // but the ACK response is dropped
2976 case ACTIVE:
2977 if (bcc.advance_to_null()) // does composed buffer contain terminating null char?
2978 proto.app_recv(key_id_, bcc.get());
2979 break;
2980 }
2981 }
2982
2983 void net_send(const Packet &net_pkt, const Base::NetSendType nstype) // called by ProtoStackBase
2984 {
2985 if (!is_reliable || nstype != Base::NET_SEND_RETRANSMIT) // retransmit packets on UDP only, not TCP
2986 proto.net_send(key_id_, net_pkt);
2987 }
2988
2990 {
2992 {
2993 switch (state)
2994 {
2995 case C_WAIT_RESET_ACK:
2997 send_auth();
2999 break;
3000 case S_WAIT_RESET_ACK:
3003 break;
3004 case C_WAIT_AUTH_ACK:
3005 active();
3007 break;
3008 case S_WAIT_AUTH_ACK:
3009 active();
3011 break;
3012 }
3013 }
3014 }
3015
3017 {
3018 auto buf = BufferAllocatedRc::Create();
3019 proto.config->frame->prepare(Frame::WRITE_SSL_CLEARTEXT, *buf);
3020 buf->write(proto_context_private::auth_prefix, sizeof(proto_context_private::auth_prefix));
3022 tlsprf->self_write(*buf);
3023 const std::string options = proto.config->options_string();
3024 write_auth_string(options, *buf);
3025 if (!proto.is_server())
3026 {
3027 OVPN_LOG_INFO("Tunnel Options:" << options);
3028 buf->add_flags(BufAllocFlags::DESTRUCT_ZERO);
3029 if (proto.config->xmit_creds)
3030 proto.client_auth(*buf);
3031 else
3032 {
3033 write_empty_string(*buf); // username
3034 write_empty_string(*buf); // password
3035 }
3036 const std::string peer_info = proto.config->peer_info_string(proto.proto_callback->supports_epoch_data());
3037 write_auth_string(peer_info, *buf);
3038 }
3039 app_send_validate(std::move(buf));
3040 dirty = true;
3041 }
3042
3044 {
3045 const unsigned char *buf_pre = buf->read_alloc(sizeof(proto_context_private::auth_prefix));
3046 if (std::memcmp(buf_pre, proto_context_private::auth_prefix, sizeof(proto_context_private::auth_prefix)))
3047 throw proto_error("bad_auth_prefix");
3048 tlsprf->peer_read(*buf);
3049 const std::string options = read_auth_string<std::string>(*buf);
3050 if (proto.is_server())
3051 {
3052 const std::string username = read_auth_string<std::string>(*buf);
3053 const SafeString password = read_auth_string<SafeString>(*buf);
3054 const std::string peer_info = read_auth_string<std::string>(*buf);
3055 proto.proto_callback->server_auth(username, password, peer_info, Base::auth_cert());
3056 }
3057 }
3058
3059 // return true if complete recv_auth message is contained in buffer
3061 {
3062 if (!bc.advance(sizeof(proto_context_private::auth_prefix)))
3063 return false;
3064 if (!tlsprf->peer_read_complete(bc))
3065 return false;
3066 if (!bc.advance_string()) // options
3067 return false;
3068 if (proto.is_server())
3069 {
3070 if (!bc.advance_string()) // username
3071 return false;
3072 if (!bc.advance_string()) // password
3073 return false;
3074 if (!bc.advance_string()) // peer_info
3075 return false;
3076 }
3077 return true;
3078 }
3079
3080 void active()
3081 {
3082 OVPN_LOG_INFO("TLS Handshake: " << Base::ssl_handshake_details());
3083
3084 /* Our internal state machine only decides after push request what protocol
3085 * options we want to use. Therefore we also have to postpone data key
3086 * generation until this happens, create a empty DataChannelKey as
3087 * placeholder */
3088 data_channel_key.reset(new DataChannelKey());
3089 if (!proto.dc_deferred)
3091
3092 while (!app_pre_write_queue.empty())
3093 {
3094 app_send_validate(std::move(app_pre_write_queue.front()));
3095 app_pre_write_queue.pop_front();
3096 dirty = true;
3097 }
3100 active_event();
3101 }
3102
3103 void prepend_dest_psid_and_acks(Buffer &buf, unsigned int opcode)
3104 {
3105 // if sending ACKs, prepend dest PSID
3106 if (xmit_acks.acks_ready())
3107 {
3108 if (proto.psid_peer.defined())
3109 proto.psid_peer.prepend(buf);
3110 else
3111 {
3113 throw proto_error("peer_psid_undef");
3114 }
3115 }
3116
3117 // prepend ACKs for messages received from peer
3118 xmit_acks.prepend(buf, opcode == ACK_V1);
3119 }
3120
3121 bool verify_src_psid(const ProtoSessionID &src_psid)
3122 {
3123 if (proto.psid_peer.defined())
3124 {
3125 if (!proto.psid_peer.match(src_psid))
3126 {
3128 if (proto.is_tcp())
3130 return false;
3131 }
3132 }
3133 else
3134 {
3135 proto.psid_peer = src_psid;
3136 }
3137 return true;
3138 }
3139
3141 {
3142 ProtoSessionID dest_psid(buf);
3143 if (!proto.psid_self.match(dest_psid))
3144 {
3146 if (proto.is_tcp())
3148 return false;
3149 }
3150 return true;
3151 }
3152
3153 void gen_head_tls_auth(const unsigned int opcode, Buffer &buf)
3154 {
3155 // write tls-auth packet ID
3157
3158 // make space for tls-auth HMAC
3160
3161 // write source PSID
3162 proto.psid_self.prepend(buf);
3163
3164 // write opcode
3165 buf.push_front(op_compose(opcode, key_id_));
3166
3167 // write hmac
3169 buf.size(),
3173 }
3174
3175 void gen_head_tls_crypt(const unsigned int opcode, BufferAllocated &buf)
3176 {
3177 // in 'work' we store all the fields that are not supposed to be encrypted
3178 proto.config->frame->prepare(Frame::ENCRYPT_WORK, work);
3179 // make space for HMAC
3181 // write tls-crypt packet ID
3183 // write source PSID
3185 // write opcode
3187
3188 // compute HMAC using header fields (from 'work') and plaintext
3189 // payload (from 'buf')
3192 buf.c_data(),
3193 buf.size());
3194
3195 const size_t data_offset = TLSCryptContext::hmac_offset + proto.hmac_size;
3196
3197 // encrypt the content of 'buf' (packet payload) into 'work'
3198 const size_t encrypt_bytes = proto.tls_crypt_send->encrypt(work.c_data() + TLSCryptContext::hmac_offset,
3199 work.data() + data_offset,
3200 work.max_size() - data_offset,
3201 buf.c_data(),
3202 buf.size());
3203 if (!encrypt_bytes)
3204 {
3205 buf.reset_size();
3206 return;
3207 }
3208 work.inc_size(encrypt_bytes);
3209
3210 // append WKc to wrapped packet for tls-crypt-v2
3211 if ((opcode == CONTROL_HARD_RESET_CLIENT_V3 || opcode == CONTROL_WKC_V1)
3214
3215 // 'work' now contains the complete packet ready to go. swap it with 'buf'
3216 buf.swap(work);
3217 }
3218
3219 void gen_head_tls_plain(const unsigned int opcode, Buffer &buf)
3220 {
3221 // write source PSID
3222 proto.psid_self.prepend(buf);
3223 // write opcode
3224 buf.push_front(op_compose(opcode, key_id_));
3225 }
3226
3227 void gen_head(const unsigned int opcode, BufferAllocated &buf)
3228 {
3229 switch (proto.tls_wrap_mode)
3230 {
3231 case TLS_AUTH:
3232 gen_head_tls_auth(opcode, buf);
3233 break;
3234 case TLS_CRYPT:
3235 case TLS_CRYPT_V2:
3236 gen_head_tls_crypt(opcode, buf);
3237 break;
3238 case TLS_PLAIN:
3239 gen_head_tls_plain(opcode, buf);
3240 break;
3241 }
3242 }
3243
3244 void encapsulate(id_t id, Packet &pkt) // called by ProtoStackBase
3245 {
3246 BufferAllocated &buf = *pkt.buf;
3247
3248 // prepend message sequence number
3249 ReliableAck::prepend_id(buf, id);
3250
3251 // prepend dest PSID and ACKs to reply to peer
3253
3254 // generate message head
3255 int opcode = pkt.opcode;
3256 if (id == 1 && resend_wkc)
3257 {
3258 opcode = CONTROL_WKC_V1;
3259 }
3260
3261 gen_head(opcode, buf);
3262 }
3263
3264 void generate_ack(Packet &pkt) // called by ProtoStackBase
3265 {
3266 BufferAllocated &buf = *pkt.buf;
3267
3268 // prepend dest PSID and ACKs to reply to peer
3270
3271 gen_head(ACK_V1, buf);
3272 }
3273
3275 {
3276 Buffer &recv = *pkt.buf;
3277
3278 // update our last-packet-received time
3280
3281 // verify source PSID
3282 if (!verify_src_psid(src_psid))
3283 return false;
3284
3285 // get current time_t
3287 // verify tls_auth/crypt packet ID
3288 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
3289
3290 // process ACKs sent by peer (if packet ID check failed,
3291 // read the ACK IDs, but don't modify the rel_send object).
3292 if (ReliableAck::ack(rel_send, recv, pid_ok))
3293 {
3294 // make sure that our own PSID is contained in packet received from peer
3295 if (!verify_dest_psid(recv))
3296 return false;
3297 }
3298
3299 // for CONTROL packets only, not ACK
3300 if (pkt.opcode != ACK_V1)
3301 {
3302 // get message sequence number
3303 const id_t id = ReliableAck::read_id(recv);
3304
3305 if (pid_ok)
3306 {
3307 // try to push message into reliable receive object
3308 const unsigned int rflags = rel_recv.receive(pkt, id);
3309
3310 // should we ACK packet back to sender?
3311 if (rflags & ReliableRecv::ACK_TO_SENDER)
3312 xmit_acks.push_back(id); // ACK packet to sender
3313
3314 // was packet accepted by reliable receive object?
3315 if (rflags & ReliableRecv::IN_WINDOW)
3316 {
3317 // remember tls_auth packet ID so that it can't be replayed
3318 proto.ta_pid_recv.test_add(pid, t, true);
3319 return true;
3320 }
3321 }
3322 else // treat as replay
3323 {
3325 if (pid.is_valid())
3326 // even replayed packets must be ACKed or protocol could deadlock
3327 xmit_acks.push_back(id);
3328 }
3329 }
3330 else
3331 {
3332 if (pid_ok)
3333 // remember tls_auth packet ID of ACK packet to prevent replay
3334 proto.ta_pid_recv.test_add(pid, t, true);
3335 else
3337 }
3338 return false;
3339 }
3340
3342 {
3343 Buffer &recv = *pkt.buf;
3344 const unsigned char *orig_data = recv.data();
3345 const size_t orig_size = recv.size();
3346
3347 // advance buffer past initial op byte
3348 recv.advance(1);
3349
3350 // get source PSID
3351 ProtoSessionID src_psid(recv);
3352
3353 // verify HMAC
3354 {
3355 recv.advance(proto.hmac_size);
3356 if (!proto.ta_hmac_recv->ovpn_hmac_cmp(orig_data,
3357 orig_size,
3361 {
3363 if (proto.is_tcp())
3365 return false;
3366 }
3367 }
3368
3369 // read tls_auth packet ID
3370 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
3371
3372 return decapsulate_post_process(pkt, src_psid, pid);
3373 }
3374
3376 {
3377 auto &recv = *pkt.buf;
3378 const unsigned char *orig_data = recv.data();
3379 const size_t orig_size = recv.size();
3380
3381 // advance buffer past initial op byte
3382 recv.advance(1);
3383 // get source PSID
3384 ProtoSessionID src_psid(recv);
3385 // get tls-crypt packet ID
3386 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
3387 // skip the hmac
3388 recv.advance(proto.hmac_size);
3389
3390 const size_t data_offset = TLSCryptContext::hmac_offset + proto.hmac_size;
3391 if (orig_size < data_offset)
3392 return false;
3393
3394 // decrypt payload
3395 proto.config->frame->prepare(Frame::DECRYPT_WORK, work);
3396
3397 const size_t decrypt_bytes = proto.tls_crypt_recv->decrypt(orig_data + TLSCryptContext::hmac_offset,
3398 work.data(),
3399 work.max_size(),
3400 recv.c_data(),
3401 recv.size());
3402 if (!decrypt_bytes)
3403 {
3405 if (proto.is_tcp())
3407 return false;
3408 }
3409
3410 work.inc_size(decrypt_bytes);
3411
3412 // verify HMAC
3413 if (!proto.tls_crypt_recv->hmac_cmp(orig_data,
3415 work.c_data(),
3416 work.size()))
3417 {
3419 if (proto.is_tcp())
3421 return false;
3422 }
3423
3424 // move the decrypted payload to 'recv', so that the processing of the
3425 // packet can continue
3426 recv.swap(work);
3427
3428 return decapsulate_post_process(pkt, src_psid, pid);
3429 }
3430
3432 {
3433 Buffer &recv = *pkt.buf;
3434
3435 // update our last-packet-received time
3437
3438 // advance buffer past initial op byte
3439 recv.advance(1);
3440
3441 // verify source PSID
3442 ProtoSessionID src_psid(recv);
3443 if (!verify_src_psid(src_psid))
3444 return false;
3445
3446 // process ACKs sent by peer
3447 if (ReliableAck::ack(rel_send, recv, true))
3448 {
3449 // make sure that our own PSID is in packet received from peer
3450 if (!verify_dest_psid(recv))
3451 return false;
3452 }
3453
3454 // for CONTROL packets only, not ACK
3455 if (pkt.opcode != ACK_V1)
3456 {
3457 // get message sequence number
3458 const id_t id = ReliableAck::read_id(recv);
3459
3460 // try to push message into reliable receive object
3461 const unsigned int rflags = rel_recv.receive(pkt, id);
3462
3463 // should we ACK packet back to sender?
3464 if (rflags & ReliableRecv::ACK_TO_SENDER)
3465 xmit_acks.push_back(id); // ACK packet to sender
3466
3467 // was packet accepted by reliable receive object?
3468 if (rflags & ReliableRecv::IN_WINDOW)
3469 return true;
3470 }
3471 return false;
3472 }
3473
3474 bool decapsulate(Packet &pkt) // called by ProtoStackBase
3475 {
3476 try
3477 {
3478 if (proto.is_server()
3480 && proto.config->tls_crypt_v2_enabled()
3482 {
3483 // setup key to be used to unwrap WKc upon client connection.
3484 // tls-crypt session key setup is postponed to reception of WKc
3485 // from client
3487
3489 proto.hmac_size = proto.config->tls_crypt_context->digest_size();
3490
3491 // init tls_crypt packet ID
3493 proto.ta_pid_recv.init("SSL-CC", 0, proto.stats);
3494 }
3495
3496 switch (proto.tls_wrap_mode)
3497 {
3498 case TLS_AUTH:
3499 return decapsulate_tls_auth(pkt);
3500 case TLS_CRYPT_V2:
3502 {
3503 // unwrap WKc and extract Kc (client key) from packet.
3504 // This way we can initialize the tls-crypt per-client contexts
3505 // (this happens on the server side only)
3506 OpenVPNStaticKey client_key;
3507 const Error::Type unwrap_wkc_result = unwrap_tls_crypt_wkc(*pkt.buf,
3508 *proto.config,
3511 switch (unwrap_wkc_result)
3512 {
3514 case Error::HMAC_ERROR:
3515 proto.stats->error(unwrap_wkc_result);
3516 if (proto.is_tcp())
3517 invalidate(unwrap_wkc_result);
3518 return false;
3520 proto.stats->error(unwrap_wkc_result);
3521 return false;
3522 case Error::SUCCESS:
3523 break;
3524 default:
3525 return false;
3526 }
3527
3528 // WKc has been authenticated: it contains the client key followed
3529 // by the optional metadata. Let's initialize the tls-crypt context
3530 // with the client key
3531 proto.reset_tls_crypt(*proto.config, proto.config->wrapped_tls_crypt_key);
3532 }
3533 // now that the tls-crypt contexts have been initialized it is
3534 // possible to proceed with the standard tls-crypt decapsulation
3535 /* no break */
3536 case TLS_CRYPT:
3537 return decapsulate_tls_crypt(pkt);
3538 case TLS_PLAIN:
3539 return decapsulate_tls_plain(pkt);
3540 }
3541 }
3542 catch (const BufferException &)
3543 {
3545 if (proto.is_tcp())
3547 }
3548 return false;
3549 }
3550
3551 // for debugging
3552 static const char *state_string(const int s)
3553 {
3554 switch (s)
3555 {
3556 case C_WAIT_RESET_ACK:
3557 return "C_WAIT_RESET_ACK";
3558 case C_WAIT_AUTH_ACK:
3559 return "C_WAIT_AUTH_ACK";
3560 case S_WAIT_RESET_ACK:
3561 return "S_WAIT_RESET_ACK";
3562 case S_WAIT_AUTH_ACK:
3563 return "S_WAIT_AUTH_ACK";
3564 case C_INITIAL:
3565 return "C_INITIAL";
3566 case C_WAIT_RESET:
3567 return "C_WAIT_RESET";
3568 case C_WAIT_AUTH:
3569 return "C_WAIT_AUTH";
3570 case S_INITIAL:
3571 return "S_INITIAL";
3572 case S_WAIT_RESET:
3573 return "S_WAIT_RESET";
3574 case S_WAIT_AUTH:
3575 return "S_WAIT_AUTH";
3576 case ACTIVE:
3577 return "ACTIVE";
3578 default:
3579 return "STATE_UNDEF";
3580 }
3581 }
3582
3583 // for debugging
3584 int seconds_until(const Time &next_time)
3585 {
3586 Time::Duration d = next_time - *now;
3587 if (d.is_infinite())
3588 return -1;
3589 else
3590 return numeric_cast<int>(d.to_seconds());
3591 }
3592
3593 // BEGIN KeyContext data members
3594
3597 unsigned int key_id_;
3598 unsigned int crypto_flags;
3599 int remote_peer_id; // -1 to disable
3601 /* early negotiation enabled resending of wrapped tls-crypt-v2 client key
3602 * with third packet of the three-way handshake
3603 */
3604 bool resend_wkc = false;
3605 bool dirty;
3616 std::deque<BufferPtr> app_pre_write_queue;
3617 std::unique_ptr<DataChannelKey> data_channel_key;
3619 std::unique_ptr<DataLimit> data_limit;
3621
3622 // static member used by validate_tls_crypt()
3624 };
3625
3627 {
3628 public:
3629 PsidCookieHelper(unsigned int op_field)
3630 : op_code_(opcode_extract(op_field)), key_id_(key_id_extract(op_field))
3631 {
3632 }
3633
3635 {
3636 return key_id_ == 0 && (op_code_ == CONTROL_HARD_RESET_CLIENT_V2 || op_code_ == CONTROL_HARD_RESET_CLIENT_V3);
3637 }
3638
3640 bool is_tls_crypt_v2() const noexcept
3641 {
3642 return op_code_ == CONTROL_HARD_RESET_CLIENT_V3 || op_code_ == CONTROL_WKC_V1;
3643 }
3644
3646 bool supports_early_negotiation(const PacketIDControl &pidc) const noexcept
3647 {
3648 return (pidc.id & EARLY_NEG_MASK) == EARLY_NEG_START;
3649 }
3650
3652 {
3653 return key_id_ == 0 && (op_code_ == CONTROL_V1 || op_code_ == ACK_V1 || op_code_ == CONTROL_WKC_V1);
3654 }
3655
3657 static void prepend_TLV(Buffer &payload)
3658 {
3659 // The only supported TLV payload for now.
3660 const uint16_t type = htons(EARLY_NEG_FLAGS);
3661 const uint16_t len = htons(sizeof(uint16_t));
3662 const uint16_t flags = htons(EARLY_NEG_FLAG_RESEND_WKC);
3663
3664 payload.prepend(&flags, sizeof(flags));
3665 payload.prepend(&len, sizeof(len));
3666 payload.prepend(&type, sizeof(type));
3667 }
3668
3669 static unsigned char get_server_hard_reset_opfield()
3670 {
3671 return op_compose(CONTROL_HARD_RESET_SERVER_V2, 0);
3672 }
3673
3674 private:
3675 const unsigned int op_code_;
3676 const unsigned int key_id_;
3677 };
3678
3680 {
3681 public:
3682 IvProtoHelper(const OptionList &peer_info)
3683 : proto_field_(peer_info.get_num<unsigned int>("IV_PROTO", 1, 0))
3684 {
3685 }
3686
3688 {
3689 return proto_field_ & iv_proto_flag::IV_PROTO_TLS_KEY_EXPORT;
3690 }
3691
3693 {
3694 return proto_field_ & iv_proto_flag::IV_PROTO_AUTH_FAIL_TEMP;
3695 }
3696
3698 {
3699 return proto_field_ & iv_proto_flag::IV_PROTO_DATA_V2;
3700 }
3701
3703 {
3704 return proto_field_ & iv_proto_flag::IV_PROTO_AUTH_PENDING_KW;
3705 }
3706
3708 {
3709 return proto_field_ & iv_proto_flag::IV_PROTO_PUSH_UPDATE;
3710 }
3711
3713 {
3714 return proto_field_ & iv_proto_flag::IV_PROTO_REQUEST_PUSH;
3715 }
3716
3719 {
3720 return proto_field_ & iv_proto_flag::IV_PROTO_CC_EXIT_NOTIFY;
3721 }
3722
3725 {
3726 return proto_field_ & iv_proto_flag::IV_PROTO_DYN_TLS_CRYPT;
3727 }
3728
3731 {
3732 return proto_field_ & iv_proto_flag::IV_PROTO_DNS_OPTION_V2;
3733 }
3734
3735 private:
3736 unsigned int proto_field_;
3737 };
3738
3739 class TLSWrapPreValidate : public RC<thread_unsafe_refcount>
3740 {
3741 public:
3743
3744 virtual bool validate(const BufferAllocated &net_buf) = 0;
3745 };
3746
3747 // Validate the integrity of a packet, only considering tls-auth HMAC.
3749 {
3750 public:
3751 OPENVPN_SIMPLE_EXCEPTION(tls_auth_pre_validate);
3752
3753 TLSAuthPreValidate(const ProtoConfig &c, const bool server)
3754 {
3755 if (!c.tls_auth_enabled())
3756 throw tls_auth_pre_validate();
3757
3758 // save hard reset op we expect to receive from peer
3759 reset_op = server ? CONTROL_HARD_RESET_CLIENT_V2 : CONTROL_HARD_RESET_SERVER_V2;
3760
3761 // init OvpnHMACInstance
3762 ta_hmac_recv = c.tls_auth_context->new_obj();
3763
3764 // init tls_auth hmac
3765 if (c.key_direction >= 0)
3766 {
3767 // key-direction is 0 or 1
3768 const unsigned int key_dir = c.key_direction
3769 ? OpenVPNStaticKey::INVERSE
3770 : OpenVPNStaticKey::NORMAL;
3771 ta_hmac_recv->init(c.tls_auth_key.slice(OpenVPNStaticKey::HMAC | OpenVPNStaticKey::DECRYPT | key_dir));
3772 }
3773 else
3774 {
3775 // key-direction bidirectional mode
3776 ta_hmac_recv->init(c.tls_auth_key.slice(OpenVPNStaticKey::HMAC));
3777 }
3778 }
3779
3780 bool validate(const BufferAllocated &net_buf)
3781 {
3782 try
3783 {
3784 if (net_buf.empty())
3785 return false;
3786
3787 const unsigned int op = net_buf[0];
3788 if (opcode_extract(op) != reset_op || key_id_extract(op) != 0)
3789 return false;
3790
3791 return ta_hmac_recv->ovpn_hmac_cmp(net_buf.c_data(),
3792 net_buf.size(),
3793 OPCODE_SIZE + ProtoSessionID::SIZE,
3794 ta_hmac_recv->output_size(),
3795 PacketIDControl::size());
3796 }
3797 catch (const BufferException &)
3798 {
3799 }
3800
3801 return false;
3802 }
3803
3804 private:
3806 unsigned int reset_op;
3807 };
3808
3810 {
3811 public:
3812 OPENVPN_SIMPLE_EXCEPTION(tls_crypt_pre_validate);
3813
3814 TLSCryptPreValidate(const ProtoConfig &c, const bool server)
3815 {
3816 const bool tls_crypt_v2_enabled = c.tls_crypt_v2_enabled();
3817
3818 if (!c.tls_crypt_enabled() && !tls_crypt_v2_enabled)
3819 throw tls_crypt_pre_validate();
3820
3821 // save hard reset op we expect to receive from peer
3822 reset_op = CONTROL_HARD_RESET_SERVER_V2;
3823
3824 if (server)
3825 {
3826 // We can't pre-validate because we haven't extracted the server key from
3827 // the server key ID that's present in the client key yet.
3828 if (tls_crypt_v2_enabled && c.tls_crypt_v2_serverkey_id)
3829 {
3830 disabled = true;
3831 return;
3832 }
3833
3834 reset_op = tls_crypt_v2_enabled
3835 ? CONTROL_HARD_RESET_CLIENT_V3
3836 : CONTROL_HARD_RESET_CLIENT_V2;
3837 }
3838
3839 tls_crypt_recv = c.tls_crypt_context->new_obj_recv();
3840
3841 // static direction assignment - not user configurable
3842 const unsigned int key_dir = server ? OpenVPNStaticKey::NORMAL : OpenVPNStaticKey::INVERSE;
3843 tls_crypt_recv->init(c.ssl_factory->libctx(),
3844 c.tls_crypt_key.slice(OpenVPNStaticKey::HMAC | OpenVPNStaticKey::DECRYPT | key_dir),
3845 c.tls_crypt_key.slice(OpenVPNStaticKey::CIPHER | OpenVPNStaticKey::DECRYPT | key_dir));
3846
3847 // needed to create the decrypt buffer during validation
3848 frame = c.frame;
3849 }
3850
3851 bool validate(const BufferAllocated &net_buf)
3852 {
3853 if (disabled)
3854 return true;
3855
3856 try
3857 {
3858 if (net_buf.empty())
3859 return false;
3860
3861 const unsigned int op = net_buf[0];
3862 if (opcode_extract(op) != reset_op || key_id_extract(op) != 0)
3863 return false;
3864
3865 const size_t data_offset = TLSCryptContext::hmac_offset + tls_crypt_recv->output_hmac_size();
3866 if (net_buf.size() < data_offset)
3867 return false;
3868
3869 frame->prepare(Frame::DECRYPT_WORK, work);
3870
3871 // decrypt payload from 'net_buf' into 'work'
3872 const size_t decrypt_bytes = tls_crypt_recv->decrypt(net_buf.c_data() + TLSCryptContext::hmac_offset,
3873 work.data(),
3874 work.max_size(),
3875 net_buf.c_data() + data_offset,
3876 net_buf.size() - data_offset);
3877 if (!decrypt_bytes)
3878 return false;
3879
3880 work.inc_size(decrypt_bytes);
3881
3882 // verify HMAC
3883 return tls_crypt_recv->hmac_cmp(net_buf.c_data(),
3884 TLSCryptContext::hmac_offset,
3885 work.data(),
3886 work.size());
3887 }
3888 catch (const BufferException &)
3889 {
3890 }
3891 return false;
3892 }
3893
3894 protected:
3895 unsigned int reset_op;
3896
3897 private:
3901 bool disabled = false;
3902 };
3903
3904 OPENVPN_SIMPLE_EXCEPTION(select_key_context_error);
3905
3907 const ProtoConfig::Ptr &config_arg, // configuration
3908 const SessionStats::Ptr &stats_arg) // error stats
3909 : proto_callback(cb_arg),
3910 config(config_arg),
3911 stats(stats_arg),
3912 mode_(config_arg->ssl_factory->mode()),
3913 n_key_ids(0),
3914 now_(config_arg->now)
3915 {
3917 }
3918
3920 {
3921 // Prefer TLS auth as the default if both TLS crypt V2 and TLS auth
3922 // are enabled.
3923 if (c.tls_crypt_v2_enabled() && !c.tls_auth_enabled())
3924 {
3926
3927 // get HMAC size from Digest object
3929
3930 return;
3931 }
3932
3933 if (c.tls_crypt_enabled() && !c.tls_auth_enabled())
3934 {
3936
3937 // get HMAC size from Digest object
3939
3940 return;
3941 }
3942
3943 if (c.tls_auth_enabled())
3944 {
3946
3947 // get HMAC size from Digest object
3949
3950 return;
3951 }
3952
3954 hmac_size = 0;
3955 }
3956
3957 uint32_t get_tls_warnings() const
3958 {
3959 if (primary)
3960 return primary->get_tls_warnings();
3961
3962 OPENVPN_LOG("TLS: primary key context uninitialized. Can't retrieve TLS warnings");
3963 return 0;
3964 }
3965
3966 bool uses_bs64_cipher() const
3967 {
3968 return is_bs64_cipher(conf().dc.cipher());
3969 }
3970
3972 {
3975
3976 // static direction assignment - not user configurable
3978
3985 }
3986
3988 {
3989 OpenVPNStaticKey dyn_key;
3990 key_ctx->export_key_material(dyn_key, "EXPORTER-OpenVPN-dynamic-tls-crypt");
3991
3992 if (c.tls_auth_enabled())
3993 dyn_key.XOR(c.tls_auth_key);
3994 else if (c.tls_crypt_enabled() || c.tls_crypt_v2_enabled())
3995 dyn_key.XOR(c.tls_crypt_key);
3996
3998
3999 // get HMAC size from Digest object
4001
4002 ta_pid_send.init();
4003 ta_pid_recv.init("SSL-CC", 0, stats);
4004
4005 reset_tls_crypt(c, dyn_key);
4006 }
4007
4009 {
4010 // It is possible that the PSID/HMAC cookie logic has already set the TLS crypt V2
4011 // keys up, during the processing of the second packet. If so, just use them.
4013 {
4015 }
4016 else
4017 {
4018 // tls-crypt session key is derived later from WKc received from the client
4021
4022 // server context is used only to process incoming WKc's
4024
4026 {
4027 // the server key is composed by one key set only, therefore direction and
4028 // mode should not be specified when slicing
4032 }
4033 }
4034
4036 }
4037
4049 void reset(const ProtoSessionID cookie_psid = ProtoSessionID())
4050 {
4051 const ProtoConfig &c = *config;
4052
4053 // defer data channel initialization until after client options pull?
4055
4056 // clear key contexts
4057 reset_all();
4058
4059 // start with key ID 0
4060 upcoming_key_id = 0;
4061
4062 unsigned int key_dir;
4063
4064 // tls-auth initialization
4066 switch (tls_wrap_mode)
4067 {
4068 case TLS_CRYPT:
4070 // init tls_crypt packet ID
4071 ta_pid_send.init();
4072 ta_pid_recv.init("SSL-CC", 0, stats);
4073 break;
4074 case TLS_CRYPT_V2:
4075 if (is_server())
4076 // setup key to be used to unwrap WKc upon client connection.
4077 // tls-crypt session key setup is postponed to reception of WKc
4078 // from client
4080 else
4084 // init tls_crypt packet ID
4086 ta_pid_recv.init("SSL-CC", 0, stats);
4087 break;
4088 case TLS_AUTH:
4089 // init OvpnHMACInstance
4092
4093 // init tls_auth hmac
4094 if (c.key_direction >= 0)
4095 {
4096 // key-direction is 0 or 1
4100 }
4101 else
4102 {
4103 // key-direction bidirectional mode
4106 }
4107
4117 ta_pid_send.init(cookie_psid.defined() ? 1 : 0);
4118 ta_pid_recv.init("SSL-CC", 0, stats);
4119 break;
4120 case TLS_PLAIN:
4121 break;
4122 }
4123
4124 // initialize proto session ID
4125 if (cookie_psid.defined())
4126 psid_self = cookie_psid;
4127 else
4129 psid_peer.reset();
4130
4131 // initialize key contexts
4132 primary.reset(new KeyContext(*this, is_client(), cookie_psid.defined()));
4133 OVPN_LOG_VERBOSE(debug_prefix() << " New KeyContext PRIMARY id=" << primary->key_id());
4134
4135 // initialize keepalive timers
4136 keepalive_expire = Time::infinite(); // initially disabled
4137 update_last_sent(); // set timer for initial keepalive send
4138 }
4139
4140 void set_protocol(const Protocol &p)
4141 {
4142 config->set_protocol(p);
4143 if (primary)
4144 primary->set_protocol(p);
4145 if (secondary)
4146 secondary->set_protocol(p);
4147 }
4148
4149 // Free up space when parent object has been halted but
4150 // object destruction is not immediately scheduled.
4152 {
4153 reset_all();
4154 }
4155
4156 // Is primary key defined
4158 {
4159 return bool(primary);
4160 }
4161
4162 virtual ~ProtoContext() = default;
4163
4164 // return the PacketType of an incoming network packet
4166 {
4167 return PacketType(buf, *this);
4168 }
4169
4178 void start(const ProtoSessionID cookie_psid = ProtoSessionID())
4179 {
4180 if (!primary)
4181 throw proto_error("start: no primary key");
4182 primary->start(cookie_psid);
4183 update_last_received(); // set an upper bound on when we expect a response
4184 }
4185
4186 // trigger a protocol renegotiation
4188 {
4189 // set up dynamic tls-crypt keys when the first rekeying happens
4190 // primary key_id 0 indicates that it is the first rekey
4191 if (conf().dynamic_tls_crypt_enabled() && primary && primary->key_id() == 0)
4193
4194 // initialize secondary key context
4195 new_secondary_key(true);
4196 secondary->start();
4197 }
4198
4199 // Should be called at the end of sequence of send/recv
4200 // operations on underlying protocol object.
4201 // If control_channel is true, do a full flush.
4202 // If control_channel is false, optimize flush for data
4203 // channel only.
4204 void flush(const bool control_channel)
4205 {
4206 if (control_channel || process_events())
4207 {
4208 do
4209 {
4210 if (primary)
4211 primary->flush();
4212 if (secondary)
4213 secondary->flush();
4214 } while (process_events());
4215 }
4216 }
4217
4218 // Perform various time-based housekeeping tasks such as retransmiting
4219 // unacknowleged packets as part of the reliability layer and testing
4220 // for keepalive timouts.
4221 // Should be called at the time returned by next_housekeeping.
4223 {
4224 // handle control channel retransmissions on primary
4225 if (primary)
4226 primary->retransmit();
4227
4228 // handle control channel retransmissions on secondary
4229 if (secondary)
4230 secondary->retransmit();
4231
4232 // handle possible events
4233 flush(false);
4234
4235 // handle keepalive/expiration
4237 }
4238
4239 // When should we next call housekeeping?
4240 // Will return a time value for immediate execution
4241 // if session has been invalidated.
4243 {
4244 if (!invalidated())
4245 {
4247 if (primary)
4248 ret.min(primary->next_retransmit());
4249 if (secondary)
4250 ret.min(secondary->next_retransmit());
4251 ret.min(keepalive_xmit);
4252 ret.min(keepalive_expire);
4253 return ret;
4254 }
4255 else
4256 return Time();
4257 }
4258
4259 // send app-level cleartext to remote peer
4260
4262 {
4263 select_control_send_context().app_send(std::move(app_bp));
4264 }
4265
4267 {
4268 control_send(BufferAllocatedRc::Create(std::move(app_buf)));
4269 }
4270
4271 // validate a control channel network packet
4272 bool control_net_validate(const PacketType &type, const Buffer &net_buf)
4273 {
4274 return type.is_defined() && KeyContext::validate(net_buf, *this, now_);
4275 }
4276
4277 // pass received control channel network packets (ciphertext) into protocol object
4278 bool control_net_recv(const PacketType &type, BufferPtr &&net_bp)
4279 {
4280 Packet pkt(std::move(net_bp), type.opcode);
4281 if (type.is_soft_reset() && !renegotiate_request(pkt))
4282 return false;
4283 return select_key_context(type, true).net_recv(std::move(pkt));
4284 }
4285
4293 bool control_net_recv(const PacketType &type, BufferAllocated &&net_buf)
4294 {
4295 return control_net_recv(type, BufferAllocatedRc::Create(std::move(net_buf)));
4296 }
4297
4298 // encrypt a data channel packet using primary KeyContext
4300 {
4301 OVPN_LOG_DEBUG(debug_prefix() << " DATA ENCRYPT size=" << in_out.size());
4302 if (!primary)
4303 throw proto_error("data_encrypt: no primary key");
4304 primary->encrypt(in_out);
4305 }
4306
4307 // decrypt a data channel packet (automatically select primary
4308 // or secondary KeyContext based on packet content)
4309 bool data_decrypt(const PacketType &type, BufferAllocated &in_out)
4310 {
4311 bool ret = false;
4312
4313 OVPN_LOG_DEBUG(debug_prefix() << " DATA DECRYPT key_id=" << select_key_context(type, false).key_id() << " size=" << in_out.size());
4314
4315 select_key_context(type, false).decrypt(in_out);
4316
4317 // update time of most recent packet received
4318 if (!in_out.empty())
4319 {
4321 ret = true;
4322 }
4323
4324 // discard keepalive packets
4325 if (proto_context_private::is_keepalive(in_out))
4326 {
4327 in_out.reset_size();
4328 }
4329
4330 return ret;
4331 }
4332
4333 // enter disconnected state
4334 void disconnect(const Error::Type reason)
4335 {
4336 if (primary)
4337 primary->invalidate(reason);
4338 if (secondary)
4339 secondary->invalidate(reason);
4340 }
4341
4342 // normally used by UDP clients to tell the server that
4343 // they are disconnecting
4345 {
4346#ifndef OPENVPN_DISABLE_EXPLICIT_EXIT // explicit exit should always be enabled in production
4347 if (!is_client() || !is_udp() || !primary)
4348 {
4349 return;
4350 }
4351
4352 if (config->cc_exit_notify)
4353 {
4354 write_control_string(std::string("EXIT"));
4355 primary->flush();
4356 }
4357 else
4358 {
4359 primary->send_explicit_exit_notify();
4360 }
4361#endif // OPENVPN_DISABLE_EXPLICIT_EXIT
4362 }
4363
4364 // should be called after a successful network packet transmit
4366 {
4367 keepalive_xmit = *now_ + config->keepalive_ping;
4368 }
4369
4370 // Can we call data_encrypt or data_decrypt yet?
4371 // Returns true if primary data channel is in ACTIVE state.
4373 {
4374 return primary && primary->data_channel_ready();
4375 }
4376
4377 // total number of SSL/TLS negotiations during lifetime of ProtoContext object
4378 unsigned int negotiations() const
4379 {
4380 return n_key_ids;
4381 }
4382
4383 // worst-case handshake time
4384 const Time::Duration &slowest_handshake()
4385 {
4386 return slowest_handshake_;
4387 }
4388
4389 // was primary context invalidated by an exception?
4390 bool invalidated() const
4391 {
4392 return primary && primary->invalidated();
4393 }
4394
4395 // reason for invalidation if invalidated() above returns true
4397 {
4398 return primary->invalidation_reason();
4399 }
4400
4401 // Do late initialization of data channel, for example
4402 // on client after server push, or on server after client
4403 // capabilities are known.
4405 {
4406 dc_deferred = false;
4407
4408 // initialize data channel (crypto & compression)
4409 if (primary)
4410 primary->init_data_channel();
4411 if (secondary)
4412 secondary->init_data_channel();
4413 }
4414
4415 // Call on client with server-pushed options
4417 {
4418 // modify config with pushed options
4419 config->process_push(opt, pco);
4420
4421 // in case keepalive parms were modified by push
4423 }
4424
4425 // Return the current transport alignment adjustment
4426 size_t align_adjust_hint() const
4427 {
4428 return config->enable_op32 ? 0 : 1;
4429 }
4430
4431 // Return true if keepalive parameter(s) are enabled
4433 {
4434 return config->keepalive_ping.enabled()
4435 || config->keepalive_timeout.enabled();
4436 }
4437
4438 // Disable keepalive for rest of session,
4439 // but return the previous keepalive parameters.
4440 void disable_keepalive(unsigned int &keepalive_ping,
4441 unsigned int &keepalive_timeout)
4442 {
4443 keepalive_ping = config->keepalive_ping.enabled()
4444 ? clamp_to_typerange<std::remove_reference_t<decltype(keepalive_ping)>>(config->keepalive_ping.to_seconds())
4445 : 0;
4446 keepalive_timeout = config->keepalive_timeout.enabled()
4447 ? clamp_to_typerange<std::remove_reference_t<decltype(keepalive_timeout)>>(config->keepalive_timeout.to_seconds())
4448 : 0;
4449 config->keepalive_ping = Time::Duration::infinite();
4450 config->keepalive_timeout = Time::Duration::infinite();
4451 config->keepalive_timeout_early = Time::Duration::infinite();
4453 }
4454
4455 // Notify our component KeyContext when per-key Data Limits have been reached
4456 void data_limit_notify(const unsigned int key_id,
4457 const DataLimit::Mode cdl_mode,
4458 const DataLimit::State cdl_status)
4459 {
4460 if (primary && key_id == primary->key_id())
4461 primary->data_limit_notify(cdl_mode, cdl_status);
4462 else if (secondary && key_id == secondary->key_id())
4463 secondary->data_limit_notify(cdl_mode, cdl_status);
4464 }
4465
4466 // access the data channel settings
4468 {
4469 return config->dc;
4470 }
4471
4472 // reset the data channel factory
4474 {
4475 config->dc.reset();
4476 }
4477
4478 // set the local peer ID (or -1 to disable)
4479 void set_local_peer_id(const int local_peer_id)
4480 {
4481 config->local_peer_id = local_peer_id;
4482 }
4483
4484 // current time
4485 const Time &now() const
4486 {
4487 return *now_;
4488 }
4490 {
4491 now_->update();
4492 }
4493
4494 // frame
4495 const Frame &frame() const
4496 {
4497 return *config->frame;
4498 }
4499 const Frame::Ptr &frameptr() const
4500 {
4501 return config->frame;
4502 }
4503
4504 // client or server?
4505 const Mode &mode() const
4506 {
4507 return mode_;
4508 }
4509 bool is_server() const
4510 {
4511 return mode_.is_server();
4512 }
4513 bool is_client() const
4514 {
4515 return mode_.is_client();
4516 }
4517
4518 // tcp/udp mode
4519 bool is_tcp()
4520 {
4521 return config->protocol.is_tcp();
4522 }
4523 bool is_udp()
4524 {
4525 return config->protocol.is_udp();
4526 }
4527
4528 // configuration
4529 const ProtoConfig &conf() const
4530 {
4531 return *config;
4532 }
4534 {
4535 return *config;
4536 }
4538 {
4539 return config;
4540 }
4541
4542 // stats
4544 {
4545 return *stats;
4546 }
4547
4548 // debugging
4550 {
4551 return primary_state() == C_WAIT_RESET_ACK;
4552 }
4553
4554 protected:
4555 int primary_state() const
4556 {
4557 if (primary)
4558 return primary->get_state();
4559 else
4560 return STATE_UNDEF;
4561 }
4562
4563 private:
4564 // TLS wrapping mode for the control channel
4572
4573 static constexpr PacketIDControl::id_t EARLY_NEG_START = 0x0f000000;
4574 static constexpr PacketIDControl::id_t EARLY_NEG_MASK = 0xff000000;
4575
4577 {
4578 if (primary)
4580 primary.reset();
4581 secondary.reset();
4582 }
4583
4584 // Called on client to request username/password credentials.
4585 // delegated to the callback/parent
4587 {
4589 }
4590
4592 {
4593 keepalive_expire = *now_ + (data_channel_ready() ? config->keepalive_timeout : config->keepalive_timeout_early);
4594 }
4595
4596 void net_send(const unsigned int key_id, const Packet &net_pkt)
4597 {
4599 }
4600
4601 void app_recv(const unsigned int key_id, BufferPtr &&to_app_buf)
4602 {
4604 }
4605
4606 // we're getting a request from peer to renegotiate.
4608 {
4609 // set up dynamic tls-crypt keys when the first rekeying happens
4610 // primary key_id 0 indicates that it is the first rekey
4611 if (conf().dynamic_tls_crypt_enabled() && primary && primary->key_id() == 0)
4613
4614 if (KeyContext::validate(pkt.buffer(), *this, now_))
4615 {
4616 new_secondary_key(false);
4617 return true;
4618 }
4619 else
4620 return false;
4621 }
4622
4623 // select a KeyContext (primary or secondary) for received network packets
4624 KeyContext &select_key_context(const PacketType &type, const bool control)
4625 {
4627 if (!control)
4628 {
4629 if (flags == (PacketType::DEFINED) && primary)
4630 return *primary;
4632 return *secondary;
4633 }
4634 else
4635 {
4637 {
4638 return *primary;
4639 }
4641 && secondary)
4642 {
4643 return *secondary;
4644 }
4645 }
4646 throw select_key_context_error();
4647 }
4648
4649 // Select a KeyContext (primary or secondary) for control channel sends.
4650 // Even after new key context goes active, we still wait for
4651 // KEV_BECOME_PRIMARY event (controlled by the become_primary duration
4652 // in Config) before we use it for app-level control-channel
4653 // transmissions. Simulations have found this method to be more reliable
4654 // than the immediate rollover practiced by OpenVPN 2.x.
4656 {
4657 OVPN_LOG_VERBOSE(debug_prefix() << " CONTROL SEND");
4658 if (!primary)
4659 throw proto_error("select_control_send_context: no primary key");
4660 return *primary;
4661 }
4662
4663 // Possibly send a keepalive message, and check for expiration
4664 // of session due to lack of received packets from peer.
4666 {
4667 const Time now = *now_;
4668
4669 // check for keepalive timeouts
4670 if (now >= keepalive_xmit && primary)
4671 {
4672 primary->send_keepalive();
4674 }
4675 if (now >= keepalive_expire)
4676 {
4677 // no contact with peer, disconnect
4680 }
4681 }
4682
4683 // Process KEV_x events
4684 // Return true if any events were processed.
4686 {
4687 bool did_work = false;
4688
4689 // primary
4690 if (primary && primary->event_pending())
4691 {
4693 did_work = true;
4694 }
4695
4696 // secondary
4697 if (secondary && secondary->event_pending())
4698 {
4700 did_work = true;
4701 }
4702
4703 return did_work;
4704 }
4705
4706 // Create a new secondary key.
4707 // initiator --
4708 // false : remote renegotiation request
4709 // true : local renegotiation request
4710 void new_secondary_key(const bool initiator)
4711 {
4712 // Create the secondary
4713 secondary.reset(new KeyContext(*this, initiator));
4715 << " New KeyContext SECONDARY id=" << secondary->key_id()
4716 << (initiator ? " local-triggered" : " remote-triggered"));
4717 }
4718
4719 // Promote a newly renegotiated KeyContext to primary status.
4720 // This is usually triggered by become_primary variable (Time::Duration)
4721 // in Config.
4723 {
4725 if (primary)
4727 if (secondary)
4728 secondary->prepare_expire();
4729 OVPN_LOG_VERBOSE(debug_prefix() << " PRIMARY_SECONDARY_SWAP");
4730 }
4731
4733 {
4734 const KeyContext::EventType ev = primary->get_event();
4735 if (ev != KeyContext::KEV_NONE)
4736 {
4737 primary->reset_event();
4738 switch (ev)
4739 {
4741 OVPN_LOG_VERBOSE(debug_prefix() << " SESSION_ACTIVE");
4743 proto_callback->active(true);
4744 break;
4747 renegotiate();
4748 break;
4750 if (secondary && !secondary->invalidated())
4752 else
4753 {
4755 // primary context expired and no secondary context available
4757 }
4758 break;
4761 // primary negotiation failed
4763 break;
4764 default:
4765 break;
4766 }
4767 }
4768 primary->set_next_event_if_unspecified();
4769 }
4770
4772 {
4773 const KeyContext::EventType ev = secondary->get_event();
4774 if (ev != KeyContext::KEV_NONE)
4775 {
4776 secondary->reset_event();
4777 switch (ev)
4778 {
4781 if (primary)
4782 primary->prepare_expire();
4783 proto_callback->active(false);
4784 break;
4786 if (!secondary->invalidated())
4788 break;
4791 secondary.reset();
4792 break;
4794 if (primary)
4796 secondary->become_primary_time());
4797 break;
4800 [[fallthrough]];
4803 renegotiate();
4804 break;
4805 default:
4806 break;
4807 }
4808 }
4809 if (secondary)
4810 secondary->set_next_event_if_unspecified();
4811 }
4812
4813 std::string debug_prefix()
4814 {
4815 std::string ret = openvpn::to_string(now_->raw());
4816 ret += is_server() ? " SERVER[" : " CLIENT[";
4817 if (primary)
4818 ret += openvpn::to_string(primary->key_id());
4819 if (secondary)
4820 {
4821 ret += '/';
4822 ret += openvpn::to_string(secondary->key_id());
4823 }
4824 ret += ']';
4825 return ret;
4826 }
4827
4828 // key_id starts at 0, increments to KEY_ID_MASK, then recycles back to 1.
4829 // Therefore, if key_id is 0, it is the first key.
4830 unsigned int next_key_id()
4831 {
4832 ++n_key_ids;
4833 unsigned int ret = upcoming_key_id;
4834 if ((upcoming_key_id = (upcoming_key_id + 1) & KEY_ID_MASK) == 0)
4835 upcoming_key_id = 1;
4836 return ret;
4837 }
4838
4839 // call whenever keepalive parms are modified,
4840 // to reset timers
4842 {
4844
4845 // For keepalive_xmit timer, don't reschedule current cycle
4846 // unless it would fire earlier. Subsequent cycles will
4847 // time according to new keepalive_ping value.
4848 const Time kx = *now_ + config->keepalive_ping;
4849 if (kx < keepalive_xmit)
4850 keepalive_xmit = kx;
4851 }
4852
4854 {
4855 if (!config->wkc.defined())
4856 throw proto_error("Client Key Wrapper undefined");
4857 dst.append(config->wkc);
4858 }
4859
4860 // BEGIN ProtoContext data members
4861
4868
4871
4874 Mode mode_; // client or server
4875 unsigned int upcoming_key_id = 0;
4876 unsigned int n_key_ids;
4877
4878 TimePtr now_; // pointer to current time (a clone of config->now)
4879 Time keepalive_xmit; // time in future when we will transmit a keepalive (subject to continuous change)
4880 Time keepalive_expire; // time in future when we must have received a packet from peer or we will timeout session
4881
4882 Time::Duration slowest_handshake_; // longest time to reach a successful handshake
4883
4886
4889
4892
4895
4898
4901 bool dc_deferred = false;
4902
4903 // END ProtoContext data members
4904};
4905
4906} // namespace openvpn
4907
4908#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:1799
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:489
const char * peer_info_string() const
Definition compress.hpp:278
static bool is_any_stub(const Type t)
Definition compress.hpp:508
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:1194
T * prepend_alloc(const size_t size)
Allocate space for prepending data to the buffer.
Definition buffer.hpp:1597
void append(const B &other)
Append data from another buffer to this buffer.
Definition buffer.hpp:1626
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:1392
size_t max_size() const
Return the maximum allowable size value in T objects given the current offset (without considering re...
Definition buffer.hpp:1377
void prepend(const T *data, const size_t size)
Prepend data to the buffer.
Definition buffer.hpp:1575
size_t size() const
Returns the size of the buffer in T objects.
Definition buffer.hpp:1242
T * data()
Get a mutable pointer to the start of the array.
Definition buffer.hpp:1450
void advance(const size_t delta)
Advances the buffer by the specified delta.
Definition buffer.hpp:1277
bool empty() const
Returns true if the buffer is empty.
Definition buffer.hpp:1236
void write(const T *data, const size_t size)
Write data to the buffer.
Definition buffer.hpp:1563
auto * read_alloc(const size_t size)
Allocate memory and read data from the buffer into the allocated memory.
Definition buffer.hpp:1343
T pop_front()
Removes and returns the first element from the buffer.
Definition buffer.hpp:1256
void push_front(const T &value)
Append a T object to the array, with possible resize.
Definition buffer.hpp:1490
void set_size(const size_t size)
After an external method, operating on the array as a mutable unsigned char buffer,...
Definition buffer.hpp:1384
void null_terminate()
Null-terminate the array.
Definition buffer.hpp:1508
void reset_size()
Resets the size of the buffer to zero.
Definition buffer.hpp:1170
void read(NCT *data, const size_t size)
Read data from the buffer into the specified memory location.
Definition buffer.hpp:1331
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:264
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:1182
bool exists(const std::string &name) const
Definition options.hpp:1321
const std::string & get(const size_t index, const size_t max_len) const
Definition options.hpp:187
T get_num(const size_t idx) const
Definition options.hpp:222
size_t size() const
Definition options.hpp:327
void min_args(const size_t n) const
Definition options.hpp:129
const std::string & ref(const size_t i) const
Definition options.hpp:353
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:3730
bool client_supports_auth_pending_kwargs() const
Definition proto.hpp:3702
IvProtoHelper(const OptionList &peer_info)
Definition proto.hpp:3682
bool client_supports_temp_auth_failed() const
Definition proto.hpp:3692
bool client_supports_exit_notify() const
Checks if the client is able to send an explicit EXIT message before exiting.
Definition proto.hpp:3718
bool client_supports_dynamic_tls_crypt() const
Checks if the client can handle dynamic TLS-crypt.
Definition proto.hpp:3724
void encapsulate(id_t id, Packet &pkt)
Definition proto.hpp:3244
static const char * event_type_string(const EventType et)
Definition proto.hpp:1776
bool decapsulate_post_process(Packet &pkt, ProtoSessionID &src_psid, const PacketIDControl pid)
Definition proto.hpp:3274
void kev_error(const EventType ev, const Error::Type reason)
Definition proto.hpp:2852
static BufferAllocated static_work
Definition proto.hpp:3623
static bool validate(const Buffer &net_buf, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2139
void set_protocol(const Protocol &p)
Definition proto.hpp:1836
void prepend_dest_psid_and_acks(Buffer &buf, unsigned int opcode)
Definition proto.hpp:3103
TLSPRFInstance::Ptr tlsprf
Definition proto.hpp:3610
bool net_recv(Packet &&pkt)
Definition proto.hpp:1922
void set_state(const int newstate)
Definition proto.hpp:2700
std::deque< BufferPtr > app_pre_write_queue
Definition proto.hpp:3616
void recv_auth(BufferPtr buf)
Definition proto.hpp:3043
bool decapsulate_tls_plain(Packet &pkt)
Definition proto.hpp:3431
static bool validate_tls_plain(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2630
void app_recv(BufferPtr &&to_app_buf)
Definition proto.hpp:2950
void net_send(const Packet &net_pkt, const Base::NetSendType nstype)
Definition proto.hpp:2983
void app_send(BufferPtr &&bp)
Definition proto.hpp:1910
void set_event(const EventType current)
Definition proto.hpp:2708
void raw_recv(Packet &&raw_pkt)
Definition proto.hpp:2929
void gen_head(const unsigned int opcode, BufferAllocated &buf)
Definition proto.hpp:3227
std::unique_ptr< DataLimit > data_limit
Definition proto.hpp:3619
void prepare_expire(const EventType current_ev=KeyContext::KEV_NONE)
Definition proto.hpp:2001
void decrypt(BufferAllocated &buf)
Definition proto.hpp:1951
void send_data_channel_message(const unsigned char *data, const size_t size)
Definition proto.hpp:2117
void gen_head_tls_crypt(const unsigned int opcode, BufferAllocated &buf)
Definition proto.hpp:3175
void gen_head_tls_plain(const unsigned int opcode, Buffer &buf)
Definition proto.hpp:3219
void encrypt(BufferAllocated &buf)
Definition proto.hpp:1930
bool recv_auth_complete(BufferComplete &bc) const
Definition proto.hpp:3060
bool verify_src_psid(const ProtoSessionID &src_psid)
Definition proto.hpp:3121
void generate_ack(Packet &pkt)
Definition proto.hpp:3264
bool verify_dest_psid(Buffer &buf)
Definition proto.hpp:3140
Error::Type invalidation_reason() const
Definition proto.hpp:2058
bool parse_early_negotiation(const Packet &pkt)
Definition proto.hpp:2885
void calculate_mssfix(ProtoConfig &c)
Definition proto.hpp:2200
bool decapsulate_tls_crypt(Packet &pkt)
Definition proto.hpp:3375
static bool validate_tls_crypt(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2561
void start(const ProtoSessionID cookie_psid=ProtoSessionID())
Initialize the state machine and start protocol negotiation.
Definition proto.hpp:1853
void invalidate(const Error::Type reason)
Definition proto.hpp:1880
uint32_t get_tls_warnings() const
Definition proto.hpp:1841
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:2374
void gen_head_tls_auth(const unsigned int opcode, Buffer &buf)
Definition proto.hpp:3153
void app_send_validate(BufferPtr &&bp)
Definition proto.hpp:1902
OPENVPN_SIMPLE_EXCEPTION(tls_crypt_unwrap_wkc_error)
void data_limit_event(const DataLimit::Mode mode, const DataLimit::State state)
Definition proto.hpp:2773
CryptoDCInstance::Ptr crypto
Definition proto.hpp:3609
KeyContext(ProtoContext &p, const bool initiator, bool psid_cookie_mode=false)
Definition proto.hpp:1803
unsigned int key_id() const
Definition proto.hpp:2064
static bool validate_tls_auth(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2513
unsigned int initial_op(const bool sender, const bool tls_crypt_v2) const
Definition proto.hpp:2859
int seconds_until(const Time &next_time)
Definition proto.hpp:3584
static const char * state_string(const int s)
Definition proto.hpp:3552
void data_limit_notify(const DataLimit::Mode cdl_mode, const DataLimit::State cdl_status)
Definition proto.hpp:2351
bool do_encrypt(BufferAllocated &buf, const bool compress_hint)
Definition proto.hpp:2650
std::unique_ptr< DataChannelKey > data_channel_key
Definition proto.hpp:3617
bool data_limit_add(const DataLimit::Mode mode, const size_t size)
Definition proto.hpp:2762
void set_event(const EventType current, const EventType next, const Time &next_time)
Definition proto.hpp:2716
void rekey(const CryptoDCInstance::RekeyType type)
Definition proto.hpp:2081
bool decapsulate(Packet &pkt)
Definition proto.hpp:3474
void key_limit_reneg(const EventType ev, const Time &t)
Definition proto.hpp:2016
bool decapsulate_tls_auth(Packet &pkt)
Definition proto.hpp:3341
PacketType(const Buffer &buf, class ProtoContext &proto)
Definition proto.hpp:1319
bool contains_tls_ciphertext() const
Definition proto.hpp:1654
Packet(BufferPtr &&buf_arg, const unsigned int opcode_arg=CONTROL_V1)
Definition proto.hpp:1623
void frame_prepare(const Frame &frame, const unsigned int context)
Definition proto.hpp:1643
const Buffer & buffer() const
Definition proto.hpp:1666
const BufferPtr & buffer_ptr()
Definition proto.hpp:1662
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:3669
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:3646
PsidCookieHelper(unsigned int op_field)
Definition proto.hpp:3629
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:3657
bool is_tls_crypt_v2() const noexcept
Returns true if this is a TLS crypt V2 protocol packet.
Definition proto.hpp:3640
TLSAuthPreValidate(const ProtoConfig &c, const bool server)
Definition proto.hpp:3753
OPENVPN_SIMPLE_EXCEPTION(tls_auth_pre_validate)
bool validate(const BufferAllocated &net_buf)
Definition proto.hpp:3780
OPENVPN_SIMPLE_EXCEPTION(tls_crypt_pre_validate)
TLSCryptPreValidate(const ProtoConfig &c, const bool server)
Definition proto.hpp:3814
bool validate(const BufferAllocated &net_buf)
Definition proto.hpp:3851
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:4456
bool control_net_recv(const PacketType &type, BufferPtr &&net_bp)
Definition proto.hpp:4278
void set_local_peer_id(const int local_peer_id)
Definition proto.hpp:4479
uint32_t get_tls_warnings() const
Definition proto.hpp:3957
void send_explicit_exit_notify()
Definition proto.hpp:4344
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, process_server_push_error)
bool is_client() const
Definition proto.hpp:4513
void net_send(const unsigned int key_id, const Packet &net_pkt)
Definition proto.hpp:4596
const Time::Duration & slowest_handshake()
Definition proto.hpp:4384
const Time & now() const
Definition proto.hpp:4485
CryptoDCSettings & dc_settings()
Definition proto.hpp:4467
void flush(const bool control_channel)
Definition proto.hpp:4204
void set_dynamic_tls_crypt(const ProtoConfig &c, const KeyContext::Ptr &key_ctx)
Definition proto.hpp:3987
OPENVPN_SIMPLE_EXCEPTION(select_key_context_error)
void control_send(BufferPtr &&app_bp)
Definition proto.hpp:4261
KeyContext & select_control_send_context()
Definition proto.hpp:4655
bool uses_bs64_cipher() const
Definition proto.hpp:3966
void process_secondary_event()
Definition proto.hpp:4771
void reset_tls_crypt(const ProtoConfig &c, const OpenVPNStaticKey &key)
Definition proto.hpp:3971
PacketType packet_type(const Buffer &buf)
Definition proto.hpp:4165
TLSCryptMetadata::Ptr tls_crypt_metadata
Definition proto.hpp:4891
void data_encrypt(BufferAllocated &in_out)
Definition proto.hpp:4299
void reset_tls_crypt_server(const ProtoConfig &c)
Definition proto.hpp:4008
TLSCryptInstance::Ptr tls_crypt_recv
Definition proto.hpp:4888
bool is_keepalive_enabled() const
Definition proto.hpp:4432
KeyContext::Ptr primary
Definition proto.hpp:4899
TLSCryptInstance::Ptr tls_crypt_server
Definition proto.hpp:4890
const Frame & frame() const
Definition proto.hpp:4495
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:1556
ProtoConfig::Ptr conf_ptr() const
Definition proto.hpp:4537
ProtoSessionID psid_peer
Definition proto.hpp:4897
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_option_error)
void process_primary_event()
Definition proto.hpp:4732
const Mode & mode() const
Definition proto.hpp:4505
TLSCryptInstance::Ptr tls_crypt_send
Definition proto.hpp:4887
void process_push(const OptionList &opt, const ProtoContextCompressionOptions &pco)
Definition proto.hpp:4416
static void write_auth_string(const S &str, Buffer &buf)
Definition proto.hpp:1542
void client_auth(Buffer &buf)
Definition proto.hpp:4586
ProtoConfig & conf()
Definition proto.hpp:4533
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:4140
static unsigned int key_id_extract(const unsigned int op)
Definition proto.hpp:306
ProtoSessionID psid_self
Definition proto.hpp:4896
static S read_control_string(const Buffer &buf)
Definition proto.hpp:1582
void write_control_string(const S &str)
Definition proto.hpp:1603
bool data_channel_ready() const
Definition proto.hpp:4372
void keepalive_housekeeping()
Definition proto.hpp:4665
Time::Duration slowest_handshake_
Definition proto.hpp:4882
unsigned int upcoming_key_id
Definition proto.hpp:4875
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:4426
PacketIDControlReceive ta_pid_recv
Definition proto.hpp:4894
ProtoContextCallbackInterface * proto_callback
Definition proto.hpp:4867
void reset_tls_wrap_mode(const ProtoConfig &c)
Definition proto.hpp:3919
SessionStats & stat() const
Definition proto.hpp:4543
bool is_server() const
Definition proto.hpp:4509
OvpnHMACInstance::Ptr ta_hmac_recv
Definition proto.hpp:4885
std::string dump_packet(const Buffer &buf)
Definition proto.hpp:1426
void disconnect(const Error::Type reason)
Definition proto.hpp:4334
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:4272
KeyContext & select_key_context(const PacketType &type, const bool control)
Definition proto.hpp:4624
static void write_empty_string(Buffer &buf)
Definition proto.hpp:1576
TLSWrapMode tls_wrap_mode
Definition proto.hpp:4873
void app_recv(const unsigned int key_id, BufferPtr &&to_app_buf)
Definition proto.hpp:4601
void keepalive_parms_modified()
Definition proto.hpp:4841
int primary_state() const
Definition proto.hpp:4555
static void write_control_string(const S &str, Buffer &buf)
Definition proto.hpp:1569
void control_send(BufferAllocated &&app_buf)
Definition proto.hpp:4266
bool data_decrypt(const PacketType &type, BufferAllocated &in_out)
Definition proto.hpp:4309
void disable_keepalive(unsigned int &keepalive_ping, unsigned int &keepalive_timeout)
Definition proto.hpp:4440
static constexpr PacketIDControl::id_t EARLY_NEG_MASK
Definition proto.hpp:4574
static constexpr PacketIDControl::id_t EARLY_NEG_START
Definition proto.hpp:4573
Error::Type invalidation_reason() const
Definition proto.hpp:4396
static size_t op_head_size(const unsigned int op)
Definition proto.hpp:311
void new_secondary_key(const bool initiator)
Definition proto.hpp:4710
void update_last_received()
Definition proto.hpp:4591
void promote_secondary_to_primary()
Definition proto.hpp:4722
bool is_state_client_wait_reset_ack() const
Definition proto.hpp:4549
unsigned int negotiations() const
Definition proto.hpp:4378
PacketIDControlSend ta_pid_send
Definition proto.hpp:4893
Time next_housekeeping() const
Definition proto.hpp:4242
ProtoContext(ProtoContextCallbackInterface *cb_arg, const ProtoConfig::Ptr &config_arg, const SessionStats::Ptr &stats_arg)
Definition proto.hpp:3906
static void write_uint16_length(const size_t size, Buffer &buf)
Definition proto.hpp:1521
SessionStats::Ptr stats
Definition proto.hpp:4870
unsigned int n_key_ids
Definition proto.hpp:4876
void tls_crypt_append_wkc(BufferAllocated &dst)
Definition proto.hpp:4853
ProtoConfig::Ptr config
Definition proto.hpp:4869
bool control_net_recv(const PacketType &type, BufferAllocated &&net_buf)
pass received control channel network packets (ciphertext) into protocol object
Definition proto.hpp:4293
virtual ~ProtoContext()=default
std::string debug_prefix()
Definition proto.hpp:4813
static constexpr size_t APP_MSG_MAX
Definition proto.hpp:214
const Frame::Ptr & frameptr() const
Definition proto.hpp:4499
bool invalidated() const
Definition proto.hpp:4390
void reset(const ProtoSessionID cookie_psid=ProtoSessionID())
Resets ProtoContext *this to it's initial state.
Definition proto.hpp:4049
void start(const ProtoSessionID cookie_psid=ProtoSessionID())
Initialize the state machine and start protocol negotiation.
Definition proto.hpp:4178
bool renegotiate_request(Packet &pkt)
Definition proto.hpp:4607
KeyContext::Ptr secondary
Definition proto.hpp:4900
unsigned int next_key_id()
Definition proto.hpp:4830
OvpnHMACInstance::Ptr ta_hmac_send
Definition proto.hpp:4884
const ProtoConfig & conf() const
Definition proto.hpp:4529
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:979
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:912
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:409
static TimeType infinite()
Definition time.hpp:256
base_type seconds_since_epoch() const
Definition time.hpp:292
bool defined() const
Definition time.hpp:283
#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:445
std::string trim_crlf_copy(std::string str)
Definition string.hpp:184
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:135
TimeType< oulong > Time
Definition time.hpp:492
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:255
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:72
static constexpr size_t size()
constexpr std::size_t size() const
std::optional< CryptoDCInstance::RekeyType > rekey_type
Definition proto.hpp:1706
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