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