OpenVPN 3 Core Library
Loading...
Searching...
No Matches
proto.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12// ProtoContext, the fundamental OpenVPN protocol implementation.
13// It can be used by OpenVPN clients, servers, or unit tests.
14
15#ifndef OPENVPN_SSL_PROTO_H
16#define OPENVPN_SSL_PROTO_H
17
18#include <cstring>
19#include <string>
20#include <sstream>
21#include <algorithm> // for std::min
22#include <cstdint> // for std::uint32_t, etc.
23#include <memory>
24#include <optional>
25
26
32#include <openvpn/common/rc.hpp>
45#include <openvpn/ip/ip4.hpp>
46#include <openvpn/ip/ip6.hpp>
47#include <openvpn/ip/udp.hpp>
48#include <openvpn/ip/tcp.hpp>
49#include <openvpn/time/time.hpp>
64#include <openvpn/ssl/psid.hpp>
71#include <openvpn/tun/layer.hpp>
79
80#ifndef OPENVPN_DEBUG_PROTO
81#define OPENVPN_DEBUG_PROTO 1
82#endif
83
84/*
85
86ProtoContext -- OpenVPN protocol implementation
87
88Protocol negotiation states:
89
90Client:
91
921. send client reset to server
932. wait for server reset from server AND ack from 1 (C_WAIT_RESET, C_WAIT_RESET_ACK)
943. start SSL handshake
954. send auth message to server
965. wait for server auth message AND ack from 4 (C_WAIT_AUTH, C_WAIT_AUTH_ACK)
976. go active (ACTIVE)
98
99Server:
100
1011. wait for client reset (S_WAIT_RESET)
1022. send server reset to client
1033. wait for ACK from 2 (S_WAIT_RESET_ACK)
1044. start SSL handshake
1055. wait for auth message from client (S_WAIT_AUTH)
1066. send auth message to client
1077. wait for ACK from 6 (S_WAIT_AUTH_ACK)
1088. go active (ACTIVE)
109
110*/
111
112namespace openvpn {
113
114// utility namespace for ProtoContext
115namespace proto_context_private {
116namespace {
117// clang-format off
118const unsigned char auth_prefix[] = { 0, 0, 0, 0, 2 }; // CONST GLOBAL
119
120const unsigned char keepalive_message[] = { // CONST GLOBAL
121 0x2a, 0x18, 0x7b, 0xf3, 0x64, 0x1e, 0xb4, 0xcb,
122 0x07, 0xed, 0x2d, 0x0a, 0x98, 0x1f, 0xc7, 0x48
123};
124
125enum
126{
127 KEEPALIVE_FIRST_BYTE = 0x2a // first byte of keepalive message
128};
129
130inline bool is_keepalive(const Buffer &buf)
131{
132 return buf.size() >= sizeof(keepalive_message)
133 && buf[0] == KEEPALIVE_FIRST_BYTE
134 && !std::memcmp(keepalive_message, buf.c_data(), sizeof(keepalive_message));
135}
136
137const unsigned char explicit_exit_notify_message[] = { // CONST GLOBAL
138 0x28, 0x7f, 0x34, 0x6b, 0xd4, 0xef, 0x7a, 0x81,
139 0x2d, 0x56, 0xb8, 0xd3, 0xaf, 0xc5, 0x45, 0x9c,
140 6 // OCC_EXIT
141};
142// clang-format on
143
144enum
145{
146 EXPLICIT_EXIT_NOTIFY_FIRST_BYTE = 0x28 // first byte of exit message
147};
148} // namespace
149} // namespace proto_context_private
150
152{
153 public:
155
159 virtual void control_net_send(const Buffer &net_buf) = 0;
160
161 /*
162 * Receive as packet from the network
163 * \note app may take ownership of app_bp via std::move
164 */
165 virtual void control_recv(BufferPtr &&app_bp) = 0;
166
171 virtual void client_auth(Buffer &buf)
172 {
173 write_empty_string(buf); // username
174 write_empty_string(buf); // password
175 }
176
179 virtual void server_auth(const std::string &username,
180 const SafeString &password,
181 const std::string &peer_info,
182 const AuthCert::Ptr &auth_cert)
183 {
184 }
185
190 static void write_empty_string(Buffer &buf)
191 {
192 uint8_t empty[]{0x00, 0x00}; // empty length field without content
193 buf.write(&empty, 2);
194 }
195
199 virtual bool supports_epoch_data() = 0;
200
202 virtual void active(bool primary) = 0;
203};
204
205class ProtoContext : public logging::LoggingMixin<OPENVPN_DEBUG_PROTO,
206 logging::LOG_LEVEL_VERB,
207 ProtoContext>
208{
209#ifdef UNIT_TEST
210 public:
211#else
212 protected:
213#endif
214 static constexpr size_t APP_MSG_MAX = 65536;
215 // size of the leading opcode/key-id byte of a packet
216 static constexpr size_t OPCODE_SIZE = 1;
217
218 enum
219 {
220 // packet opcode (high 5 bits) and key-id (low 3 bits) are combined in one byte
223
224 // packet opcodes -- the V1 is intended to allow protocol changes in the future
225 // CONTROL_HARD_RESET_CLIENT_V1 = 1, // (obsolete) initial key from client, forget previous state
226 // CONTROL_HARD_RESET_SERVER_V1 = 2, // (obsolete) initial key from server, forget previous state
227 CONTROL_SOFT_RESET_V1 = 3, // new key, graceful transition from old to new key
228 CONTROL_V1 = 4, // control channel packet (usually TLS ciphertext)
229 CONTROL_WKC_V1 = 11, // control channel packet with wrapped client key appended
230 ACK_V1 = 5, // acknowledgement for packets received
231 DATA_V1 = 6, // data channel packet with 1-byte header
232 DATA_V2 = 9, // data channel packet with 4-byte header
233
234 // indicates key_method >= 2
235 CONTROL_HARD_RESET_CLIENT_V2 = 7, // initial key from client, forget previous state
236 CONTROL_HARD_RESET_CLIENT_V3 = 10, // initial key from client, forget previous state
237 CONTROL_HARD_RESET_SERVER_V2 = 8, // initial key from server, forget previous state
238
240
241 // DATA_V2 constants
242 OP_SIZE_V2 = 4, // size of initial packet opcode
243 OP_PEER_ID_UNDEF = 0x00FFFFFF, // indicates that Peer ID is undefined
244
245 // states
246 // C_x : client states
247 // S_x : server states
248
249 // ACK states -- must be first before other states
255 LAST_ACK_STATE = 3, // all ACK states must be <= this value
256
257 // key negotiation states (client)
259 C_WAIT_RESET = 5, // must be C_INITIAL+1
261
262 // key negotiation states (server)
264 S_WAIT_RESET = 8, // must be S_INITIAL+1
266
267 // key negotiation states (client and server)
268 ACTIVE = 10,
269 };
270
271 enum iv_proto_flag : unsigned int
272 {
273 // See ssl.h in openvpn2 for detailed documentation of IV_PROTO
274 //
275 // NOTE: Bit field (1 << 0) is reserved for historic reasons
276 // and not expected to be set. Do not use this field.
277 //
282 IV_PROTO_NCP_P2P = (1 << 5), // not implemented
283 IV_PROTO_DNS_OPTION = (1 << 6), // outdated, don't send
289 IV_PROTO_PUSH_UPDATE = (1 << 12)
290 };
291
292 enum tlv_types : uint16_t
293 {
294 EARLY_NEG_FLAGS = 0x0001
295 };
296
297 enum early_neg_flags : uint16_t
298 {
300 };
301
306 static constexpr PacketIDControl::id_t EARLY_NEG_START = 0x0f000000;
307 static constexpr PacketIDControl::id_t EARLY_NEG_MASK = 0xff000000;
308
309 static unsigned int opcode_extract(const unsigned int op)
310 {
311 return op >> OPCODE_SHIFT;
312 }
313
314 static unsigned int key_id_extract(const unsigned int op)
315 {
316 return op & KEY_ID_MASK;
317 }
318
319 static size_t op_head_size(const unsigned int op)
320 {
321 return opcode_extract(op) == DATA_V2 ? OP_SIZE_V2 : 1;
322 }
323
324 static unsigned char op_compose(const unsigned int opcode, const unsigned int key_id)
325 {
326 // As long as 'opcode' stays within the range specified by the enum the cast should be safe.
327 // TODO: Use a more constrained type for opcode to ensure range violations can't happen.
328 return static_cast<unsigned char>((opcode << OPCODE_SHIFT) | key_id);
329 }
330
331 static unsigned int op32_compose(const unsigned int opcode,
332 const unsigned int key_id,
333 const int op_peer_id)
334 {
335 return (op_compose(opcode, key_id) << 24) | (op_peer_id & 0x00FFFFFF);
336 }
337
338 public:
339 OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_error);
340 OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, process_server_push_error);
341 OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_option_error);
342
343 // Worst-case number of bytes added around the SSL ciphertext of a
344 // control channel packet: opcode, session id, tls-auth/tls-crypt
345 // packet id, the largest supported HMAC digest (SHA512, tls-auth),
346 // the reliable-layer message id and the largest possible piggybacked
347 // ACK block (count byte + ACK ids + dest session id). Used to size
348 // the control channel ciphertext chunks such that the final wrapped
349 // packet cannot exceed the mssfix_ctrl limit.
350 static constexpr size_t MAX_CONTROL_WRAP_OVERHEAD =
354 + 64 // largest supported HMAC digest (SHA512, tls-auth)
355 + sizeof(reliable::id_t)
358
359 // configuration data passed to ProtoContext constructor
360 class ProtoConfig : public RCCopyable<thread_unsafe_refcount>
361 {
362 public:
364
365 // master SSL context factory
367
368 // data channel
370
371 // TLSPRF factory
373
374 // master Frame object
376
377 // (non-smart) pointer to current time
379
380 // Random number generator.
381 // Use-cases demand highest cryptographic strength
382 // such as key generation.
384
385 // Pseudo-random number generator.
386 // Use-cases demand cryptographic strength
387 // combined with high performance. Used for
388 // IV and ProtoSessionID generation.
390
391 // If relay mode is enabled, connect to a special OpenVPN
392 // server that acts as a relay/proxy to a second server.
393 bool relay_mode = false;
394
395 // defer data channel initialization until after client options pull
396 bool dc_deferred = false;
397
398 // transmit username/password creds to server (client-only)
399 bool xmit_creds = true;
400
401 // send client exit notifications via control channel
402 bool cc_exit_notify = false;
403
404 // Transport protocol, i.e. UDPv4, etc.
405 Protocol protocol; // set with set_protocol()
406
407 // OSI layer
409
410 // compressor
412
413 // tls_auth/crypt parms
415 {
416 None = 0,
417 V1 = (1 << 0),
418 V2 = (1 << 1),
419 Dynamic = (1 << 2)
420 };
421
424
427
430
433
436
439
442 int key_direction = -1; // 0, 1, or -1 for bidirectional
443
446
448
449 // timeout parameters, relative to construction of KeyContext object
450 Time::Duration handshake_window; // SSL/TLS negotiation must complete by this time
451 Time::Duration become_primary; // KeyContext (that is ACTIVE) becomes primary at this time
452 Time::Duration renegotiate; // start SSL/TLS renegotiation at this time
453 Time::Duration expire; // KeyContext expires at this time
454 Time::Duration tls_timeout; // Packet retransmit timeout on TLS control channel
455
456 // keepalive parameters
457 Time::Duration keepalive_ping; // ping xmit period
458 Time::Duration keepalive_timeout; // timeout period after primary KeyContext reaches ACTIVE state
459 Time::Duration keepalive_timeout_early; // timeout period before primary KeyContext reaches ACTIVE state
460
463
464 // App control config
470
474
475 // op header
476 bool enable_op32 = false;
477 int remote_peer_id = -1; // -1 to disable
478 int local_peer_id = -1; // -1 to disable
479
480 // MTU
481 unsigned int tun_mtu = TUN_MTU_DEFAULT;
482 unsigned int tun_mtu_max = TUN_MTU_DEFAULT + 100;
484 unsigned int mss_fix = 0;
485
486 // maximum size of a control channel packet on the wire, after all
487 // wrapping (tls-auth/tls-crypt/tls-crypt-v2) has been applied;
488 // 1280 == IPv6 minimum MTU
489 size_t mssfix_ctrl = 1280;
490
491 // For compatibility with openvpn2 we send initial options on rekeying,
492 // instead of possible modifications caused by NCP
493 std::string initial_options;
494
495 bool auth_nocache = false;
496
497 void load(const OptionList &opt,
499 const int default_key_direction,
500 const bool server)
501 {
502 // first set defaults
503 handshake_window = Time::Duration::seconds(60);
504 renegotiate = Time::Duration::seconds(3600);
505 tls_timeout = Time::Duration::seconds(1);
506 keepalive_ping = Time::Duration::seconds(8);
507 keepalive_timeout = Time::Duration::seconds(40);
510 protocol = Protocol();
511 key_direction = default_key_direction;
512
513 // layer
514 {
515 const Option *dev = opt.get_ptr("dev-type");
516 if (!dev)
517 dev = opt.get_ptr("dev");
518 if (!dev)
519 throw proto_option_error(ERR_INVALID_CONFIG, "missing dev-type or dev option");
520 const std::string &dev_type = dev->get(1, 64);
521 if (dev_type.starts_with("tun"))
523 else if (dev_type.starts_with("tap"))
524 throw proto_option_error(ERR_INVALID_CONFIG, "TAP mode is not supported");
525 else
526 throw proto_option_error(ERR_INVALID_OPTION_VAL, "bad dev-type");
527 }
528
529 // cipher/digest/tls-auth/tls-crypt
530 {
533
534 // data channel cipher
535 {
536 const Option *o = opt.get_ptr("cipher");
537 if (o)
538 {
539 const std::string &cipher_name = o->get(1, 128);
540 if (cipher_name != "none")
541 cipher = CryptoAlgs::lookup(cipher_name);
542 }
543 else
544 cipher = CryptoAlgs::lookup("BF-CBC");
545 }
546
547 // data channel HMAC
548 {
549 const Option *o = opt.get_ptr("auth");
550 if (o)
551 {
552 const std::string &auth_name = o->get(1, 128);
553 if (auth_name != "none")
554 digest = CryptoAlgs::lookup(auth_name);
555 }
556 else
557 digest = CryptoAlgs::lookup("SHA1");
558 }
559 dc.set_cipher(cipher);
560 dc.set_digest(digest);
561
562 // tls-auth
563 {
564 const Option *o = opt.get_ptr(relay_prefix("tls-auth"));
565 if (o)
566 {
567 if (!server && tls_crypt_context)
568 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-auth and tls-crypt are mutually exclusive");
569
570 tls_auth_key.parse(o->get(1, 0));
571
572 const Option *tad = opt.get_ptr(relay_prefix("tls-auth-digest"));
573 if (tad)
574 digest = CryptoAlgs::lookup(tad->get(1, 128));
575 if (digest != CryptoAlgs::NONE)
576 set_tls_auth_digest(digest);
577 }
578 }
579
580 // tls-crypt
581 {
582 const Option *o = opt.get_ptr(relay_prefix("tls-crypt"));
583 if (o)
584 {
585 if (!server && tls_auth_context)
586 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-auth and tls-crypt are mutually exclusive");
588 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-crypt and tls-crypt-v2 are mutually exclusive");
589
591 tls_crypt_key.parse(o->get(1, 0));
592
594 }
595 }
596
597 // tls-crypt-v2
598 {
599 const Option *o = opt.get_ptr(relay_prefix("tls-crypt-v2"));
600 if (o)
601 {
602 if (!server && tls_auth_context)
603 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-auth and tls-crypt-v2 are mutually exclusive");
605 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-crypt and tls-crypt-v2 are mutually exclusive");
606
607 // initialize tls_crypt_context
609
610 std::string keyfile = o->get(1, 0);
611
612 if (opt.exists("client"))
613 {
614 // in client mode expect the key to be a PEM encoded tls-crypt-v2 client key (key + WKc)
615 TLSCryptV2ClientKey tls_crypt_v2_key(tls_crypt_context);
616 tls_crypt_v2_key.parse(keyfile);
617 tls_crypt_v2_key.extract_key(tls_crypt_key);
618 tls_crypt_v2_key.extract_wkc(wkc);
619 }
620 else
621 {
623 {
624 // in server mode this is a PEM encoded tls-crypt-v2 server key
625 TLSCryptV2ServerKey tls_crypt_v2_key;
626 tls_crypt_v2_key.parse(keyfile);
627 tls_crypt_v2_key.extract_key(tls_crypt_key);
628 }
629 }
631 }
632 }
633 }
634
635 // key-direction
636 {
637 if (key_direction >= -1 && key_direction <= 1)
638 {
639 const Option *o = opt.get_ptr(relay_prefix("key-direction"));
640 if (o)
641 {
642 const std::string &dir = o->get(1, 16);
643 if (dir == "0")
644 key_direction = 0;
645 else if (dir == "1")
646 key_direction = 1;
647 else if (dir == "bidirectional" || dir == "bi")
648 key_direction = -1;
649 else
650 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "bad key-direction parameter");
651 }
652 }
653 else
654 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "bad key-direction default");
655 }
656
657 // compression
658 {
659 const Option *o = opt.get_ptr("compress");
660 if (o)
661 {
662 if (o->size() >= 2)
663 {
664 const std::string meth_name = o->get(1, 128);
666 if (meth == CompressContext::NONE)
667 OPENVPN_THROW_ARG1(proto_option_error, ERR_INVALID_OPTION_VAL, "Unknown compressor: '" << meth_name << '\'');
669 }
670 else
672 }
673 else
674 {
675 o = opt.get_ptr("comp-lzo");
676 if (o)
677 {
678 if (o->size() == 2 && o->ref(1) == "no")
679 {
680 // On the client, by using ANY instead of ANY_LZO, we are telling the server
681 // that it's okay to use any of our supported compression methods.
683 }
684 else
685 {
687 }
688 }
689 }
690 }
691
692 // tun-mtu
695
696 // mssfix
697 mss_parms.parse(opt, true);
699 {
701 {
703 mss_parms.mtu = true;
704 }
705 else
706 {
708 mss_parms.fixed = true;
709 }
710 }
711
712 // mssfix-ctrl: cap on the wrapped size of control channel packets
714
715 // load parameters that can be present in both config file or pushed options
717 }
718
728
729 // load options string pushed by server
731 {
732 // data channel
734
735 // protocol-flags
737
738 // compression
739 parse_pushed_compression(opt, pco);
740
741 // peer ID
743
744 // custom app control channel options
746
747 try
748 {
749 // load parameters that can be present in both config file or pushed options
751 }
752 catch (const std::exception &e)
753 {
754 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed parameter: " << e.what());
755 }
756
757 // show negotiated options
759 }
760
762 {
763 try
764 {
765 const Option *o = opt.get_ptr("custom-control");
766 if (o)
767 {
768 app_control_config.max_msg_size = o->get_num(1, 1, std::numeric_limits<int>::max());
769 const auto &flags = o->get(2, 1024);
770 const auto &protocols = o->get(3, 1024);
772
774
775 /* This implementation always wants to have at least both base64 and text encoding */
777 {
778 OPENVPN_LOG("Warning: custom app control requires base64 encoding to properly work");
779 }
780 }
781 }
782 catch (const std::exception &e)
783 {
784 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed parameter: " << e.what());
786 }
787 }
788
790 {
791 // cipher
792 std::string new_cipher;
793 try
794 {
795 const Option *o = opt.get_ptr("cipher");
796 if (o)
797 {
798 new_cipher = o->get(1, 128);
799 if (new_cipher != "none")
800 dc.set_cipher(CryptoAlgs::lookup(new_cipher));
801 }
802 }
803 catch (const std::exception &e)
804 {
805 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed cipher '" << new_cipher << "': " << e.what());
806 }
807
808 // digest
809 std::string new_digest;
810 try
811 {
812 const Option *o = opt.get_ptr("auth");
813 if (o)
814 {
815 new_digest = o->get(1, 128);
816 if (new_digest != "none")
817 dc.set_digest(CryptoAlgs::lookup(new_digest));
818 }
819 }
820 catch (const std::exception &e)
821 {
822 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed digest '" << new_digest << "': " << e.what());
823 }
824 }
825
827 {
828 try
829 {
830 const Option *o = opt.get_ptr("peer-id");
831 if (o)
832 {
833 bool status = parse_number_validate<int>(o->get(1, 16),
834 16,
835 -1,
836 0xFFFFFE,
838 if (!status)
839 throw Exception("parse/range issue");
840 enable_op32 = true;
841 }
842 }
843 catch (const std::exception &e)
844 {
845 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed peer-id: " << e.what());
846 }
847 }
848
850 {
851 // tls key-derivation method with old key-derivation option
852 std::string key_method;
853 try
854 {
855 const Option *o = opt.get_ptr("key-derivation");
856 if (o)
857 {
858 key_method = o->get(1, 128);
859 if (key_method == "tls-ekm")
861 else
862 OPENVPN_THROW(process_server_push_error, "Problem accepting key-derivation method '" << key_method << "'");
863 }
864 else
866 }
867 catch (const std::exception &e)
868 {
869 OPENVPN_THROW(process_server_push_error, "Problem accepting key-derivation method '" << key_method << "': " << e.what());
870 }
871
872 try
873 {
874 const Option *o = opt.get_ptr("protocol-flags");
875 if (o)
876 {
877 o->min_args(2);
878 for (std::size_t i = 1; i < o->size(); i++)
879 {
880 std::string flag = o->get(i, 128);
881 if (flag == "cc-exit")
882 {
883 cc_exit_notify = true;
884 }
885 else if (flag == "dyn-tls-crypt")
886 {
888 }
889 else if (flag == "tls-ekm")
890 {
891 // Overrides "key-derivation" method set above
893 }
894 else if (flag == "aead-epoch")
895 {
897 }
898 else
899 {
900 OPENVPN_THROW(process_server_push_error, "unknown flag '" << flag << "'");
901 }
902 }
903 }
904 }
905 catch (const std::exception &e)
906 {
907 OPENVPN_THROW(process_server_push_error, "Problem accepting protocol-flags: " << e.what());
908 }
909 }
910
912 {
913 std::string new_comp;
914 try
915 {
916 const Option *o;
917 o = opt.get_ptr("compress");
918 if (o)
919 {
920 new_comp = o->get(1, 128);
922 if (meth != CompressContext::NONE)
923 {
924 // if compression is not availabe, CompressContext ctor throws an exception
925 if (pco.is_comp())
927 else
928 {
929 // server pushes compression but client has compression disabled
930 // degrade to asymmetric compression (downlink only)
931 comp_ctx = CompressContext(meth, true);
932 if (!comp_ctx.is_any_stub(meth))
933 {
934 OPENVPN_LOG("Server has pushed compressor "
935 << comp_ctx.str()
936 << ", but client has disabled compression, switching to asymmetric");
937 }
938 }
939 }
940 }
941 else
942 {
943 o = opt.get_ptr("comp-lzo");
944 if (o)
945 {
946 if (o->size() == 2 && o->ref(1) == "no")
947 {
949 }
950 else
951 {
953 }
954 }
955 }
956 }
957 catch (const std::exception &e)
958 {
959 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed compressor '" << new_comp << "': " << e.what());
960 }
961 }
962
963 void get_data_channel_options(std::ostringstream &os) const
964 {
965 os << " data channel:";
966 os << " cipher " << CryptoAlgs::name(dc.cipher());
968 os << ", digest " << CryptoAlgs::name(dc.digest());
969
970 os << ", peer-id " << remote_peer_id;
971
972 if (dc.useEpochKeys())
973 os << ", aead-epoch";
974
975 os << '\n';
976 }
977
978 void show_cc_enc_option(std::ostringstream &os) const
979 {
980 if (tls_auth_enabled())
981 {
982 os << " control channel: tls-auth enabled\n";
983 }
985 {
986 os << " control channel: tls-crypt v2 enabled\n";
987 }
988 else if (tls_crypt_enabled())
989 {
990 os << " control channel: tls-crypt enabled\n";
991 }
992 else if (dynamic_tls_crypt_enabled())
993 {
994 os << " control channel: dynamic tls-crypt enabled\n";
995 }
996 }
997
998 std::string show_options() const
999 {
1000 std::ostringstream os;
1001 os << "PROTOCOL OPTIONS:\n";
1002 os << " key-derivation: " << CryptoAlgs::name(dc.key_derivation()) << '\n';
1004 os << " compress: " << comp_ctx.str() << '\n';
1005
1008
1010 {
1011 os << " app custom control channel: " << app_control_config.str() << '\n';
1012 }
1013
1014 return os.str();
1015 }
1016
1017 void set_protocol(const Protocol &p)
1018 {
1019 // adjust options for new transport protocol
1020 protocol = p;
1021 }
1022
1024 {
1026 }
1027
1029 {
1031 return;
1032
1033 auto digest = CryptoAlgs::lookup("SHA256");
1034 auto cipher = CryptoAlgs::lookup("AES-256-CTR");
1035
1036 if ((digest == CryptoAlgs::NONE) || (cipher == CryptoAlgs::NONE))
1037 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "missing support for tls-crypt algorithms");
1038
1039 /* TODO: we currently use the default SSL library context here as the
1040 * library context is not available this early. This should not matter
1041 * for the algorithms used by tls_crypt */
1042 tls_crypt_context = tls_crypt_factory->new_obj(nullptr, digest, cipher);
1043 }
1044
1045 void set_xmit_creds(const bool xmit_creds_arg)
1046 {
1047 xmit_creds = xmit_creds_arg;
1048 }
1049
1050 bool tls_auth_enabled() const
1051 {
1053 }
1054
1056 {
1058 }
1059
1064
1066 {
1067 return (tls_crypt_ & TLSCrypt::Dynamic);
1068 }
1069
1070 // generate a string summarizing options that will be
1071 // transmitted to peer for options consistency check
1072 std::string options_string()
1073 {
1074 if (!initial_options.empty())
1075 return initial_options;
1076
1077 std::ostringstream out;
1078
1079 const bool server = ssl_factory->mode().is_server();
1080 const unsigned int l2extra = (layer() == Layer::OSI_LAYER_2 ? 32 : 0);
1081
1082 out << "V4";
1083
1084 out << ",dev-type " << layer.dev_type();
1085 out << ",link-mtu " << tun_mtu + link_mtu_adjust() + l2extra;
1086 out << ",tun-mtu " << tun_mtu + l2extra;
1087 out << ",proto " << protocol.occ_str(server);
1088
1089 {
1090 const char *compstr = comp_ctx.options_string();
1091 if (compstr)
1092 out << ',' << compstr;
1093 }
1094
1095 if (tls_auth_context && (key_direction >= 0))
1096 out << ",keydir " << key_direction;
1097
1098 out << ",cipher " << CryptoAlgs::name(dc.cipher(), "[null-cipher]");
1099 out << ",auth " << CryptoAlgs::name(dc.digest(), "[null-digest]");
1100 out << ",keysize " << (CryptoAlgs::key_length(dc.cipher()) * 8);
1101
1102 if (tls_auth_context)
1103 out << ",tls-auth";
1104
1105 // sending tls-crypt does not make sense. If we got to this point it
1106 // means that tls-crypt was already there and it worked fine.
1107 // tls-auth has to be kept for backward compatibility as it is there
1108 // since a bit.
1109
1110 out << ",key-method 2";
1111
1112 if (server)
1113 out << ",tls-server";
1114 else
1115 out << ",tls-client";
1116
1117 initial_options = out.str();
1118
1119 return initial_options;
1120 }
1121
1127 {
1130 {
1131 /* check if the IV_HWADDR is already present in the extra_peer_info set as it has then been
1132 * statically been overridden */
1133 if (!extra_peer_info->contains_key("IV_HWADDR"))
1134 {
1135 std::string hwaddr = get_hwaddr(transport->server_endpoint_addr());
1136 if (!hwaddr.empty())
1137 extra_peer_info_transport->emplace_back("IV_HWADDR", hwaddr);
1138 }
1139 }
1140 }
1141
1142 // generate a string summarizing information about the client
1143 // including capabilities
1144 std::string peer_info_string(bool supports_epoch_data) const
1145 {
1146 std::ostringstream out;
1147 const char *compstr = nullptr;
1148
1149 // supports op32 and P_DATA_V2 and expects a push reply
1150 unsigned int iv_proto = IV_PROTO_DATA_V2
1157
1158 if (supports_epoch_data)
1159 iv_proto |= IV_PROTO_DATA_EPOCH;
1160
1161 if (CryptoAlgs::lookup("SHA256") != CryptoAlgs::NONE && CryptoAlgs::lookup("AES-256-CTR") != CryptoAlgs::NONE)
1162 iv_proto |= IV_PROTO_DYN_TLS_CRYPT;
1163
1164 if (SSLLib::SSLAPI::support_key_material_export())
1165 {
1166 iv_proto |= IV_PROTO_TLS_KEY_EXPORT;
1167 }
1168
1169 out << "IV_VER=" << OPENVPN_VERSION << '\n';
1170 out << "IV_PLAT=" << platform_name() << '\n';
1171 out << "IV_NCP=2\n"; // negotiable crypto parameters V2
1172 out << "IV_TCPNL=1\n"; // supports TCP non-linear packet ID
1173 out << "IV_PROTO=" << iv_proto << '\n';
1174 out << "IV_MTU=" << tun_mtu_max << "\n";
1175 /*
1176 * OpenVPN3 allows to be pushed any cipher that it supports as it
1177 * only implements secure ones and BF-CBC for backwards
1178 * compatibility and generally adopts the concept of the server being
1179 * responsible for sensible choices. Include the cipher here since
1180 * OpenVPN 2.5 will otherwise ignore it and break on conrer cases
1181 * like --cipher AES-128-CBC on client and --data-ciphers "AES-128-CBC"
1182 * on server.
1183 *
1184 */
1185 out << "IV_CIPHERS=";
1187 [&out](CryptoAlgs::Type type, const CryptoAlgs::Alg &alg) -> bool
1188 {
1189 if (!alg.dc_cipher())
1190 return false;
1191 out << alg.name() << ':';
1192 return true;
1193 });
1194 out.seekp(-1, std::ios_base::cur);
1195 out << "\n";
1196
1197 compstr = comp_ctx.peer_info_string();
1198
1199 if (compstr)
1200 out << compstr;
1201 if (extra_peer_info)
1202 out << extra_peer_info->to_string();
1204 out << extra_peer_info_transport->to_string();
1205 if (is_bs64_cipher(dc.cipher()))
1206 out << "IV_BS64DL=1\n"; // indicate support for data limits when using 64-bit block-size ciphers, version 1 (CVE-2016-6329)
1207 if (relay_mode)
1208 out << "IV_RELAY=1\n";
1209
1210
1211 const std::string ret = out.str();
1212 OVPN_LOG_INFO("Sending Peer Info:\n"
1213 << ret);
1214 return ret;
1215 }
1216
1217 // Used to generate link_mtu option sent to peer.
1218 // Not const because dc.context() caches the DC context.
1219 unsigned int link_mtu_adjust()
1220 {
1221 size_t dc_overhead;
1222 if (dc.cipher() == CryptoAlgs::BF_CBC)
1223 {
1224 /* since often configuration lack BF-CBC, we hardcode the overhead for BF-CBC to avoid
1225 * trying to load BF-CBC, which is not available anymore in modern crypto libraries */
1226 dc_overhead = CryptoAlgs::size(dc.digest()) // HMAC
1227 + 64 / 8 // Cipher IV
1228 + 64 / 8; // worst-case PKCS#7 padding expansion (blocksize)
1229 }
1230 else
1231 {
1232 dc_overhead = dc.context().encap_overhead();
1233 }
1234 const size_t adj = protocol.extra_transport_bytes() + // extra 2 bytes for TCP-streamed packet length
1235 (enable_op32 ? 4 : 1) + // leading op
1236 comp_ctx.extra_payload_bytes() + // compression header
1237 PacketIDData::size(false) + // sequence number
1238 dc_overhead; // data channel crypto layer overhead
1239 return (unsigned int)adj;
1240 }
1241
1242 private:
1249
1250 // load parameters that can be present in both config file or pushed options
1251 void load_common(const OptionList &opt,
1253 const LoadCommonType type)
1254 {
1255 // duration parms
1256 load_duration_parm(renegotiate, "reneg-sec", opt, 10, false, false);
1258 load_duration_parm(expire, "tran-window", opt, 10, false, false);
1260 load_duration_parm(handshake_window, "hand-window", opt, 10, false, false);
1261 if (is_bs64_cipher(dc.cipher())) // special data limits for 64-bit block-size ciphers (CVE-2016-6329)
1262 {
1263 become_primary = Time::Duration::seconds(5);
1264 tls_timeout = Time::Duration::milliseconds(1000);
1265 }
1266 else
1267 become_primary = Time::Duration::seconds(std::min(handshake_window.to_seconds(),
1268 renegotiate.to_seconds() / 2));
1269 load_duration_parm(become_primary, "become-primary", opt, 0, false, false);
1270 load_duration_parm(tls_timeout, "tls-timeout", opt, 100, false, true);
1271
1272 if (type == LOAD_COMMON_SERVER)
1273 renegotiate += handshake_window; // avoid renegotiation collision with client
1274
1275 // keepalive, ping, ping-restart
1276 {
1277 const Option *o = opt.get_ptr("keepalive");
1278 if (o)
1279 {
1280 set_duration_parm(keepalive_ping, "keepalive ping", o->get(1, 16), 1, false, false);
1281 set_duration_parm(keepalive_timeout, "keepalive timeout", o->get(2, 16), 1, type == LOAD_COMMON_SERVER, false);
1282
1283 if (o->size() >= 4)
1284 set_duration_parm(keepalive_timeout_early, "keepalive timeout early", o->get(3, 16), 1, false, false);
1285 else
1287 }
1288 else
1289 {
1290 load_duration_parm(keepalive_ping, "ping", opt, 1, false, false);
1291 load_duration_parm(keepalive_timeout, "ping-restart", opt, 1, false, false);
1292 }
1293 }
1294
1295 if ((type == LOAD_COMMON_CLIENT) || (type == LOAD_COMMON_CLIENT_PUSHED))
1296 {
1297 auth_nocache = opt.exists("auth-nocache");
1298 }
1299 }
1300
1301 std::string relay_prefix(const char *optname) const
1302 {
1303 std::string ret;
1304 if (relay_mode)
1305 ret = "relay-";
1306 ret += optname;
1307 return ret;
1308 }
1309 };
1310
1311 // Used to describe an incoming network packet
1313 {
1314 friend class ProtoContext;
1315
1316 enum
1317 {
1318 DEFINED = 1 << 0, // packet is valid (otherwise invalid)
1319 CONTROL = 1 << 1, // packet for control channel (otherwise for data channel)
1320 SECONDARY = 1 << 2, // packet is associated with secondary KeyContext (otherwise primary)
1321 SOFT_RESET = 1 << 3, // packet is a CONTROL_SOFT_RESET_V1 msg indicating a request for SSL/TLS renegotiate
1322 };
1323
1324 public:
1325 bool is_defined() const
1326 {
1327 return flags & DEFINED;
1328 }
1329 bool is_control() const
1330 {
1331 return (flags & (CONTROL | DEFINED)) == (CONTROL | DEFINED);
1332 }
1333 bool is_data() const
1334 {
1335 return (flags & (CONTROL | DEFINED)) == DEFINED;
1336 }
1337 bool is_soft_reset() const
1338 {
1339 return (flags & (CONTROL | DEFINED | SECONDARY | SOFT_RESET))
1341 }
1342 int peer_id() const
1343 {
1344 return peer_id_;
1345 }
1346
1347 private:
1348 PacketType(const Buffer &buf, class ProtoContext &proto)
1350 {
1351 if (likely(buf.size()))
1352 {
1353 // get packet header byte
1354 const unsigned int op = buf[0];
1355
1356 // examine opcode
1357 {
1358 const unsigned int opc = opcode_extract(op);
1359 switch (opc)
1360 {
1362 case CONTROL_V1:
1363 case ACK_V1:
1364 {
1365 flags |= CONTROL;
1366 opcode = opc;
1367 break;
1368 }
1369 case DATA_V2:
1370 {
1371 if (unlikely(buf.size() < 4))
1372 return;
1373 std::uint32_t opi;
1374 // avoid unaligned access
1375 std::memcpy(&opi, buf.c_data(), sizeof(opi));
1376 opi = ntohl(opi) & 0x00FFFFFF;
1377 if (opi != OP_PEER_ID_UNDEF)
1378 peer_id_ = opi;
1379 opcode = opc;
1380 break;
1381 }
1382 case DATA_V1:
1383 {
1384 opcode = opc;
1385 break;
1386 }
1389 {
1390 if (!proto.is_server())
1391 return;
1392 flags |= CONTROL;
1393 opcode = opc;
1394 break;
1395 }
1397 if (proto.is_server())
1398 return;
1399 [[fallthrough]];
1400 case CONTROL_WKC_V1:
1401 {
1402 flags |= CONTROL;
1403 opcode = opc;
1404 break;
1405 }
1406 default:
1407 return;
1408 }
1409 }
1410
1411 // examine key ID
1412 {
1413 const unsigned int kid = key_id_extract(op);
1414 if (proto.primary && kid == proto.primary->key_id())
1415 flags |= DEFINED;
1416 else if (proto.secondary && kid == proto.secondary->key_id())
1417 flags |= (DEFINED | SECONDARY);
1418 else if (opcode == CONTROL_SOFT_RESET_V1 && kid == proto.upcoming_key_id)
1420 }
1421 }
1422 }
1423
1424 unsigned int flags;
1425 unsigned int opcode;
1427 };
1428
1429 static const char *opcode_name(const unsigned int opcode)
1430 {
1431 switch (opcode)
1432 {
1434 return "CONTROL_SOFT_RESET_V1";
1435 case CONTROL_V1:
1436 return "CONTROL_V1";
1437 case ACK_V1:
1438 return "ACK_V1";
1439 case DATA_V1:
1440 return "DATA_V1";
1441 case DATA_V2:
1442 return "DATA_V2";
1444 return "CONTROL_HARD_RESET_CLIENT_V2";
1446 return "CONTROL_HARD_RESET_CLIENT_V3";
1448 return "CONTROL_HARD_RESET_SERVER_V2";
1449 case CONTROL_WKC_V1:
1450 return "CONTROL_WKC_V1";
1451 }
1452 return nullptr;
1453 }
1454
1455 std::string dump_packet(const Buffer &buf)
1456 {
1457 std::ostringstream out;
1458 try
1459 {
1460 Buffer b(buf);
1461 const size_t orig_size = b.size();
1462 const unsigned int op = b.pop_front();
1463
1464 const unsigned int opcode = opcode_extract(op);
1465 const char *op_name = opcode_name(opcode);
1466 if (op_name)
1467 out << op_name << '/' << key_id_extract(op);
1468 else
1469 return "BAD_PACKET";
1470
1471 if (opcode == DATA_V1 || opcode == DATA_V2)
1472 {
1473 if (opcode == DATA_V2)
1474 {
1475 const unsigned int p1 = b.pop_front();
1476 const unsigned int p2 = b.pop_front();
1477 const unsigned int p3 = b.pop_front();
1478 const unsigned int peer_id = (p1 << 16) + (p2 << 8) + p3;
1479 if (peer_id != 0xFFFFFF)
1480 out << " PEER_ID=" << peer_id;
1481 }
1482 out << " SIZE=" << b.size() << '/' << orig_size;
1483 }
1484 else
1485 {
1486 {
1487 ProtoSessionID src_psid(b);
1488 out << " SRC_PSID=" << src_psid.str();
1489 }
1490
1492 {
1493 PacketIDControl pid;
1494 pid.read(b);
1495 out << " PID=" << pid.str();
1496
1497 const unsigned char *hmac = b.read_alloc(hmac_size);
1498 out << " HMAC=" << render_hex(hmac, hmac_size);
1499 out << " TLS-CRYPT ENCRYPTED PAYLOAD=" << b.size() << " bytes";
1500 }
1501 else
1502 {
1503 if (tls_wrap_mode == TLS_AUTH)
1504 {
1505 const unsigned char *hmac = b.read_alloc(hmac_size);
1506 out << " HMAC=" << render_hex(hmac, hmac_size);
1507
1508 PacketIDControl pid;
1509 pid.read(b);
1510 out << " PID=" << pid.str();
1511 }
1512
1513 ReliableAck ack{};
1514 ack.read(b);
1515 const bool dest_psid_defined = !ack.empty();
1516 out << " ACK=[";
1517 while (!ack.empty())
1518 {
1519 out << " " << ack.front();
1520 ack.pop_front();
1521 }
1522 out << " ]";
1523
1524 if (dest_psid_defined)
1525 {
1526 ProtoSessionID dest_psid(b);
1527 out << " DEST_PSID=" << dest_psid.str();
1528 }
1529
1530 if (opcode != ACK_V1)
1531 out << " MSG_ID=" << ReliableAck::read_id(b);
1532
1533 out << " SIZE=" << b.size() << '/' << orig_size;
1534 }
1535 }
1536#ifdef OPENVPN_DEBUG_PROTO_DUMP
1537 out << '\n'
1539#endif
1540 }
1541 catch (const std::exception &e)
1542 {
1543 out << " EXCEPTION: " << e.what();
1544 }
1545 return out.str();
1546 }
1547
1548 // used for reading/writing authentication strings (username, password, etc.) from buffer using the
1549 // 2 byte prefix for length
1550 static void write_uint16_length(const size_t size, Buffer &buf)
1551 {
1552 if (size > 0xFFFF)
1553 throw proto_error("auth_string_overflow");
1554 const std::uint16_t net_size = htons(static_cast<std::uint16_t>(size));
1555 buf.write((const unsigned char *)&net_size, sizeof(net_size));
1556 }
1557
1558 static uint16_t read_uint16_length(Buffer &buf)
1559 {
1560 if (!buf.empty())
1561 {
1562 std::uint16_t net_size;
1563 buf.read((unsigned char *)&net_size, sizeof(net_size));
1564 return ntohs(net_size);
1565 }
1566 return 0;
1567 }
1568
1569 template <typename S>
1570 static void write_auth_string(const S &str, Buffer &buf)
1571 {
1572 const size_t len = str.length();
1573 if (len)
1574 {
1575 write_uint16_length(len + 1, buf);
1576 buf.write((const unsigned char *)str.c_str(), len);
1577 buf.null_terminate();
1578 }
1579 else
1580 write_uint16_length(0, buf);
1581 }
1582
1583 template <typename S>
1585 {
1586 const size_t len = read_uint16_length(buf);
1587 if (len)
1588 {
1589 const char *data = (const char *)buf.read_alloc(len);
1590 if (len > 1)
1591 return S(data, len - 1);
1592 }
1593 return S();
1594 }
1595
1596 template <typename S>
1597 static void write_control_string(const S &str, Buffer &buf)
1598 {
1599 const size_t len = str.length();
1600 buf.write((const unsigned char *)str.c_str(), len);
1601 buf.null_terminate();
1602 }
1603
1604 static void write_empty_string(Buffer &buf)
1605 {
1606 write_uint16_length(0, buf);
1607 }
1608
1609 template <typename S>
1610 static S read_control_string(const Buffer &buf)
1611 {
1612 size_t size = buf.size();
1613 if (size)
1614 {
1615 /* Trim any trailing \n or \r or 0x00 characters. Scripts plugin sometimes accidentally include a \n or \r\n in AUTH_FAILED
1616 * or similar messages */
1617 while (size > 0 && (buf[size - 1] == 0 || buf[size - 1] == '\r' || buf[size - 1] == '\n'))
1618 {
1619 --size;
1620 }
1621
1622 if (size)
1623 {
1624 return S{reinterpret_cast<const char *>(buf.c_data()), size};
1625 }
1626 }
1627 return {};
1628 }
1629
1630 template <typename S>
1631 void write_control_string(const S &str)
1632 {
1633 const size_t len = str.length();
1634 auto bp = BufferAllocatedRc::Create(len + 1);
1635 write_control_string(str, *bp);
1636 control_send(std::move(bp));
1637 }
1638
1639 // Packet structure for managing network packets, passed as a template
1640 // parameter to ProtoStackBase
1642 {
1643 friend class ProtoContext;
1644
1645 public:
1647 {
1648 reset_non_buf();
1649 }
1650
1651 Packet(BufferPtr &&buf_arg, const unsigned int opcode_arg = CONTROL_V1)
1652 : opcode(opcode_arg), buf(std::move(buf_arg))
1653 {
1654 }
1655
1656 // clone packet, including buffer content
1658 {
1659 Packet pkt;
1660 pkt.opcode = opcode;
1662 return pkt;
1663 }
1664
1665 void reset()
1666 {
1667 reset_non_buf();
1668 buf.reset();
1669 }
1670
1671 void frame_prepare(const Frame &frame, const unsigned int context)
1672 {
1673 if (!buf)
1675 frame.prepare(context, *buf);
1676 }
1677
1683 {
1684 return opcode == CONTROL_V1 || opcode == CONTROL_WKC_V1;
1685 }
1686 operator bool() const
1687 {
1688 return bool(buf);
1689 }
1691 {
1692 return buf;
1693 }
1694 const Buffer &buffer() const
1695 {
1696 return *buf;
1697 }
1698
1699 private:
1701 {
1703 }
1704
1705 unsigned int opcode;
1707 };
1708
1709 // KeyContext encapsulates a single SSL/TLS session.
1710 // ProtoStackBase uses CRTP-based static polymorphism for method callbacks.
1711 class KeyContext : ProtoStackBase<Packet, KeyContext>, public RC<thread_unsafe_refcount>
1712 {
1714 friend Base;
1715#ifdef UNIT_TEST
1716 // test seam: lets ProtoContext::force_resend_wkc() set resend_wkc
1717 friend class ProtoContext;
1718#endif
1721
1722 // ProtoStackBase protected vars
1723 using Base::now;
1724 using Base::rel_recv;
1725 using Base::rel_send;
1726 using Base::xmit_acks;
1727
1728 // ProtoStackBase member functions
1729 using Base::raw_send;
1732
1733 // Helper for handling deferred data channel setup,
1734 // for example if cipher/digest are pushed.
1736 {
1738 std::optional<CryptoDCInstance::RekeyType> rekey_type;
1739 };
1740
1741 public:
1743
1744 // ProtoStackBase member functions
1746
1747 OPENVPN_SIMPLE_EXCEPTION(tls_crypt_unwrap_wkc_error);
1748
1749 // KeyContext events occur on two basic key types:
1750 // Primary Key -- the key we transmit/encrypt on.
1751 // Secondary Key -- new keys and retiring keys.
1752 //
1753 // The very first key created (key_id == 0) is a
1754 // primary key. Subsequently created keys are always,
1755 // at least initially, secondary keys. Secondary keys
1756 // promote to primary via the KEV_BECOME_PRIMARY event
1757 // (actually KEV_BECOME_PRIMARY swaps the primary and
1758 // secondary keys, so the old primary is demoted
1759 // to secondary and marked for expiration).
1760 //
1761 // Secondary keys are created by:
1762 // 1. locally-generated soft renegotiation requests, and
1763 // 2. peer-requested soft renegotiation requests.
1764 // In each case, any previous secondary key will be
1765 // wiped (including a secondary key that exists due to
1766 // demotion of a previous primary key that has been marked
1767 // for expiration).
1769 {
1771
1772 // KeyContext has reached the ACTIVE state, occurs on both
1773 // primary and secondary.
1775
1776 // SSL/TLS negotiation must complete by this time. If this
1777 // event is hit on the first primary (i.e. first KeyContext
1778 // with key_id == 0), it is fatal to the session and will
1779 // trigger a disconnect/reconnect. If it's hit on the
1780 // secondary, it will trigger a soft renegotiation.
1782
1783 // When a KeyContext (normally the secondary) is scheduled
1784 // to transition to the primary state.
1786
1787 // Waiting for condition on secondary (usually
1788 // dataflow-based) to trigger KEV_BECOME_PRIMARY.
1790
1791 // Start renegotiating a new KeyContext on secondary
1792 // (ignored unless originating on primary).
1794
1795 // Trigger a renegotiation originating from either
1796 // primary or secondary.
1798
1799 // Queue delayed renegotiation request from secondary
1800 // to take effect after KEV_BECOME_PRIMARY.
1802
1803 // Expiration of KeyContext.
1805 };
1806
1807 // for debugging
1808 static const char *event_type_string(const EventType et)
1809 {
1810 switch (et)
1811 {
1812 case KEV_NONE:
1813 return "KEV_NONE";
1814 case KEV_ACTIVE:
1815 return "KEV_ACTIVE";
1816 case KEV_NEGOTIATE:
1817 return "KEV_NEGOTIATE";
1818 case KEV_BECOME_PRIMARY:
1819 return "KEV_BECOME_PRIMARY";
1821 return "KEV_PRIMARY_PENDING";
1822 case KEV_RENEGOTIATE:
1823 return "KEV_RENEGOTIATE";
1825 return "KEV_RENEGOTIATE_FORCE";
1827 return "KEV_RENEGOTIATE_QUEUE";
1828 case KEV_EXPIRE:
1829 return "KEV_EXPIRE";
1830 default:
1831 return "KEV_?";
1832 }
1833 }
1834
1835 KeyContext(ProtoContext &p, const bool initiator, bool psid_cookie_mode = false)
1836 : Base(*p.config->ssl_factory,
1837 p.config->now,
1839 p.config->frame,
1840 p.stats,
1841 psid_cookie_mode),
1842 proto(p),
1844 crypto_flags(0),
1845 dirty(0),
1847 tlsprf(p.config->tlsprf_factory->new_obj(p.is_server()))
1848 {
1849 // reliable protocol?
1850 set_protocol(proto.config->protocol);
1851
1852 // get key_id from parent
1854
1855 // set initial state
1856 set_state((proto.is_server() ? S_INITIAL : C_INITIAL) + (initiator ? 0 : 1));
1857
1858 // cache stuff that we need to access in hot path
1859 cache_op32();
1860
1861 // remember when we were constructed
1863
1864 // set must-negotiate-by time
1866 }
1867
1868 void set_protocol(const Protocol &p)
1869 {
1870 is_reliable = p.is_reliable(); // cache is_reliable state locally
1871 }
1872
1873 uint32_t get_tls_warnings() const
1874 {
1875 return Base::get_tls_warnings();
1876 }
1877
1885 void start(const ProtoSessionID cookie_psid = ProtoSessionID())
1886 {
1887 if (cookie_psid.defined())
1888 {
1890 dirty = true;
1891 }
1892 if (state == C_INITIAL || state == S_INITIAL)
1893 {
1894 send_reset();
1895 set_state(state + 1);
1896 dirty = true;
1897 }
1898 }
1899
1900 // control channel flush
1901 void flush()
1902 {
1903 if (dirty)
1904 {
1906 Base::flush();
1908 dirty = false;
1909 }
1910 }
1911
1912 void invalidate(const Error::Type reason)
1913 {
1914 Base::invalidate(reason);
1915 }
1916
1917 // retransmit packets as part of reliability layer
1919 {
1920 // note that we don't set dirty here
1922 }
1923
1924 // when should we next call retransmit method
1926 {
1927 const Time t = Base::next_retransmit();
1928 if (t <= next_event_time)
1929 return t;
1930 return next_event_time;
1931 }
1932
1934 {
1935 if (bp->size() > APP_MSG_MAX)
1936 throw proto_error("app_send: sent control message is too large");
1937 Base::app_send(std::move(bp));
1938 }
1939
1940 // send app-level cleartext data to peer via SSL
1942 {
1943 if (state >= ACTIVE)
1944 {
1945 app_send_validate(std::move(bp));
1946 dirty = true;
1947 }
1948 else
1949 app_pre_write_queue.push_back(bp);
1950 }
1951
1952 // pass received ciphertext packets on network to SSL/reliability layers
1953 bool net_recv(Packet &&pkt)
1954 {
1955 const bool ret = Base::net_recv(std::move(pkt));
1956 dirty = true;
1957 return ret;
1958 }
1959
1960 // data channel encrypt
1962 {
1963 if (state >= ACTIVE
1965 && !invalidated())
1966 {
1967 // compress and encrypt packet and prepend op header
1968 const bool pid_wrap = do_encrypt(buf, true);
1969
1970 // Trigger a new SSL/TLS negotiation if packet ID (a 32-bit unsigned int)
1971 // is getting close to wrapping around. If it wraps back to 0 without
1972 // a renegotiation, it would cause the replay protection logic to wrongly
1973 // think that all further packets are replays.
1974 if (pid_wrap)
1976 }
1977 else
1978 buf.reset_size(); // no crypto context available
1979 }
1980
1981 // data channel decrypt
1983 {
1984 try
1985 {
1986 if (state >= ACTIVE
1988 && !invalidated())
1989 {
1990 // Knock off leading op from buffer, but pass the 32-bit version to
1991 // decrypt so it can be used as Additional Data for packet authentication.
1992 const size_t head_size = op_head_size(buf[0]);
1993 const unsigned char *op32 = (head_size == OP_SIZE_V2) ? buf.c_data() : nullptr;
1994 buf.advance(head_size);
1995
1996 // decrypt packet
1997 const Error::Type err = crypto->decrypt(buf, now->seconds_since_epoch(), op32);
1998 if (err)
1999 {
2000 proto.stats->error(err);
2001 if (proto.is_tcp() && (err == Error::DECRYPT_ERROR || err == Error::HMAC_ERROR))
2002 invalidate(err);
2003 }
2004
2005 // trigger renegotiation if we hit decrypt data limit
2006 if (data_limit)
2008 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "Unable to add data limit");
2009
2010 // decompress packet
2011 if (compress)
2012 compress->decompress(buf);
2013
2014 // set MSS for segments server can receive
2015 if (proto.config->mss_fix > 0)
2016 MSSFix::mssfix(buf, numeric_cast<uint16_t>(proto.config->mss_fix));
2017 }
2018 else
2019 buf.reset_size(); // no crypto context available
2020 }
2021 catch (std::exception &)
2022 {
2024 buf.reset_size();
2025 if (proto.is_tcp())
2027 }
2028 }
2029
2030 // usually called by parent ProtoContext object when this KeyContext
2031 // has been retired.
2033 {
2034 set_event(current_ev,
2035 KEV_EXPIRE,
2037 }
2038
2039 // set a default next event, if unspecified
2041 {
2042 if (next_event == KEV_NONE && !invalidated())
2044 }
2045
2046 // set a key limit renegotiation event at time t
2047 void key_limit_reneg(const EventType ev, const Time &t)
2048 {
2049 if (t.defined())
2050 set_event(KEV_NONE, ev, t + Time::Duration::seconds(proto.is_server() ? 2 : 1));
2051 }
2052
2053 // return time of upcoming KEV_BECOME_PRIMARY event
2055 {
2057 return next_event_time;
2058 return Time();
2059 }
2060
2061 // is an KEV_x event pending?
2063 {
2066 return current_event != KEV_NONE;
2067 }
2068
2069 // get KEV_x event
2071 {
2072 return current_event;
2073 }
2074
2075 // clear KEV_x event
2077 {
2079 }
2080
2081 // was session invalidated by an exception?
2082 bool invalidated() const
2083 {
2084 return Base::invalidated();
2085 }
2086
2087 // Reason for invalidation
2089 {
2091 }
2092
2093 // our Key ID in the OpenVPN protocol
2094 unsigned int key_id() const
2095 {
2096 return key_id_;
2097 }
2098
2099 // indicates that data channel is keyed and ready to encrypt/decrypt packets
2101 {
2102 return state >= ACTIVE;
2103 }
2104
2105 bool is_dirty() const
2106 {
2107 return dirty;
2108 }
2109
2110 // notification from parent of rekey operation
2112 {
2113 if (crypto)
2114 crypto->rekey(type);
2115 else if (data_channel_key)
2116 {
2117 // save for deferred processing
2118 data_channel_key->rekey_type = type;
2119 }
2120 }
2121
2122 // time that our state transitioned to ACTIVE
2124 {
2125 return reached_active_time_;
2126 }
2127
2128 // transmit a keepalive message to peer
2130 {
2131 send_data_channel_message(proto_context_private::keepalive_message,
2132 sizeof(proto_context_private::keepalive_message));
2133 }
2134
2135 // send explicit-exit-notify message to peer
2137 {
2140 else
2141 send_data_channel_message(proto_context_private::explicit_exit_notify_message,
2142 sizeof(proto_context_private::explicit_exit_notify_message));
2143 }
2144
2145 // general purpose method for sending constant string messages
2146 // to peer via data channel
2147 void send_data_channel_message(const unsigned char *data, const size_t size)
2148 {
2149 if (state >= ACTIVE
2151 && !invalidated())
2152 {
2153 // allocate packet
2154 Packet pkt;
2156
2157 // write keepalive message
2158 pkt.buf->write(data, size);
2159
2160 // process packet for transmission
2161 do_encrypt(*pkt.buf, false); // set compress hint to "no"
2162
2163 // send it
2164 proto.net_send(key_id_, pkt);
2165 }
2166 }
2167
2168 // validate the integrity of a packet
2169 static bool validate(const Buffer &net_buf, ProtoContext &proto, TimePtr now)
2170 {
2171 try
2172 {
2173 Buffer recv(net_buf);
2174
2175 switch (proto.tls_wrap_mode)
2176 {
2177 case TLS_AUTH:
2178 return validate_tls_auth(recv, proto, now);
2179 case TLS_CRYPT_V2:
2181 {
2182 // skip validation of HARD_RESET_V3 because the tls-crypt
2183 // engine has not been initialized yet
2184 OVPN_LOG_VERBOSE("SKIPPING VALIDATION OF HARD_RESET_V3");
2185 return true;
2186 }
2187 /* no break */
2188 case TLS_CRYPT:
2189 return validate_tls_crypt(recv, proto, now);
2190 case TLS_PLAIN:
2191 return validate_tls_plain(recv, proto, now);
2192 }
2193 }
2194 catch ([[maybe_unused]] BufferException &e)
2195 {
2196 OVPN_LOG_VERBOSE("validate() exception: " << e.what());
2197 }
2198 return false;
2199 }
2200
2201 // Resets data_channel_key but also retains old
2202 // rekey_defined and rekey_type from previous instance.
2204 {
2205 std::unique_ptr<DataChannelKey> dck(new DataChannelKey());
2206
2207 if (proto.config->dc.key_derivation() == CryptoAlgs::KeyDerivation::TLS_EKM)
2208 {
2209 // USE RFC 5705 key material export
2210 export_key_material(dck->key, "EXPORTER-OpenVPN-datakeys");
2211 }
2212 else
2213 {
2214 // use the TLS PRF construction to exchange session keys for building
2215 // the data channel crypto context
2217 }
2218 tlsprf->erase();
2220 << " KEY " << CryptoAlgs::name(proto.config->dc.key_derivation())
2221 << " " << proto.mode().str() << ' ' << dck->key.render());
2222
2223 if (data_channel_key)
2224 {
2225 dck->rekey_type = data_channel_key->rekey_type;
2226 }
2227 dck.swap(data_channel_key);
2228 }
2229
2231 {
2232 if (c.mss_parms.fixed)
2233 {
2234 // substract IPv4 and TCP overhead, mssfix method will add extra 20 bytes for IPv6
2235 c.mss_fix = c.mss_parms.mssfix - (20 + 20);
2236 OPENVPN_LOG("fixed mssfix=" << c.mss_fix);
2237 return;
2238 }
2239
2240 /* If we are running default mssfix but have a different tun-mtu pushed
2241 * disable mssfix */
2242 if (c.tun_mtu != TUN_MTU_DEFAULT && c.tun_mtu != 0 && c.mss_parms.mssfix_default)
2243 {
2244 c.mss_fix = 0;
2245 OPENVPN_LOG("mssfix disabled since tun-mtu is non-default ("
2246 << c.tun_mtu << ")");
2247 return;
2248 }
2249
2250 auto payload_overhead = size_t(0);
2251
2252 // compv2 doesn't increase payload size
2253 switch (c.comp_ctx.type())
2254 {
2258 break;
2259 default:
2260 payload_overhead += 1;
2261 }
2262
2264 payload_overhead += PacketIDData::size(false);
2265
2266 // account for IPv4 and TCP headers of the payload, mssfix method
2267 // will add 20 extra bytes if payload is IPv6
2268 payload_overhead += 20 + 20;
2269
2270 auto overhead = c.protocol.extra_transport_bytes()
2271 + (enable_op32 ? OP_SIZE_V2 : 1)
2272 + c.dc.context().encap_overhead();
2273
2274 // in CBC mode, the packet id is part of the payload size / overhead
2276 overhead += PacketIDData::size(false);
2277
2278 if (c.mss_parms.mtu)
2279 {
2280 overhead += c.protocol.is_ipv6()
2281 ? sizeof(struct IPv6Header)
2282 : sizeof(struct IPv4Header);
2283 overhead += proto.is_tcp()
2284 ? sizeof(struct TCPHeader)
2285 : sizeof(struct UDPHeader);
2286 }
2287
2288 auto target = c.mss_parms.mssfix - overhead;
2289 if (CryptoAlgs::mode(c.dc.cipher()) == CryptoAlgs::CBC_HMAC)
2290 {
2291 // openvpn3 crypto includes blocksize in overhead, but we can
2292 // be a bit smarter here and instead make sure that resulting
2293 // ciphertext size (which is always multiple blocksize) is not
2294 // larger than target by running down target to the nearest
2295 // multiple of multiple and substracting 1.
2296
2297 auto block_size = CryptoAlgs::block_size(c.dc.cipher());
2298 target += block_size;
2299 target = (target / block_size) * block_size;
2300 target -= 1;
2301 }
2302
2303 if (!is_safe_conversion<decltype(c.mss_fix)>(target - payload_overhead))
2304 {
2305 OPENVPN_LOG("mssfix disabled since computed value is outside type bounds ("
2306 << c.mss_fix << ")");
2307 c.mss_fix = 0;
2308 return;
2309 }
2310
2311 c.mss_fix = static_cast<decltype(c.mss_fix)>(target - payload_overhead);
2312 OVPN_LOG_VERBOSE("mssfix=" << c.mss_fix
2313 << " (upper bound=" << c.mss_parms.mssfix
2314 << ", overhead=" << overhead
2315 << ", payload_overhead=" << payload_overhead
2316 << ", target=" << target << ")");
2317 }
2318
2319 // Initialize the components of the OpenVPN data channel protocol
2321 {
2322 // don't run until our prerequisites are satisfied
2323 if (!data_channel_key)
2324 return;
2326
2327 // set up crypto for data channel
2328 bool enable_compress = true;
2329 ProtoConfig &c = *proto.config;
2330 const unsigned int key_dir = proto.is_server() ? OpenVPNStaticKey::INVERSE : OpenVPNStaticKey::NORMAL;
2331 const OpenVPNStaticKey &key = data_channel_key->key;
2332
2333 // special data limits for 64-bit block-size ciphers (CVE-2016-6329)
2334 if (is_bs64_cipher(c.dc.cipher()))
2335 {
2339 OVPN_LOG_INFO("Per-Key Data Limit: "
2340 << dp.encrypt_red_limit << '/' << dp.decrypt_red_limit);
2341 data_limit.reset(new DataLimit(dp));
2342 }
2343
2344 // build crypto context for data channel encryption/decryption
2347
2352
2356
2357 crypto->init_pid("DATA",
2358 int(key_id_),
2359 proto.stats);
2360
2362
2363 enable_compress = crypto->consider_compression(proto.config->comp_ctx);
2364
2365 if (data_channel_key->rekey_type.has_value())
2366 crypto->rekey(data_channel_key->rekey_type.value());
2367 data_channel_key.reset();
2368
2369 // set up compression for data channel
2370 if (enable_compress)
2371 compress = proto.config->comp_ctx.new_compressor(proto.config->frame, proto.stats);
2372 else
2373 compress.reset();
2374
2375 // cache op32 for hot path in do_encrypt
2376 cache_op32();
2377
2379 }
2380
2382 const DataLimit::State cdl_status)
2383 {
2384 if (data_limit)
2385 data_limit_event(cdl_mode, data_limit->update_state(cdl_mode, cdl_status));
2386 }
2387
2388 int get_state() const
2389 {
2390 return state;
2391 }
2392
2399 static size_t tls_crypt_frame_size(const ProtoConfig &proto_config)
2400 {
2402 + proto_config.tls_crypt_context->digest_size()
2403 // the following is the tls-crypt payload
2404 + sizeof(char) // length of ACK array
2405 + sizeof(id_t); // reliable ID
2406 }
2407
2415 static size_t wkc_overhead(const ProtoConfig &proto_config)
2416 {
2417 return sizeof(uint16_t)
2418 + proto_config.tls_crypt_context->digest_size()
2419 + (proto_config.tls_crypt_v2_serverkey_id ? sizeof(uint32_t) : 0);
2420 }
2421
2436 static bool trailing_wkc_len(const Buffer &recv,
2437 const ProtoConfig &proto_config,
2438 const size_t min_wkc_len,
2439 uint16_t &wkc_len)
2440 {
2441 const size_t frame_size = tls_crypt_frame_size(proto_config);
2442 const size_t orig_size = recv.size();
2443
2444 if (orig_size < (frame_size + sizeof(wkc_len)))
2445 return false;
2446
2447 // avoid unaligned access
2448 std::memcpy(&wkc_len, recv.c_data() + orig_size - sizeof(wkc_len), sizeof(wkc_len));
2449 wkc_len = ntohs(wkc_len);
2450
2451 return wkc_len >= min_wkc_len && wkc_len <= (orig_size - frame_size);
2452 }
2453
2462 {
2464 int type = -1;
2466 };
2467
2481
2492 const ProtoConfig &proto_config,
2494 UnwrappedWkc &unwrapped)
2495 {
2496 // the ``WKc`` is located at the end of the packet, after the tls-crypt
2497 // payload.
2498 //
2499 // K_id is optional, and controlled by proto_config.tls_crypt_v2_serverkey_id.
2500 // If it is missing, we will use a single server key for all clients.
2501 //
2502 // Format is as follows:
2503 //
2504 // ``len = len(WKc)`` (16 bit, network byte order)
2505 // ``T = HMAC-SHA256(Ka, len || K_id || Kc || metadata)``
2506 // ``IV = 128 most significant bits of T``
2507 // ``WKc = T || AES-256-CTR(Ke, IV, Kc || metadata) || K_id || len``
2508
2509 const unsigned char *orig_data = recv.data();
2510 const size_t orig_size = recv.size();
2511 const size_t hmac_size = proto_config.tls_crypt_context->digest_size();
2512 const size_t tls_frame_size = tls_crypt_frame_size(proto_config);
2513
2514 uint32_t k_id = 0;
2515 const size_t serverkey_id_size = proto_config.tls_crypt_v2_serverkey_id ? sizeof(k_id) : 0;
2516
2517 // Establishes ``wkc_overhead() <= wkc_len <= orig_size - tls_frame_size``, so
2518 // the WKc holds its own length field, the authentication tag ``T`` and the
2519 // optional ``K_id``, and fits behind the tls-crypt frame. Both wkc_raw_size
2520 // expressions below then come to at least ``hmac_size + serverkey_id_size``,
2521 // which is what keeps the ``K_id`` read and the ciphertext length handed to
2522 // decrypt() from underflowing.
2523 uint16_t wkc_len;
2524 if (!trailing_wkc_len(recv, proto_config, wkc_overhead(proto_config), wkc_len))
2525 return Error::CC_ERROR;
2526
2527 // A CONTROL_HARD_RESET_CLIENT_V3 carries nothing but the ``WKc`` behind the
2528 // tls-crypt frame, so its extent follows from the sizes; a P_CONTROL_WKC_V1
2529 // carries a payload as well, and only ``wkc_len`` locates the ``WKc`` in it.
2530 const unsigned char *wkc_raw;
2531 size_t wkc_raw_size;
2532 if (opcode_extract(orig_data[0]) == CONTROL_HARD_RESET_CLIENT_V3)
2533 {
2534 wkc_raw = orig_data + tls_frame_size;
2535 wkc_raw_size = orig_size - tls_frame_size - sizeof(wkc_len);
2536 }
2537 else
2538 {
2539 wkc_raw = orig_data + orig_size - wkc_len;
2540 wkc_raw_size = wkc_len - sizeof(wkc_len);
2541 }
2542
2543 if (proto_config.tls_crypt_v2_serverkey_id)
2544 {
2545 std::memcpy(&k_id, wkc_raw + wkc_raw_size - serverkey_id_size, sizeof(k_id));
2546 k_id = ntohl(k_id);
2547 }
2548
2549 // length sanity check (the size of the ``len`` field is included in the value)
2550 if ((wkc_len - sizeof(uint16_t)) != wkc_raw_size)
2551 return Error::CC_ERROR;
2552
2554 // plaintext will be used to compute the Auth Tag, therefore start by prepending
2555 // the WKc length in network order
2556 const uint16_t net_wkc_len = htons(wkc_len);
2557 plaintext.write(&net_wkc_len, sizeof(net_wkc_len));
2558
2559 if (proto_config.tls_crypt_v2_serverkey_id)
2560 {
2561 std::stringstream ss;
2562 ss << std::hex << std::setfill('0') << std::uppercase << std::setw(8) << k_id;
2563
2564 const std::string serverkey_fn = ss.str() + ".key";
2565 const std::string serverkey_path = proto_config.tls_crypt_v2_serverkey_dir + "/"
2566 + serverkey_fn.substr(0, 2) + "/" + serverkey_fn;
2567
2568 // The K_id came off the wire, so a client whose key we never had -- or a
2569 // forgery -- names a file that is not there. That is a WKc we cannot unwrap
2570 // and nothing more, so nothing here may leave as an exception: decapsulate()
2571 // catches BufferException alone and open_file_error is not one.
2572 try
2573 {
2574 TLSCryptV2ServerKey tls_crypt_v2_key;
2575 tls_crypt_v2_key.parse(read_text(serverkey_path));
2576
2577 // Ka/Ke are of use only for the unwrap they key below, so they stay here
2578 // rather than on the config the cookie layer shares between sessions.
2579 OpenVPNStaticKey serverkey_material;
2580 tls_crypt_v2_key.extract_key(serverkey_material);
2581
2582 // the server key is composed by one key set only, therefore direction and
2583 // mode should not be specified when slicing
2584 tls_crypt_server.init(proto_config.ssl_factory->libctx(),
2585 serverkey_material.slice(OpenVPNStaticKey::HMAC),
2586 serverkey_material.slice(OpenVPNStaticKey::CIPHER));
2587 }
2588 catch (const std::exception &e)
2589 {
2590 OVPN_LOG_VERBOSE("DROPPING WKc NAMING TLS-crypt-V2 server key "
2591 << serverkey_path << ": " << e.what());
2592 return Error::DECRYPT_ERROR;
2593 }
2594
2595 OVPN_LOG_VERBOSE("Using TLS-crypt-V2 server key " << serverkey_path);
2596
2597 k_id = htonl(k_id);
2598 plaintext.write(&k_id, sizeof(k_id));
2599 }
2600 else
2601 {
2602 // Same key for every client, straight off the config. Keying the context is
2603 // this function's business in either mode: a caller that had to do it for one
2604 // mode and not the other could forget.
2605 if (!proto_config.tls_crypt_key.defined())
2606 {
2607 OVPN_LOG_VERBOSE("DROPPING WKc WITH NO TLS-crypt-V2 SERVER KEY TO UNWRAP IT");
2608 return Error::DECRYPT_ERROR;
2609 }
2610
2611 tls_crypt_server.init(proto_config.ssl_factory->libctx(),
2614 }
2615
2616 // the ``len || K_id`` prefix written above is part of the authenticated
2617 // plaintext, but the decrypted key material goes behind it
2618 const size_t plaintext_prefix_size = sizeof(wkc_len) + serverkey_id_size;
2619
2620 const size_t plaintext_max_size = plaintext.max_size();
2621 if (plaintext_max_size <= plaintext_prefix_size)
2622 return Error::DECRYPT_ERROR;
2623
2624 const size_t decrypt_bytes = tls_crypt_server.decrypt(wkc_raw,
2625 plaintext.data() + plaintext_prefix_size,
2626 plaintext_max_size - plaintext_prefix_size,
2627 wkc_raw + hmac_size,
2628 wkc_raw_size - hmac_size - serverkey_id_size);
2629 plaintext.inc_size(decrypt_bytes);
2630
2631 // The decrypted part must hold a full 2048-bit client key; metadata behind it is
2632 // optional. Measure decrypt_bytes, not plaintext.size(), which also counts the
2633 // length prefix and K_id written above.
2634 if (decrypt_bytes < OpenVPNStaticKey::KEY_SIZE)
2635 return Error::DECRYPT_ERROR;
2636
2637 if (!tls_crypt_server.hmac_cmp(wkc_raw, 0, plaintext.c_data(), plaintext.size()))
2638 return Error::HMAC_ERROR;
2639
2640 // we can now remove the WKc length (and the server key ID, if present)
2641 // from the plaintext, as they are not really part of the key material
2642 plaintext.advance(sizeof(wkc_len));
2643
2644 if (proto_config.tls_crypt_v2_serverkey_id)
2645 plaintext.advance(sizeof(k_id));
2646
2647 plaintext.read(unwrapped.client_key.raw_alloc(), OpenVPNStaticKey::KEY_SIZE);
2648
2649 // what is left of the plaintext is the metadata, its type byte in front
2650 if (!plaintext.empty())
2651 unwrapped.metadata.type = plaintext.pop_front();
2652 unwrapped.metadata.payload = std::move(plaintext);
2653
2654 // virtually remove the WKc from the packet
2655 recv.set_size(orig_size - wkc_len);
2656
2657 return Error::SUCCESS;
2658 }
2659
2676 static bool strip_resent_wkc(Buffer &recv, const ProtoConfig &proto_config)
2677 {
2678 // nothing is unwrapped here, but a WKc that could not hold the client key is
2679 // malformed all the same
2680 uint16_t wkc_len;
2681 if (!trailing_wkc_len(recv,
2682 proto_config,
2684 wkc_len))
2685 return false;
2686
2687 recv.set_size(recv.size() - wkc_len);
2688
2689 return true;
2690 }
2691
2692 private:
2694 {
2695 const unsigned char *orig_data = recv.data();
2696 const size_t orig_size = recv.size();
2697
2698 // advance buffer past initial op byte
2699 recv.advance(1);
2700
2701 // get source PSID
2702 ProtoSessionID src_psid(recv);
2703
2704 // verify HMAC
2705 {
2706 recv.advance(proto.hmac_size);
2707 if (!proto.ta_hmac_recv->ovpn_hmac_cmp(orig_data,
2708 orig_size,
2712 {
2713 return false;
2714 }
2715 }
2716
2717 // verify source PSID
2718 if (!proto.psid_peer.match(src_psid))
2719 return false;
2720
2721 // read tls_auth packet ID
2722 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
2723
2724 // get current time_t
2726
2727 // verify tls_auth packet ID
2728 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
2729
2730 // make sure that our own PSID is contained in packet received from peer
2731 if (ReliableAck::ack_skip(recv))
2732 {
2733 ProtoSessionID dest_psid(recv);
2734 if (!proto.psid_self.match(dest_psid))
2735 return false;
2736 }
2737
2738 return pid_ok;
2739 }
2740
2742 {
2743 // in TLS_CRYPT_V2 mode the receive context stays unset until a WKc has been
2744 // unwrapped, so a packet reaching here before that has nothing to be judged
2745 // with -- whichever opcodes validate() lets past it
2746 if (!proto.tls_crypt_recv)
2747 return false;
2748
2749 const unsigned char *orig_data = recv.data();
2750 const size_t orig_size = recv.size();
2751
2752 // advance buffer past initial op byte
2753 recv.advance(1);
2754 // get source PSID
2755 ProtoSessionID src_psid(recv);
2756 // read tls_auth packet ID
2757 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
2758
2759 recv.advance(proto.hmac_size);
2760
2761 const size_t head_size = OPCODE_SIZE + ProtoSessionID::SIZE + PacketIDControl::size();
2762 const size_t data_offset = head_size + proto.hmac_size;
2763 if (orig_size < data_offset)
2764 return false;
2765
2766 // we need a buffer to perform the payload decryption and being this a static
2767 // function we can't use the instance member like in decapsulate_tls_crypt()
2769 proto.config->frame->prepare(Frame::DECRYPT_WORK, work);
2770
2771 // decrypt payload from 'recv' into 'work'
2772 const size_t decrypt_bytes = proto.tls_crypt_recv->decrypt(orig_data + head_size,
2773 work.data(),
2774 work.max_size(),
2775 recv.c_data(),
2776 recv.size());
2777 if (!decrypt_bytes)
2778 return false;
2779
2780 work.inc_size(decrypt_bytes);
2781
2782 // verify HMAC
2783 if (!proto.tls_crypt_recv->hmac_cmp(orig_data,
2785 work.c_data(),
2786 work.size()))
2787 return false;
2788
2789 // verify source PSID
2790 if (proto.psid_peer.defined())
2791 {
2792 if (!proto.psid_peer.match(src_psid))
2793 return false;
2794 }
2795 else
2796 {
2797 proto.psid_peer = src_psid;
2798 }
2799
2800 // get current time_t
2802
2803 // verify tls_auth packet ID
2804 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
2805 // make sure that our own PSID is contained in packet received from peer
2807 {
2808 ProtoSessionID dest_psid(work);
2809 if (!proto.psid_self.match(dest_psid))
2810 return false;
2811 }
2812
2813 return pid_ok;
2814 }
2815
2817 {
2818 // advance buffer past initial op byte
2819 recv.advance(1);
2820
2821 // verify source PSID
2822 ProtoSessionID src_psid(recv);
2823 if (!proto.psid_peer.match(src_psid))
2824 return false;
2825
2826 // make sure that our own PSID is contained in packet received from peer
2827 if (ReliableAck::ack_skip(recv))
2828 {
2829 ProtoSessionID dest_psid(recv);
2830 if (!proto.psid_self.match(dest_psid))
2831 return false;
2832 }
2833 return true;
2834 }
2835
2836 bool do_encrypt(BufferAllocated &buf, const bool compress_hint)
2837 {
2838 if (!is_safe_conversion<uint16_t>(proto.config->mss_fix))
2839 return false;
2840
2841 // set MSS for segments client can receive
2842 if (proto.config->mss_fix > 0)
2843 MSSFix::mssfix(buf, static_cast<uint16_t>(proto.config->mss_fix));
2844
2845 // compress packet
2846 if (compress)
2847 compress->compress(buf, compress_hint);
2848
2849 // trigger renegotiation if we hit encrypt data limit
2850 if (data_limit)
2852 return false;
2853
2854 bool pid_wrap;
2855
2856 if (enable_op32)
2857 {
2858 const std::uint32_t op32 = htonl(op32_compose(DATA_V2, key_id_, remote_peer_id));
2859
2860 static_assert(sizeof(op32) == OP_SIZE_V2, "OP_SIZE_V2 inconsistency");
2861
2862 // encrypt packet
2863 pid_wrap = crypto->encrypt(buf, (const unsigned char *)&op32);
2864
2865 // prepend op
2866 buf.prepend((const unsigned char *)&op32, sizeof(op32));
2867 }
2868 else
2869 {
2870 // encrypt packet
2871 pid_wrap = crypto->encrypt(buf, nullptr);
2872
2873 // prepend op
2875 }
2876 return pid_wrap;
2877 }
2878
2879 // cache op32 and remote_peer_id
2881 {
2882 enable_op32 = proto.config->enable_op32;
2883 remote_peer_id = proto.config->remote_peer_id;
2884 }
2885
2886 void set_state(const int newstate)
2887 {
2889 << " KeyContext[" << key_id_ << "] "
2890 << state_string(state) << " -> " << state_string(newstate));
2891 state = newstate;
2892 }
2893
2894 void set_event(const EventType current)
2895 {
2897 << " KeyContext[" << key_id_ << "] "
2898 << event_type_string(current));
2899 current_event = current;
2900 }
2901
2902 void set_event(const EventType current, const EventType next, const Time &next_time)
2903 {
2905 << " KeyContext[" << key_id_ << "] "
2906 << event_type_string(current) << " -> " << event_type_string(next)
2907 << '(' << seconds_until(next_time) << ')');
2908 current_event = current;
2909 next_event = next;
2910 next_event_time = next_time;
2911 }
2912
2913 void invalidate_callback() // called by ProtoStackBase when session is invalidated
2914 {
2918 }
2919
2920 // Trigger a renegotiation based on data flow condition such
2921 // as per-key data limit or packet ID approaching wraparound.
2923 {
2925 {
2926 OVPN_LOG_VERBOSE(proto.debug_prefix() << " SCHEDULE KEY LIMIT RENEGOTIATION");
2927
2930
2931 // If primary, renegotiate now (within a second or two).
2932 // If secondary, queue the renegotiation request until
2933 // key reaches primary.
2934 if (next_event == KEV_BECOME_PRIMARY) // secondary key before transition to primary?
2935 {
2936 // reneg request crosses over to primary,
2937 // doesn't wipe next_event (KEV_BECOME_PRIMARY)
2939 }
2940 else
2941 {
2943 }
2944 }
2945 }
2946
2947 // Handle data-limited keys such as Blowfish and other 64-bit block-size ciphers.
2948 bool data_limit_add(const DataLimit::Mode mode, const size_t size)
2949 {
2950 if (is_safe_conversion<DataLimit::size_type>(size))
2951 return false;
2952 const DataLimit::State state = data_limit->add(mode, static_cast<DataLimit::size_type>(size));
2953 if (state > DataLimit::None)
2955 return true;
2956 }
2957
2958 // Handle a DataLimit event.
2960 {
2962 << " DATA LIMIT " << DataLimit::mode_str(mode)
2963 << ' ' << DataLimit::state_str(state)
2964 << " key_id=" << key_id_);
2965
2966 // State values:
2967 // DataLimit::Green -- first packet received and decrypted.
2968 // DataLimit::Red -- data limit has been exceeded, so trigger a renegotiation.
2969 if (state == DataLimit::Red)
2971
2972 // When we are in KEV_PRIMARY_PENDING state, we must receive at least
2973 // one packet from the peer on this key before we transition to
2974 // KEV_BECOME_PRIMARY so we can transmit on it.
2975 if (next_event == KEV_PRIMARY_PENDING && data_limit->is_decrypt_green())
2976 set_event(KEV_NONE, KEV_BECOME_PRIMARY, *now + Time::Duration::seconds(1));
2977 }
2978
2979 // Should we enter KEV_PRIMARY_PENDING state? Do it if:
2980 // 1. we are a client,
2981 // 2. data limit is enabled,
2982 // 3. this is a renegotiated key in secondary context, i.e. not the first key, and
2983 // 4. no data received yet from peer on this key.
2984 bool data_limit_defer() const
2985 {
2986 return !proto.is_server()
2987 && data_limit
2988 && key_id_
2989 && !data_limit->is_decrypt_green();
2990 }
2991
2992 // General expiration set when key hits data limit threshold.
2994 {
2995 return *now + (proto.config->handshake_window * 2);
2996 }
2997
2999 {
3002 reached_active() + proto.config->become_primary);
3003 }
3004
3006 {
3007 if (*now >= next_event_time)
3008 {
3009 switch (next_event)
3010 {
3011 case KEV_BECOME_PRIMARY:
3012 if (data_limit_defer())
3014 else
3017 construct_time + proto.config->renegotiate);
3018 break;
3019 case KEV_RENEGOTIATE:
3022 break;
3023 case KEV_NEGOTIATE:
3025 break;
3028 break;
3029 case KEV_EXPIRE:
3031 break;
3032 default:
3033 break;
3034 }
3035 }
3036 }
3037
3038 void kev_error(const EventType ev, const Error::Type reason)
3039 {
3040 proto.stats->error(reason);
3041 invalidate(reason);
3042 set_event(ev);
3043 }
3044
3045 unsigned int initial_op(const bool sender, const bool tls_crypt_v2) const
3046 {
3047 if (key_id_)
3048 {
3049 return CONTROL_SOFT_RESET_V1;
3050 }
3051
3052 if (proto.is_server() == sender)
3054
3055 if (!tls_crypt_v2)
3058 }
3059
3061 {
3062 Packet pkt;
3065 raw_send(std::move(pkt));
3066 }
3067
3069 {
3070 /* The data in the early negotiation packet is structured as
3071 * TLV (type, length, value) */
3072
3073 Buffer buf = pkt.buffer();
3074 while (!buf.empty())
3075 {
3076 if (buf.size() < 4)
3077 {
3078 /* Buffer does not have enough bytes for type (uint16) and length (uint16) */
3079 return false;
3080 }
3081
3082 uint16_t type = read_uint16_length(buf);
3083 uint16_t len = read_uint16_length(buf);
3084
3085 /* TLV defines a length that is larger than the remainder in the buffer. */
3086 if (buf.size() < len)
3087 return false;
3088
3089 if (type == EARLY_NEG_FLAGS)
3090 {
3091 if (len != 2)
3092 return false;
3093 uint16_t flags = read_uint16_length(buf);
3094
3095 if (flags & EARLY_NEG_FLAG_RESEND_WKC)
3096 {
3097 resend_wkc = true;
3098 }
3099 }
3100 else
3101 {
3102 /* skip over unknown types. We rather ignore undefined TLV to
3103 * not needing to add bits initial reset message (where space
3104 * is really tight) for optional features. */
3105 buf.advance(len);
3106 }
3107 }
3108 return true;
3109 }
3110
3111
3112 void raw_recv(Packet &&raw_pkt) // called by ProtoStackBase
3113 {
3114 if (raw_pkt.opcode == initial_op(false, proto.tls_wrap_mode == TLS_CRYPT_V2))
3115 {
3116 switch (state)
3117 {
3118 case C_WAIT_RESET:
3120 if (!parse_early_negotiation(raw_pkt))
3121 {
3123 }
3124 break;
3125 case S_WAIT_RESET:
3126 send_reset();
3128 break;
3129 }
3130 }
3131 }
3132
3133 void app_recv(BufferPtr &&to_app_buf) // called by ProtoStackBase
3134 {
3135 app_recv_buf.put(std::move(to_app_buf));
3137 throw proto_error("app_recv: received control message is too large");
3139 switch (state)
3140 {
3141 case C_WAIT_AUTH:
3142 if (recv_auth_complete(bcc))
3143 {
3144 recv_auth(bcc.get());
3146 }
3147 break;
3148 case S_WAIT_AUTH:
3149 if (recv_auth_complete(bcc))
3150 {
3151 recv_auth(bcc.get());
3152 send_auth();
3154 }
3155 break;
3156 case S_WAIT_AUTH_ACK:
3157 // rare case where client receives auth, goes ACTIVE,
3158 // but the ACK response is dropped
3159 case ACTIVE:
3160 if (bcc.advance_to_null()) // does composed buffer contain terminating null char?
3161 proto.app_recv(key_id_, bcc.get());
3162 break;
3163 }
3164 }
3165
3166 void net_send(const Packet &net_pkt, const Base::NetSendType nstype) // called by ProtoStackBase
3167 {
3168 if (!is_reliable || nstype != Base::NET_SEND_RETRANSMIT) // retransmit packets on UDP only, not TCP
3169 proto.net_send(key_id_, net_pkt);
3170 }
3171
3173 {
3175 {
3176 switch (state)
3177 {
3178 case C_WAIT_RESET_ACK:
3180 send_auth();
3182 break;
3183 case S_WAIT_RESET_ACK:
3186 break;
3187 case C_WAIT_AUTH_ACK:
3188 active();
3190 break;
3191 case S_WAIT_AUTH_ACK:
3192 active();
3194 break;
3195 }
3196 }
3197 }
3198
3200 {
3201 auto buf = BufferAllocatedRc::Create();
3202 proto.config->frame->prepare(Frame::WRITE_SSL_CLEARTEXT, *buf);
3203 buf->write(proto_context_private::auth_prefix, sizeof(proto_context_private::auth_prefix));
3205 tlsprf->self_write(*buf);
3206 const std::string options = proto.config->options_string();
3207 write_auth_string(options, *buf);
3208 if (!proto.is_server())
3209 {
3210 OVPN_LOG_INFO("Tunnel Options:" << options);
3211 buf->add_flags(BufAllocFlags::DESTRUCT_ZERO);
3212 if (proto.config->xmit_creds)
3213 proto.client_auth(*buf);
3214 else
3215 {
3216 write_empty_string(*buf); // username
3217 write_empty_string(*buf); // password
3218 }
3219 const std::string peer_info = proto.config->peer_info_string(proto.proto_callback->supports_epoch_data());
3220 write_auth_string(peer_info, *buf);
3221 }
3222 app_send_validate(std::move(buf));
3223 dirty = true;
3224 }
3225
3227 {
3228 const unsigned char *buf_pre = buf->read_alloc(sizeof(proto_context_private::auth_prefix));
3229 if (std::memcmp(buf_pre, proto_context_private::auth_prefix, sizeof(proto_context_private::auth_prefix)))
3230 throw proto_error("bad_auth_prefix");
3231 tlsprf->peer_read(*buf);
3232 const std::string options = read_auth_string<std::string>(*buf);
3233 if (proto.is_server())
3234 {
3235 const std::string username = read_auth_string<std::string>(*buf);
3236 const SafeString password = read_auth_string<SafeString>(*buf);
3237 const std::string peer_info = read_auth_string<std::string>(*buf);
3238 proto.proto_callback->server_auth(username, password, peer_info, Base::auth_cert());
3239 }
3240 }
3241
3242 // return true if complete recv_auth message is contained in buffer
3244 {
3245 if (!bc.advance(sizeof(proto_context_private::auth_prefix)))
3246 return false;
3247 if (!tlsprf->peer_read_complete(bc))
3248 return false;
3249 if (!bc.advance_string()) // options
3250 return false;
3251 if (proto.is_server())
3252 {
3253 if (!bc.advance_string()) // username
3254 return false;
3255 if (!bc.advance_string()) // password
3256 return false;
3257 if (!bc.advance_string()) // peer_info
3258 return false;
3259 }
3260 return true;
3261 }
3262
3263 void active()
3264 {
3265 OVPN_LOG_INFO("TLS Handshake: " << Base::ssl_handshake_details());
3266
3267 /* Our internal state machine only decides after push request what protocol
3268 * options we want to use. Therefore we also have to postpone data key
3269 * generation until this happens, create a empty DataChannelKey as
3270 * placeholder */
3271 data_channel_key.reset(new DataChannelKey());
3272 if (!proto.dc_deferred)
3274
3275 while (!app_pre_write_queue.empty())
3276 {
3277 app_send_validate(std::move(app_pre_write_queue.front()));
3278 app_pre_write_queue.pop_front();
3279 dirty = true;
3280 }
3283 active_event();
3284 }
3285
3286 void prepend_dest_psid_and_acks(Buffer &buf, unsigned int opcode)
3287 {
3288 // if sending ACKs, prepend dest PSID
3289 if (xmit_acks.acks_ready())
3290 {
3291 if (proto.psid_peer.defined())
3292 proto.psid_peer.prepend(buf);
3293 else
3294 {
3296 throw proto_error("peer_psid_undef");
3297 }
3298 }
3299
3300 // prepend ACKs for messages received from peer
3301 xmit_acks.prepend(buf, opcode == ACK_V1);
3302 }
3303
3304 bool verify_src_psid(const ProtoSessionID &src_psid)
3305 {
3306 if (proto.psid_peer.defined() && !proto.psid_peer.match(src_psid))
3307 {
3309 if (proto.is_tcp())
3311 return false;
3312 }
3313 return true;
3314 }
3315
3324 void accept_peer(const ProtoSessionID &src_psid)
3325 {
3326 pkt_from_peer = true;
3327 if (!proto.psid_peer.defined())
3328 proto.psid_peer = src_psid;
3329 }
3330
3332 {
3333 ProtoSessionID dest_psid(buf);
3334 if (!proto.psid_self.match(dest_psid))
3335 {
3337 if (proto.is_tcp())
3339 return false;
3340 }
3341 return true;
3342 }
3343
3344 void gen_head_tls_auth(const unsigned int opcode, Buffer &buf)
3345 {
3346 // write tls-auth packet ID
3348
3349 // make space for tls-auth HMAC
3351
3352 // write source PSID
3353 proto.psid_self.prepend(buf);
3354
3355 // write opcode
3356 buf.push_front(op_compose(opcode, key_id_));
3357
3358 // write hmac
3360 buf.size(),
3364 }
3365
3366 void gen_head_tls_crypt(const unsigned int opcode, BufferAllocated &buf)
3367 {
3368 // The send context stays unset until a WKc has been unwrapped, and decapsulate()
3369 // can put a session into TLS_CRYPT_V2 mode before that ever happens. Giving up
3370 // this session is caught per session, where the dereference below would not be.
3371 if (!proto.tls_crypt_send)
3372 throw proto_error("gen_head_tls_crypt: no tls-crypt send context");
3373
3374 // in 'work' we store all the fields that are not supposed to be encrypted
3375 proto.config->frame->prepare(Frame::ENCRYPT_WORK, work);
3376 // make space for HMAC
3378 // write tls-crypt packet ID
3380 // write source PSID
3382 // write opcode
3384
3385 // compute HMAC using header fields (from 'work') and plaintext
3386 // payload (from 'buf')
3389 buf.c_data(),
3390 buf.size());
3391
3392 const size_t data_offset = TLSCryptContext::hmac_offset + proto.hmac_size;
3393
3394 // encrypt the content of 'buf' (packet payload) into 'work'
3395 const size_t encrypt_bytes = proto.tls_crypt_send->encrypt(work.c_data() + TLSCryptContext::hmac_offset,
3396 work.data() + data_offset,
3397 work.max_size() - data_offset,
3398 buf.c_data(),
3399 buf.size());
3400 if (!encrypt_bytes)
3401 {
3402 buf.reset_size();
3403 return;
3404 }
3405 work.inc_size(encrypt_bytes);
3406
3407 // append WKc to wrapped packet for tls-crypt-v2
3408 if ((opcode == CONTROL_HARD_RESET_CLIENT_V3 || opcode == CONTROL_WKC_V1)
3411
3412 // 'work' now contains the complete packet ready to go. swap it with 'buf'
3413 buf.swap(work);
3414 }
3415
3416 void gen_head_tls_plain(const unsigned int opcode, Buffer &buf)
3417 {
3418 // write source PSID
3419 proto.psid_self.prepend(buf);
3420 // write opcode
3421 buf.push_front(op_compose(opcode, key_id_));
3422 }
3423
3424 void gen_head(const unsigned int opcode, BufferAllocated &buf)
3425 {
3426 switch (proto.tls_wrap_mode)
3427 {
3428 case TLS_AUTH:
3429 gen_head_tls_auth(opcode, buf);
3430 break;
3431 case TLS_CRYPT:
3432 case TLS_CRYPT_V2:
3433 gen_head_tls_crypt(opcode, buf);
3434 break;
3435 case TLS_PLAIN:
3436 gen_head_tls_plain(opcode, buf);
3437 break;
3438 }
3439 }
3440
3441 // True if the control packet with the given reliable-layer id will
3442 // carry the tls-crypt-v2 wrapped client key (WKc), appended after the
3443 // payload during encapsulation. Used both to select the CONTROL_WKC_V1
3444 // opcode and to reserve room for the WKc when filling the packet with
3445 // ciphertext.
3447 {
3448 return id == 1 && resend_wkc && proto.tls_wrap_mode == TLS_CRYPT_V2;
3449 }
3450
3451 // Worst-case number of bytes this control packet will carry around
3452 // the SSL ciphertext once encapsulated and wrapped: the tls wrap
3453 // header (opcode, session id, packet id, hmac) plus the reliable
3454 // layer message id and the largest possible piggybacked ACK block.
3455 // ACKs must be accounted for at their maximum, since retransmits
3456 // re-run encapsulate() with whatever ACKs are pending at that time.
3458 {
3459 size_t overhead = OPCODE_SIZE + ProtoSessionID::SIZE + proto.hmac_size;
3461 overhead += PacketIDControl::size();
3462 // reliable layer message id
3463 overhead += sizeof(id_t);
3464 // worst-case ACK block: count byte + ACK ids + dest session id
3465 overhead += 1 + sizeof(id_t) * ReliableAck::maximum_acks_control_v1
3467 return overhead;
3468 }
3469
3470 // Maximum amount of SSL ciphertext that may be placed into the control
3471 // packet with the given id, such that the fully wrapped packet does
3472 // not exceed the mssfix_ctrl limit. For the packet that also carries
3473 // the WKc, the WKc length is subtracted as well. Called by
3474 // ProtoStackBase.
3476 {
3477 size_t capacity = (*proto.config->frame)[Frame::READ_BIO_MEMQ_STREAM].payload();
3478
3479 // never let the fully wrapped packet exceed mssfix_ctrl
3480 size_t wire_budget = proto.config->mssfix_ctrl;
3481 wire_budget -= std::min(wire_budget, control_channel_wrap_overhead());
3482 capacity = std::min(capacity, wire_budget);
3483
3484 if (packet_carries_wkc(id) && proto.config->wkc.defined())
3485 {
3486 // clamp: a large WKc could exceed a small budget (mssfix-ctrl
3487 // can go as low as 256); never let the subtraction wrap. A
3488 // zero capacity yields a CONTROL_WKC_V1 packet carrying the
3489 // WKc alone, with all ciphertext deferred to the following
3490 // messages.
3491 capacity -= std::min(capacity, proto.config->wkc.size());
3492 }
3493 return capacity;
3494 }
3495
3496 void encapsulate(id_t id, Packet &pkt) // called by ProtoStackBase
3497 {
3498 BufferAllocated &buf = *pkt.buf;
3499
3500 // prepend message sequence number
3501 ReliableAck::prepend_id(buf, id);
3502
3503 // prepend dest PSID and ACKs to reply to peer
3505
3506 // generate message head
3507 int opcode = pkt.opcode;
3508 if (packet_carries_wkc(id))
3509 {
3510 opcode = CONTROL_WKC_V1;
3511 }
3512
3513 gen_head(opcode, buf);
3514 }
3515
3516 void generate_ack(Packet &pkt) // called by ProtoStackBase
3517 {
3518 BufferAllocated &buf = *pkt.buf;
3519
3520 // prepend dest PSID and ACKs to reply to peer
3522
3523 gen_head(ACK_V1, buf);
3524 }
3525
3527 {
3528 Buffer &recv = *pkt.buf;
3529
3530 // update our last-packet-received time
3532
3533 // verify source PSID
3534 if (!verify_src_psid(src_psid))
3535 return false;
3536
3537 // get current time_t
3539 // verify tls_auth/crypt packet ID
3540 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
3541
3542 // process ACKs sent by peer (if packet ID check failed,
3543 // read the ACK IDs, but don't modify the rel_send object).
3544 if (ReliableAck::ack(rel_send, recv, pid_ok))
3545 {
3546 // make sure that our own PSID is contained in packet received from peer
3547 if (!verify_dest_psid(recv))
3548 return false;
3549 }
3550
3551 accept_peer(src_psid);
3552
3553 // for CONTROL packets only, not ACK
3554 if (pkt.opcode != ACK_V1)
3555 {
3556 // get message sequence number
3557 const id_t id = ReliableAck::read_id(recv);
3558
3559 if (pid_ok)
3560 {
3561 // try to push message into reliable receive object
3562 const unsigned int rflags = rel_recv.receive(pkt, id);
3563
3564 // should we ACK packet back to sender?
3565 if (rflags & ReliableRecv::ACK_TO_SENDER)
3566 xmit_acks.push_back(id); // ACK packet to sender
3567
3568 // was packet accepted by reliable receive object?
3569 if (rflags & ReliableRecv::IN_WINDOW)
3570 {
3571 // remember tls_auth packet ID so that it can't be replayed
3572 proto.ta_pid_recv.test_add(pid, t, true);
3573 return true;
3574 }
3575 }
3576 else // treat as replay
3577 {
3579 if (pid.is_valid())
3580 // even replayed packets must be ACKed or protocol could deadlock
3581 xmit_acks.push_back(id);
3582 }
3583 }
3584 else
3585 {
3586 if (pid_ok)
3587 // remember tls_auth packet ID of ACK packet to prevent replay
3588 proto.ta_pid_recv.test_add(pid, t, true);
3589 else
3591 }
3592 return false;
3593 }
3594
3596 {
3597 Buffer &recv = *pkt.buf;
3598 const unsigned char *orig_data = recv.data();
3599 const size_t orig_size = recv.size();
3600
3601 // advance buffer past initial op byte
3602 recv.advance(1);
3603
3604 // get source PSID
3605 ProtoSessionID src_psid(recv);
3606
3607 // verify HMAC
3608 {
3609 recv.advance(proto.hmac_size);
3610 if (!proto.ta_hmac_recv->ovpn_hmac_cmp(orig_data,
3611 orig_size,
3615 {
3617 if (proto.is_tcp())
3619 return false;
3620 }
3621 }
3622
3623 // read tls_auth packet ID
3624 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
3625
3626 return decapsulate_post_process(pkt, src_psid, pid);
3627 }
3628
3630 {
3631 // in TLS_CRYPT_V2 mode the receive context stays unset until a WKc has been
3632 // unwrapped, so any other opcode reaching us before that has no key to be
3633 // decrypted with
3634 if (!proto.tls_crypt_recv)
3635 {
3637 if (proto.is_tcp())
3639 return false;
3640 }
3641
3642 auto &recv = *pkt.buf;
3643 const unsigned char *orig_data = recv.data();
3644 const size_t orig_size = recv.size();
3645
3646 // advance buffer past initial op byte
3647 recv.advance(1);
3648 // get source PSID
3649 ProtoSessionID src_psid(recv);
3650 // get tls-crypt packet ID
3651 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
3652 // skip the hmac
3653 recv.advance(proto.hmac_size);
3654
3655 const size_t data_offset = TLSCryptContext::hmac_offset + proto.hmac_size;
3656 if (orig_size < data_offset)
3657 return false;
3658
3659 // decrypt payload
3660 proto.config->frame->prepare(Frame::DECRYPT_WORK, work);
3661
3662 const size_t decrypt_bytes = proto.tls_crypt_recv->decrypt(orig_data + TLSCryptContext::hmac_offset,
3663 work.data(),
3664 work.max_size(),
3665 recv.c_data(),
3666 recv.size());
3667 if (!decrypt_bytes)
3668 {
3670 if (proto.is_tcp())
3672 return false;
3673 }
3674
3675 work.inc_size(decrypt_bytes);
3676
3677 // verify HMAC
3678 if (!proto.tls_crypt_recv->hmac_cmp(orig_data,
3680 work.c_data(),
3681 work.size()))
3682 {
3684 if (proto.is_tcp())
3686 return false;
3687 }
3688
3689 // move the decrypted payload to 'recv', so that the processing of the
3690 // packet can continue
3691 recv.swap(work);
3692
3693 return decapsulate_post_process(pkt, src_psid, pid);
3694 }
3695
3697 {
3698 Buffer &recv = *pkt.buf;
3699
3700 // update our last-packet-received time
3702
3703 // advance buffer past initial op byte
3704 recv.advance(1);
3705
3706 // verify source PSID
3707 ProtoSessionID src_psid(recv);
3708 if (!verify_src_psid(src_psid))
3709 return false;
3710
3711 // process ACKs sent by peer
3712 if (ReliableAck::ack(rel_send, recv, true))
3713 {
3714 // make sure that our own PSID is in packet received from peer
3715 if (!verify_dest_psid(recv))
3716 return false;
3717 }
3718
3719 accept_peer(src_psid);
3720
3721 // for CONTROL packets only, not ACK
3722 if (pkt.opcode != ACK_V1)
3723 {
3724 // get message sequence number
3725 const id_t id = ReliableAck::read_id(recv);
3726
3727 // try to push message into reliable receive object
3728 const unsigned int rflags = rel_recv.receive(pkt, id);
3729
3730 // should we ACK packet back to sender?
3731 if (rflags & ReliableRecv::ACK_TO_SENDER)
3732 xmit_acks.push_back(id); // ACK packet to sender
3733
3734 // was packet accepted by reliable receive object?
3735 if (rflags & ReliableRecv::IN_WINDOW)
3736 return true;
3737 }
3738 return false;
3739 }
3740
3748 bool tls_crypt_v2_wanted(const Packet &pkt) const
3749 {
3750 return proto.is_server()
3752 && !proto.psid_peer.defined()
3753 && proto.config->tls_crypt_v2_enabled()
3755 }
3756
3757 bool decapsulate(Packet &pkt) // called by ProtoStackBase
3758 {
3759 const bool detect_tls_crypt_v2 = tls_crypt_v2_wanted(pkt);
3760 const size_t tls_auth_hmac_size = proto.hmac_size;
3761 const bool had_client_key = bool(proto.tls_crypt_recv);
3762 bool authenticated = false;
3763
3764 pkt_from_peer = false;
3765
3766 try
3767 {
3768 if (detect_tls_crypt_v2)
3769 {
3770 // Create the server context the client's WKc is unwrapped with,
3771 // keyed only at unwrap time, when the WKc names its key. tls-crypt
3772 // session key setup is postponed to reception of the WKc too.
3774
3776 proto.hmac_size = proto.config->tls_crypt_context->digest_size();
3777
3778 // init tls_crypt packet ID; the send half waits until the packet has
3779 // earned it, below, since putting the previous id back is not possible
3780 proto.ta_pid_recv.init("SSL-CC", 0, proto.stats);
3781 }
3782
3783 authenticated = decapsulate_by_wrap_mode(pkt);
3784 }
3785 catch (const BufferException &)
3786 {
3788 if (proto.is_tcp())
3790 }
3791
3792 if (!pkt_from_peer && !had_client_key && proto.tls_crypt_recv)
3793 {
3794 // Drop a packet that's not ours.
3798 }
3799
3800 if (detect_tls_crypt_v2)
3801 {
3802 if (!pkt_from_peer)
3803 {
3804 // Not our peer's packet, so leave the session as tls-auth had it. The
3805 // receive packet id needs no undoing: reset() initialises it the same
3806 // way and nothing of our peer's has moved it.
3808 proto.hmac_size = tls_auth_hmac_size;
3809 }
3810 else
3811 {
3815 }
3816 }
3817
3818 return authenticated;
3819 }
3820
3834 {
3835 switch (proto.tls_wrap_mode)
3836 {
3837 case TLS_AUTH:
3838 return decapsulate_tls_auth(pkt);
3839 case TLS_CRYPT_V2:
3840 // Both opcodes carry a WKc: the first packet of a handshake this session
3841 // saw the start of, and the third one of a handshake a psid cookie layer
3842 // fielded on its behalf, which is what asking the client to resend the WKc
3843 // (EARLY_NEG_FLAG_RESEND_WKC) is for. Either way the client key comes from
3844 // the packet in front of us and from nowhere else, so unwrap it here, once
3845 // -- and take the WKc off every later copy, which carries it just the same.
3846 if (proto.is_server()
3848 {
3849 if (!proto.tls_crypt_recv)
3850 {
3852 {
3854 << " DROPPING WKc WITH NO SERVER CONTEXT");
3855 return false;
3856 }
3857
3858 UnwrappedWkc unwrapped;
3859 const Error::Type unwrap_wkc_result = unwrap_tls_crypt_wkc(*pkt.buf,
3860 *proto.config,
3862 unwrapped);
3863 switch (unwrap_wkc_result)
3864 {
3866 case Error::HMAC_ERROR:
3867 proto.stats->error(unwrap_wkc_result);
3868 if (proto.is_tcp())
3869 invalidate(unwrap_wkc_result);
3870 return false;
3871 case Error::SUCCESS:
3872 break;
3873 default:
3874 return false;
3875 }
3876
3877 if (proto.config->tls_crypt_metadata_factory)
3878 {
3879 const TLSCryptMetadata::Ptr metadata = proto.config->tls_crypt_metadata_factory->new_obj();
3880
3881 if (!metadata->verify(unwrapped.metadata.type, unwrapped.metadata.payload))
3882 {
3884 return false;
3885 }
3886 }
3887
3888 // The WKc holds up under the server key, so the client key inside it
3889 // is one this server issued. Key the session with it.
3890 proto.tls_crypt_client_key = std::move(unwrapped.client_key);
3892 }
3893 else if (!strip_resent_wkc(*pkt.buf, *proto.config))
3894 {
3896 if (proto.is_tcp())
3898 return false;
3899 }
3900 }
3901 // now that the tls-crypt contexts have been initialized it is
3902 // possible to proceed with the standard tls-crypt decapsulation
3903 [[fallthrough]];
3904 case TLS_CRYPT:
3905 return decapsulate_tls_crypt(pkt);
3906 case TLS_PLAIN:
3907 return decapsulate_tls_plain(pkt);
3908 }
3909 return false;
3910 }
3911
3912 // for debugging
3913 static const char *state_string(const int s)
3914 {
3915 switch (s)
3916 {
3917 case C_WAIT_RESET_ACK:
3918 return "C_WAIT_RESET_ACK";
3919 case C_WAIT_AUTH_ACK:
3920 return "C_WAIT_AUTH_ACK";
3921 case S_WAIT_RESET_ACK:
3922 return "S_WAIT_RESET_ACK";
3923 case S_WAIT_AUTH_ACK:
3924 return "S_WAIT_AUTH_ACK";
3925 case C_INITIAL:
3926 return "C_INITIAL";
3927 case C_WAIT_RESET:
3928 return "C_WAIT_RESET";
3929 case C_WAIT_AUTH:
3930 return "C_WAIT_AUTH";
3931 case S_INITIAL:
3932 return "S_INITIAL";
3933 case S_WAIT_RESET:
3934 return "S_WAIT_RESET";
3935 case S_WAIT_AUTH:
3936 return "S_WAIT_AUTH";
3937 case ACTIVE:
3938 return "ACTIVE";
3939 default:
3940 return "STATE_UNDEF";
3941 }
3942 }
3943
3944 // for debugging
3945 int seconds_until(const Time &next_time)
3946 {
3947 Time::Duration d = next_time - *now;
3948 if (d.is_infinite())
3949 return -1;
3950 return numeric_cast<int>(d.to_seconds());
3951 }
3952
3953 // BEGIN KeyContext data members
3954
3957 unsigned int key_id_;
3958 unsigned int crypto_flags;
3959 int remote_peer_id; // -1 to disable
3961 /* early negotiation enabled resending of wrapped tls-crypt-v2 client key
3962 * with third packet of the three-way handshake
3963 */
3964 bool resend_wkc = false;
3966 bool pkt_from_peer = false;
3967 bool dirty;
3978 std::deque<BufferPtr> app_pre_write_queue;
3979 std::unique_ptr<DataChannelKey> data_channel_key;
3981 std::unique_ptr<DataLimit> data_limit;
3983
3984 // static member used by validate_tls_crypt()
3986 };
3987
3989 {
3990 public:
3991 PsidCookieHelper(unsigned int op_field)
3992 : op_code_(opcode_extract(op_field)), key_id_(key_id_extract(op_field))
3993 {
3994 }
3995
3997 {
3998 return key_id_ == 0 && (op_code_ == CONTROL_HARD_RESET_CLIENT_V2 || op_code_ == CONTROL_HARD_RESET_CLIENT_V3);
3999 }
4000
4002 bool is_tls_crypt_v2() const noexcept
4003 {
4004 return op_code_ == CONTROL_HARD_RESET_CLIENT_V3 || op_code_ == CONTROL_WKC_V1;
4005 }
4006
4008 bool supports_early_negotiation(const PacketIDControl &pidc) const noexcept
4009 {
4010 return (pidc.id & EARLY_NEG_MASK) == EARLY_NEG_START;
4011 }
4012
4015 {
4016 return key_id_ == 0 && (op_code_ == CONTROL_V1 || op_code_ == ACK_V1);
4017 }
4018
4021 {
4022 return key_id_ == 0 && op_code_ == CONTROL_WKC_V1;
4023 }
4024
4026 bool is_ack_v1() const
4027 {
4028 return op_code_ == ACK_V1;
4029 }
4030
4032 static void prepend_TLV(Buffer &payload)
4033 {
4034 // The only supported TLV payload for now.
4035 const uint16_t type = htons(EARLY_NEG_FLAGS);
4036 const uint16_t len = htons(sizeof(uint16_t));
4037 const uint16_t flags = htons(EARLY_NEG_FLAG_RESEND_WKC);
4038
4039 payload.prepend(&flags, sizeof(flags));
4040 payload.prepend(&len, sizeof(len));
4041 payload.prepend(&type, sizeof(type));
4042 }
4043
4044 static unsigned char get_server_hard_reset_opfield()
4045 {
4046 return op_compose(CONTROL_HARD_RESET_SERVER_V2, 0);
4047 }
4048
4049 private:
4050 const unsigned int op_code_;
4051 const unsigned int key_id_;
4052 };
4053
4055 {
4056 public:
4057 IvProtoHelper(const OptionList &peer_info)
4058 : proto_field_(peer_info.get_num<unsigned int>("IV_PROTO", 1, 0))
4059 {
4060 }
4061
4063 {
4064 return proto_field_ & iv_proto_flag::IV_PROTO_TLS_KEY_EXPORT;
4065 }
4066
4068 {
4069 return proto_field_ & iv_proto_flag::IV_PROTO_AUTH_FAIL_TEMP;
4070 }
4071
4073 {
4074 return proto_field_ & iv_proto_flag::IV_PROTO_DATA_V2;
4075 }
4076
4078 {
4079 return proto_field_ & iv_proto_flag::IV_PROTO_AUTH_PENDING_KW;
4080 }
4081
4083 {
4084 return proto_field_ & iv_proto_flag::IV_PROTO_PUSH_UPDATE;
4085 }
4086
4088 {
4089 return proto_field_ & iv_proto_flag::IV_PROTO_REQUEST_PUSH;
4090 }
4091
4094 {
4095 return proto_field_ & iv_proto_flag::IV_PROTO_CC_EXIT_NOTIFY;
4096 }
4097
4100 {
4101 return proto_field_ & iv_proto_flag::IV_PROTO_DYN_TLS_CRYPT;
4102 }
4103
4106 {
4107 return proto_field_ & iv_proto_flag::IV_PROTO_DNS_OPTION_V2;
4108 }
4109
4110 private:
4111 unsigned int proto_field_;
4112 };
4113
4114 class TLSWrapPreValidate : public RC<thread_unsafe_refcount>
4115 {
4116 public:
4118
4119 virtual bool validate(const BufferAllocated &net_buf) = 0;
4120 };
4121
4122 // Validate the integrity of a packet, only considering tls-auth HMAC.
4124 {
4125 public:
4126 OPENVPN_SIMPLE_EXCEPTION(tls_auth_pre_validate);
4127
4128 TLSAuthPreValidate(const ProtoConfig &c, const bool server)
4129 {
4130 if (!c.tls_auth_enabled())
4131 throw tls_auth_pre_validate();
4132
4133 // save hard reset op we expect to receive from peer
4134 reset_op = server ? CONTROL_HARD_RESET_CLIENT_V2 : CONTROL_HARD_RESET_SERVER_V2;
4135
4136 // init OvpnHMACInstance
4137 ta_hmac_recv = c.tls_auth_context->new_obj();
4138
4139 // init tls_auth hmac
4140 if (c.key_direction >= 0)
4141 {
4142 // key-direction is 0 or 1
4143 const unsigned int key_dir = c.key_direction
4144 ? OpenVPNStaticKey::INVERSE
4145 : OpenVPNStaticKey::NORMAL;
4146 ta_hmac_recv->init(c.tls_auth_key.slice(OpenVPNStaticKey::HMAC | OpenVPNStaticKey::DECRYPT | key_dir));
4147 }
4148 else
4149 {
4150 // key-direction bidirectional mode
4151 ta_hmac_recv->init(c.tls_auth_key.slice(OpenVPNStaticKey::HMAC));
4152 }
4153 }
4154
4155 bool validate(const BufferAllocated &net_buf)
4156 {
4157 try
4158 {
4159 if (net_buf.empty())
4160 return false;
4161
4162 const unsigned int op = net_buf[0];
4163 if (opcode_extract(op) != reset_op || key_id_extract(op) != 0)
4164 return false;
4165
4166 return ta_hmac_recv->ovpn_hmac_cmp(net_buf.c_data(),
4167 net_buf.size(),
4168 OPCODE_SIZE + ProtoSessionID::SIZE,
4169 ta_hmac_recv->output_size(),
4170 PacketIDControl::size());
4171 }
4172 catch (const BufferException &)
4173 {
4174 }
4175
4176 return false;
4177 }
4178
4179 private:
4181 unsigned int reset_op;
4182 };
4183
4185 {
4186 public:
4187 OPENVPN_SIMPLE_EXCEPTION(tls_crypt_pre_validate);
4188
4189 TLSCryptPreValidate(const ProtoConfig &c, const bool server)
4190 {
4191 const bool tls_crypt_v2_enabled = c.tls_crypt_v2_enabled();
4192
4193 if (!c.tls_crypt_enabled() && !tls_crypt_v2_enabled)
4194 throw tls_crypt_pre_validate();
4195
4196 // save hard reset op we expect to receive from peer
4197 reset_op = CONTROL_HARD_RESET_SERVER_V2;
4198
4199 if (server)
4200 {
4201 // We can't pre-validate because we haven't extracted the server key from
4202 // the server key ID that's present in the client key yet.
4203 if (tls_crypt_v2_enabled && c.tls_crypt_v2_serverkey_id)
4204 {
4205 disabled = true;
4206 return;
4207 }
4208
4209 reset_op = tls_crypt_v2_enabled
4210 ? CONTROL_HARD_RESET_CLIENT_V3
4211 : CONTROL_HARD_RESET_CLIENT_V2;
4212 }
4213
4214 tls_crypt_recv = c.tls_crypt_context->new_obj_recv();
4215
4216 // static direction assignment - not user configurable
4217 const unsigned int key_dir = server ? OpenVPNStaticKey::NORMAL : OpenVPNStaticKey::INVERSE;
4218 tls_crypt_recv->init(c.ssl_factory->libctx(),
4219 c.tls_crypt_key.slice(OpenVPNStaticKey::HMAC | OpenVPNStaticKey::DECRYPT | key_dir),
4220 c.tls_crypt_key.slice(OpenVPNStaticKey::CIPHER | OpenVPNStaticKey::DECRYPT | key_dir));
4221
4222 // needed to create the decrypt buffer during validation
4223 frame = c.frame;
4224 }
4225
4226 bool validate(const BufferAllocated &net_buf)
4227 {
4228 if (disabled)
4229 return true;
4230
4231 try
4232 {
4233 if (net_buf.empty())
4234 return false;
4235
4236 const unsigned int op = net_buf[0];
4237 if (opcode_extract(op) != reset_op || key_id_extract(op) != 0)
4238 return false;
4239
4240 const size_t data_offset = TLSCryptContext::hmac_offset + tls_crypt_recv->output_hmac_size();
4241 if (net_buf.size() < data_offset)
4242 return false;
4243
4244 frame->prepare(Frame::DECRYPT_WORK, work);
4245
4246 // decrypt payload from 'net_buf' into 'work'
4247 const size_t decrypt_bytes = tls_crypt_recv->decrypt(net_buf.c_data() + TLSCryptContext::hmac_offset,
4248 work.data(),
4249 work.max_size(),
4250 net_buf.c_data() + data_offset,
4251 net_buf.size() - data_offset);
4252 if (!decrypt_bytes)
4253 return false;
4254
4255 work.inc_size(decrypt_bytes);
4256
4257 // verify HMAC
4258 return tls_crypt_recv->hmac_cmp(net_buf.c_data(),
4259 TLSCryptContext::hmac_offset,
4260 work.data(),
4261 work.size());
4262 }
4263 catch (const BufferException &)
4264 {
4265 }
4266 return false;
4267 }
4268
4269 protected:
4270 unsigned int reset_op;
4271
4272 private:
4276 bool disabled = false;
4277 };
4278
4279 OPENVPN_SIMPLE_EXCEPTION(select_key_context_error);
4280
4282 const ProtoConfig::Ptr &config_arg, // configuration
4283 const SessionStats::Ptr &stats_arg) // error stats
4284 : proto_callback(cb_arg),
4285 config(config_arg),
4286 stats(stats_arg),
4287 mode_(config_arg->ssl_factory->mode()),
4288 n_key_ids(0),
4289 now_(config_arg->now)
4290 {
4292 }
4293
4295 {
4296 // Prefer TLS auth as the default if both TLS crypt V2 and TLS auth
4297 // are enabled.
4298 if (c.tls_crypt_v2_enabled() && !c.tls_auth_enabled())
4299 {
4301
4302 // get HMAC size from Digest object
4304
4305 return;
4306 }
4307
4308 if (c.tls_crypt_enabled() && !c.tls_auth_enabled())
4309 {
4311
4312 // get HMAC size from Digest object
4314
4315 return;
4316 }
4317
4318 if (c.tls_auth_enabled())
4319 {
4321
4322 // get HMAC size from Digest object
4324
4325 return;
4326 }
4327
4329 hmac_size = 0;
4330 }
4331
4332 uint32_t get_tls_warnings() const
4333 {
4334 if (primary)
4335 return primary->get_tls_warnings();
4336
4337 OPENVPN_LOG("TLS: primary key context uninitialized. Can't retrieve TLS warnings");
4338 return 0;
4339 }
4340
4341 bool uses_bs64_cipher() const
4342 {
4343 return is_bs64_cipher(conf().dc.cipher());
4344 }
4345
4347 {
4350
4351 // static direction assignment - not user configurable
4353
4360 }
4361
4363 {
4364 // Both call sites fire on primary->key_id() == 0, which a duplicated -- or
4365 // corrupted, then retransmitted -- soft reset satisfies twice. The switch below
4366 // reads tls_wrap_mode, which this function ends by overwriting, so a second
4367 // pass would land on TLS_CRYPT and mix c.tls_crypt_key: the wrong key, and on
4368 // a tls_crypt_v2_serverkey_id server not a defined one. There is nothing new
4369 // to derive anyway -- same TLS session, same exported material.
4371 return;
4372
4373 OpenVPNStaticKey dyn_key;
4374 key_ctx->export_key_material(dyn_key, "EXPORTER-OpenVPN-dynamic-tls-crypt");
4375
4376 // The mode this session settled on, not what the config allows. A server holding
4377 // both a tls-auth key and tls-crypt-v2 starts every session as TLS_AUTH and only
4378 // decapsulate() converts it, so asking the config here would have such a server
4379 // mix tls_auth_key while its converted tls-crypt-v2 client mixes Kc.
4380 switch (tls_wrap_mode)
4381 {
4382 case TLS_AUTH:
4383 dyn_key.XOR(c.tls_auth_key);
4384 break;
4385 case TLS_CRYPT_V2:
4386 // Kc, this session's own: c.tls_crypt_key is the client's Kc on a client but the
4387 // server key on a server, and with tls_crypt_v2_serverkey_id not even defined, so
4388 // mixing it in would have the two ends derive different keys.
4390 throw proto_error("dynamic tls-crypt with no tls-crypt-v2 client key");
4391 dyn_key.XOR(tls_crypt_client_key);
4392 break;
4393 case TLS_CRYPT:
4394 dyn_key.XOR(c.tls_crypt_key);
4395 break;
4396 case TLS_PLAIN:
4397 break;
4398 }
4399
4401
4402 // get HMAC size from Digest object
4404
4405 ta_pid_send.init();
4406 ta_pid_recv.init("SSL-CC", 0, stats);
4407
4408 reset_tls_crypt(c, dyn_key);
4410 }
4411
4413 {
4414 // The session key is derived from the WKc riding on the first packet we
4415 // decapsulate, so there is nothing to install here -- see decapsulate(). Any key
4416 // this session already holds is left alone: decapsulate() can bring us back here
4417 // for a session already running, and dropping its contexts would leave the next
4418 // control packet it sends with nothing to authenticate itself with.
4419
4420 // Server context, used only to process incoming WKc's. Left unkeyed:
4421 // unwrap_tls_crypt_wkc() keys it, since only it knows which key the WKc needs.
4423 }
4424
4436 void reset(const ProtoSessionID cookie_psid = ProtoSessionID())
4437 {
4438 const ProtoConfig &c = *config;
4439
4440 // defer data channel initialization until after client options pull?
4442
4443 // clear key contexts
4444 reset_all();
4445
4446 // Drop the contexts a previous handshake set up: until the peer is known, no key may
4447 // be left that could authenticate its packets. reset_tls_crypt_server() cannot do it,
4448 // since decapsulate() also calls that for a session already running.
4454
4455 // start with key ID 0
4456 upcoming_key_id = 0;
4457
4458 unsigned int key_dir;
4459
4460 // tls-auth initialization
4462 switch (tls_wrap_mode)
4463 {
4464 case TLS_CRYPT:
4466 // init tls_crypt packet ID
4467 ta_pid_send.init();
4468 ta_pid_recv.init("SSL-CC", 0, stats);
4469 break;
4470 case TLS_CRYPT_V2:
4471 if (is_server())
4472 // Create the server context the client's WKc is unwrapped with,
4473 // keyed only at unwrap time, when the WKc names its key. tls-crypt
4474 // session key setup is postponed to reception of the WKc too.
4476 else
4477 {
4478 // a client's own Kc, the one its WKc carries to the server
4481 }
4484 // init tls_crypt packet ID
4486 ta_pid_recv.init("SSL-CC", 0, stats);
4487 break;
4488 case TLS_AUTH:
4489 // init OvpnHMACInstance
4492
4493 // init tls_auth hmac
4494 if (c.key_direction >= 0)
4495 {
4496 // key-direction is 0 or 1
4500 }
4501 else
4502 {
4503 // key-direction bidirectional mode
4506 }
4507
4517 ta_pid_send.init(cookie_psid.defined() ? 1 : 0);
4518 ta_pid_recv.init("SSL-CC", 0, stats);
4519 break;
4520 case TLS_PLAIN:
4521 break;
4522 }
4523
4524 // initialize proto session ID
4525 if (cookie_psid.defined())
4526 psid_self = cookie_psid;
4527 else
4529 psid_peer.reset();
4530
4531 // initialize key contexts
4532 primary.reset(new KeyContext(*this, is_client(), cookie_psid.defined()));
4533 OVPN_LOG_VERBOSE(debug_prefix() << " New KeyContext PRIMARY id=" << primary->key_id());
4534
4535 // initialize keepalive timers
4536 keepalive_expire = Time::infinite(); // initially disabled
4537 update_last_sent(); // set timer for initial keepalive send
4538 }
4539
4540 void set_protocol(const Protocol &p)
4541 {
4542 config->set_protocol(p);
4543 if (primary)
4544 primary->set_protocol(p);
4545 if (secondary)
4546 secondary->set_protocol(p);
4547 }
4548
4549 // Free up space when parent object has been halted but
4550 // object destruction is not immediately scheduled.
4552 {
4553 reset_all();
4554 }
4555
4556 // Is primary key defined
4558 {
4559 return bool(primary);
4560 }
4561
4562 virtual ~ProtoContext() = default;
4563
4564 // return the PacketType of an incoming network packet
4566 {
4567 return PacketType(buf, *this);
4568 }
4569
4578 void start(const ProtoSessionID cookie_psid = ProtoSessionID())
4579 {
4580 if (!primary)
4581 throw proto_error("start: no primary key");
4582 primary->start(cookie_psid);
4583 update_last_received(); // set an upper bound on when we expect a response
4584 }
4585
4586#ifdef UNIT_TEST
4587 // Test seam: pretend the server requested resending the tls-crypt-v2 WKc
4588 // (EARLY_NEG_FLAG_RESEND_WKC), so the first control packet carrying SSL
4589 // ciphertext is emitted as CONTROL_WKC_V1 with the WKc appended.
4590 void force_resend_wkc()
4591 {
4592 if (primary)
4593 primary->resend_wkc = true;
4594 }
4595#endif
4596
4597 // trigger a protocol renegotiation
4599 {
4600 // set up dynamic tls-crypt keys when the first rekeying happens
4601 // primary key_id 0 indicates that it is the first rekey
4602 if (conf().dynamic_tls_crypt_enabled() && primary && primary->key_id() == 0)
4604
4605 // initialize secondary key context
4606 new_secondary_key(true);
4607 secondary->start();
4608 }
4609
4610 // Should be called at the end of sequence of send/recv
4611 // operations on underlying protocol object.
4612 // If control_channel is true, do a full flush.
4613 // If control_channel is false, optimize flush for data
4614 // channel only.
4615 void flush(const bool control_channel)
4616 {
4617 if (control_channel || process_events())
4618 {
4619 do
4620 {
4621 if (primary)
4622 primary->flush();
4623 if (secondary)
4624 secondary->flush();
4625 } while (process_events());
4626 }
4627 }
4628
4629 // Perform various time-based housekeeping tasks such as retransmiting
4630 // unacknowleged packets as part of the reliability layer and testing
4631 // for keepalive timouts.
4632 // Should be called at the time returned by next_housekeeping.
4634 {
4635 // handle control channel retransmissions on primary
4636 if (primary)
4637 primary->retransmit();
4638
4639 // handle control channel retransmissions on secondary
4640 if (secondary)
4641 secondary->retransmit();
4642
4643 // handle possible events
4644 flush(false);
4645
4646 // handle keepalive/expiration
4648 }
4649
4650 // When should we next call housekeeping?
4651 // Will return a time value for immediate execution
4652 // if session has been invalidated.
4654 {
4655 if (!invalidated())
4656 {
4657 Time ret = Time::infinite();
4658 if (primary)
4659 ret.min(primary->next_retransmit());
4660 if (secondary)
4661 ret.min(secondary->next_retransmit());
4662 ret.min(keepalive_xmit);
4663 ret.min(keepalive_expire);
4664 return ret;
4665 }
4666 return Time();
4667 }
4668
4669 // send app-level cleartext to remote peer
4670
4672 {
4673 select_control_send_context().app_send(std::move(app_bp));
4674 }
4675
4677 {
4678 control_send(BufferAllocatedRc::Create(std::move(app_buf)));
4679 }
4680
4681 // validate a control channel network packet
4682 bool control_net_validate(const PacketType &type, const Buffer &net_buf)
4683 {
4684 return type.is_defined() && KeyContext::validate(net_buf, *this, now_);
4685 }
4686
4687 // pass received control channel network packets (ciphertext) into protocol object
4688 bool control_net_recv(const PacketType &type, BufferPtr &&net_bp)
4689 {
4690 Packet pkt(std::move(net_bp), type.opcode);
4691 if (type.is_soft_reset() && !renegotiate_request(pkt))
4692 return false;
4693 return select_key_context(type, true).net_recv(std::move(pkt));
4694 }
4695
4703 bool control_net_recv(const PacketType &type, BufferAllocated &&net_buf)
4704 {
4705 return control_net_recv(type, BufferAllocatedRc::Create(std::move(net_buf)));
4706 }
4707
4708 // encrypt a data channel packet using primary KeyContext
4710 {
4711 OVPN_LOG_DEBUG(debug_prefix() << " DATA ENCRYPT size=" << in_out.size());
4712 if (!primary)
4713 throw proto_error("data_encrypt: no primary key");
4714 primary->encrypt(in_out);
4715 }
4716
4717 // decrypt a data channel packet (automatically select primary
4718 // or secondary KeyContext based on packet content)
4719 bool data_decrypt(const PacketType &type, BufferAllocated &in_out)
4720 {
4721 bool ret = false;
4722
4723 OVPN_LOG_DEBUG(debug_prefix() << " DATA DECRYPT key_id=" << select_key_context(type, false).key_id() << " size=" << in_out.size());
4724
4725 select_key_context(type, false).decrypt(in_out);
4726
4727 // update time of most recent packet received
4728 if (!in_out.empty())
4729 {
4731 ret = true;
4732 }
4733
4734 // discard keepalive packets
4735 if (proto_context_private::is_keepalive(in_out))
4736 {
4737 in_out.reset_size();
4738 }
4739
4740 return ret;
4741 }
4742
4743 // enter disconnected state
4744 void disconnect(const Error::Type reason)
4745 {
4746 if (primary)
4747 primary->invalidate(reason);
4748 if (secondary)
4749 secondary->invalidate(reason);
4750 }
4751
4752 // normally used by UDP clients to tell the server that
4753 // they are disconnecting
4755 {
4756#ifndef OPENVPN_DISABLE_EXPLICIT_EXIT // explicit exit should always be enabled in production
4757 if (!is_client() || !is_udp() || !primary)
4758 {
4759 return;
4760 }
4761
4762 if (config->cc_exit_notify)
4763 {
4764 write_control_string(std::string("EXIT"));
4765 primary->flush();
4766 }
4767 else
4768 {
4769 primary->send_explicit_exit_notify();
4770 }
4771#endif // OPENVPN_DISABLE_EXPLICIT_EXIT
4772 }
4773
4774 // should be called after a successful network packet transmit
4776 {
4777 keepalive_xmit = *now_ + config->keepalive_ping;
4778 }
4779
4780 // Can we call data_encrypt or data_decrypt yet?
4781 // Returns true if primary data channel is in ACTIVE state.
4783 {
4784 return primary && primary->data_channel_ready();
4785 }
4786
4787 // total number of SSL/TLS negotiations during lifetime of ProtoContext object
4788 unsigned int negotiations() const
4789 {
4790 return n_key_ids;
4791 }
4792
4793 // worst-case handshake time
4794 const Time::Duration &slowest_handshake()
4795 {
4796 return slowest_handshake_;
4797 }
4798
4799 // was primary context invalidated by an exception?
4800 bool invalidated() const
4801 {
4802 return primary && primary->invalidated();
4803 }
4804
4805 // reason for invalidation if invalidated() above returns true
4807 {
4808 return primary->invalidation_reason();
4809 }
4810
4811 // Do late initialization of data channel, for example
4812 // on client after server push, or on server after client
4813 // capabilities are known.
4815 {
4816 dc_deferred = false;
4817
4818 // initialize data channel (crypto & compression)
4819 if (primary)
4820 primary->init_data_channel();
4821 if (secondary)
4822 secondary->init_data_channel();
4823 }
4824
4825 // Call on client with server-pushed options
4827 {
4828 // modify config with pushed options
4829 config->process_push(opt, pco);
4830
4831 // in case keepalive parms were modified by push
4833 }
4834
4835 // Return the current transport alignment adjustment
4836 size_t align_adjust_hint() const
4837 {
4838 return config->enable_op32 ? 0 : 1;
4839 }
4840
4841 // Return true if keepalive parameter(s) are enabled
4843 {
4844 return config->keepalive_ping.enabled()
4845 || config->keepalive_timeout.enabled();
4846 }
4847
4848 // Disable keepalive for rest of session,
4849 // but return the previous keepalive parameters.
4850 void disable_keepalive(unsigned int &keepalive_ping,
4851 unsigned int &keepalive_timeout)
4852 {
4853 keepalive_ping = config->keepalive_ping.enabled()
4854 ? clamp_to_typerange<std::remove_reference_t<decltype(keepalive_ping)>>(config->keepalive_ping.to_seconds())
4855 : 0;
4856 keepalive_timeout = config->keepalive_timeout.enabled()
4857 ? clamp_to_typerange<std::remove_reference_t<decltype(keepalive_timeout)>>(config->keepalive_timeout.to_seconds())
4858 : 0;
4859 config->keepalive_ping = Time::Duration::infinite();
4860 config->keepalive_timeout = Time::Duration::infinite();
4861 config->keepalive_timeout_early = Time::Duration::infinite();
4863 }
4864
4865 // Notify our component KeyContext when per-key Data Limits have been reached
4866 void data_limit_notify(const unsigned int key_id,
4867 const DataLimit::Mode cdl_mode,
4868 const DataLimit::State cdl_status)
4869 {
4870 if (primary && key_id == primary->key_id())
4871 primary->data_limit_notify(cdl_mode, cdl_status);
4872 else if (secondary && key_id == secondary->key_id())
4873 secondary->data_limit_notify(cdl_mode, cdl_status);
4874 }
4875
4876 // access the data channel settings
4878 {
4879 return config->dc;
4880 }
4881
4882 // reset the data channel factory
4884 {
4885 config->dc.reset();
4886 }
4887
4888 // set the local peer ID (or -1 to disable)
4889 void set_local_peer_id(const int local_peer_id)
4890 {
4891 config->local_peer_id = local_peer_id;
4892 }
4893
4894 // current time
4895 const Time &now() const
4896 {
4897 return *now_;
4898 }
4900 {
4901 now_->update();
4902 }
4903
4904 // frame
4905 const Frame &frame() const
4906 {
4907 return *config->frame;
4908 }
4909 const Frame::Ptr &frameptr() const
4910 {
4911 return config->frame;
4912 }
4913
4914 // client or server?
4915 const Mode &mode() const
4916 {
4917 return mode_;
4918 }
4919 bool is_server() const
4920 {
4921 return mode_.is_server();
4922 }
4923 bool is_client() const
4924 {
4925 return mode_.is_client();
4926 }
4927
4928 // tcp/udp mode
4929 bool is_tcp()
4930 {
4931 return config->protocol.is_tcp();
4932 }
4933 bool is_udp()
4934 {
4935 return config->protocol.is_udp();
4936 }
4937
4938 // configuration
4939 const ProtoConfig &conf() const
4940 {
4941 return *config;
4942 }
4944 {
4945 return *config;
4946 }
4948 {
4949 return config;
4950 }
4951
4952 // stats
4954 {
4955 return *stats;
4956 }
4957
4958 // debugging
4960 {
4961 return primary_state() == C_WAIT_RESET_ACK;
4962 }
4963
4964 protected:
4965 int primary_state() const
4966 {
4967 if (primary)
4968 return primary->get_state();
4969 return STATE_UNDEF;
4970 }
4971
4972 private:
4973 // TLS wrapping mode for the control channel
4981
4983 {
4984 if (primary)
4986 primary.reset();
4987 secondary.reset();
4988 }
4989
4990 // Called on client to request username/password credentials.
4991 // delegated to the callback/parent
4993 {
4995 }
4996
4998 {
4999 keepalive_expire = *now_ + (data_channel_ready() ? config->keepalive_timeout : config->keepalive_timeout_early);
5000 }
5001
5002 void net_send(const unsigned int key_id, const Packet &net_pkt)
5003 {
5005 }
5006
5007 void app_recv(const unsigned int key_id, BufferPtr &&to_app_buf)
5008 {
5010 }
5011
5012 // we're getting a request from peer to renegotiate.
5014 {
5015 // set up dynamic tls-crypt keys when the first rekeying happens
5016 // primary key_id 0 indicates that it is the first rekey
5017 if (conf().dynamic_tls_crypt_enabled() && primary && primary->key_id() == 0)
5019
5020 if (KeyContext::validate(pkt.buffer(), *this, now_))
5021 {
5022 new_secondary_key(false);
5023 return true;
5024 }
5025 return false;
5026 }
5027
5028 // select a KeyContext (primary or secondary) for received network packets
5029 KeyContext &select_key_context(const PacketType &type, const bool control)
5030 {
5031 const unsigned int flags = type.flags & (PacketType::DEFINED | PacketType::SECONDARY | PacketType::CONTROL);
5032 if (!control)
5033 {
5034 if (flags == (PacketType::DEFINED) && primary)
5035 return *primary;
5037 return *secondary;
5038 }
5039 else
5040 {
5042 {
5043 return *primary;
5044 }
5046 && secondary)
5047 {
5048 return *secondary;
5049 }
5050 }
5051 throw select_key_context_error();
5052 }
5053
5054 // Select a KeyContext (primary or secondary) for control channel sends.
5055 // Even after new key context goes active, we still wait for
5056 // KEV_BECOME_PRIMARY event (controlled by the become_primary duration
5057 // in Config) before we use it for app-level control-channel
5058 // transmissions. Simulations have found this method to be more reliable
5059 // than the immediate rollover practiced by OpenVPN 2.x.
5061 {
5062 OVPN_LOG_VERBOSE(debug_prefix() << " CONTROL SEND");
5063 if (!primary)
5064 throw proto_error("select_control_send_context: no primary key");
5065 return *primary;
5066 }
5067
5068 // Possibly send a keepalive message, and check for expiration
5069 // of session due to lack of received packets from peer.
5071 {
5072 const Time now = *now_;
5073
5074 // check for keepalive timeouts
5075 if (now >= keepalive_xmit && primary)
5076 {
5077 primary->send_keepalive();
5079 }
5080 if (now >= keepalive_expire)
5081 {
5082 // no contact with peer, disconnect
5085 }
5086 }
5087
5088 // Process KEV_x events
5089 // Return true if any events were processed.
5091 {
5092 bool did_work = false;
5093
5094 // primary
5095 if (primary && primary->event_pending())
5096 {
5098 did_work = true;
5099 }
5100
5101 // secondary
5102 if (secondary && secondary->event_pending())
5103 {
5105 did_work = true;
5106 }
5107
5108 return did_work;
5109 }
5110
5111 // Create a new secondary key.
5112 // initiator --
5113 // false : remote renegotiation request
5114 // true : local renegotiation request
5115 void new_secondary_key(const bool initiator)
5116 {
5117 // Create the secondary
5118 secondary.reset(new KeyContext(*this, initiator));
5120 << " New KeyContext SECONDARY id=" << secondary->key_id()
5121 << (initiator ? " local-triggered" : " remote-triggered"));
5122 }
5123
5124 // Promote a newly renegotiated KeyContext to primary status.
5125 // This is usually triggered by become_primary variable (Time::Duration)
5126 // in Config.
5128 {
5130 if (primary)
5132 if (secondary)
5133 secondary->prepare_expire();
5134 OVPN_LOG_VERBOSE(debug_prefix() << " PRIMARY_SECONDARY_SWAP");
5135 }
5136
5138 {
5139 const KeyContext::EventType ev = primary->get_event();
5140 if (ev != KeyContext::KEV_NONE)
5141 {
5142 primary->reset_event();
5143 switch (ev)
5144 {
5146 OVPN_LOG_VERBOSE(debug_prefix() << " SESSION_ACTIVE");
5148 proto_callback->active(true);
5149 break;
5152 renegotiate();
5153 break;
5155 if (secondary && !secondary->invalidated())
5157 else
5158 {
5160 // primary context expired and no secondary context available
5162 }
5163 break;
5166 // primary negotiation failed
5168 break;
5169 default:
5170 break;
5171 }
5172 }
5173 primary->set_next_event_if_unspecified();
5174 }
5175
5177 {
5178 const KeyContext::EventType ev = secondary->get_event();
5179 if (ev != KeyContext::KEV_NONE)
5180 {
5181 secondary->reset_event();
5182 switch (ev)
5183 {
5186 if (primary)
5187 primary->prepare_expire();
5188 proto_callback->active(false);
5189 break;
5191 if (!secondary->invalidated())
5193 break;
5196 secondary.reset();
5197 break;
5199 if (primary)
5201 secondary->become_primary_time());
5202 break;
5205 [[fallthrough]];
5208 renegotiate();
5209 break;
5210 default:
5211 break;
5212 }
5213 }
5214 if (secondary)
5215 secondary->set_next_event_if_unspecified();
5216 }
5217
5218 std::string debug_prefix()
5219 {
5220 std::string ret = openvpn::to_string(now_->raw());
5221 ret += is_server() ? " SERVER[" : " CLIENT[";
5222 if (primary)
5223 ret += openvpn::to_string(primary->key_id());
5224 if (secondary)
5225 {
5226 ret += '/';
5227 ret += openvpn::to_string(secondary->key_id());
5228 }
5229 ret += ']';
5230 return ret;
5231 }
5232
5233 // key_id starts at 0, increments to KEY_ID_MASK, then recycles back to 1.
5234 // Therefore, if key_id is 0, it is the first key.
5235 unsigned int next_key_id()
5236 {
5237 ++n_key_ids;
5238 unsigned int ret = upcoming_key_id;
5239 if ((upcoming_key_id = (upcoming_key_id + 1) & KEY_ID_MASK) == 0)
5240 upcoming_key_id = 1;
5241 return ret;
5242 }
5243
5244 // call whenever keepalive parms are modified,
5245 // to reset timers
5247 {
5249
5250 // For keepalive_xmit timer, don't reschedule current cycle
5251 // unless it would fire earlier. Subsequent cycles will
5252 // time according to new keepalive_ping value.
5253 const Time kx = *now_ + config->keepalive_ping;
5254 if (kx < keepalive_xmit)
5255 keepalive_xmit = kx;
5256 }
5257
5259 {
5260 if (!config->wkc.defined())
5261 throw proto_error("Client Key Wrapper undefined");
5262 dst.append(config->wkc);
5263 }
5264
5265 // BEGIN ProtoContext data members
5266
5273
5276
5279 Mode mode_; // client or server
5280 unsigned int upcoming_key_id = 0;
5281 unsigned int n_key_ids;
5282
5283 TimePtr now_; // pointer to current time (a clone of config->now)
5284 Time keepalive_xmit; // time in future when we will transmit a keepalive (subject to continuous change)
5285 Time keepalive_expire; // time in future when we must have received a packet from peer or we will timeout session
5286
5287 Time::Duration slowest_handshake_; // longest time to reach a successful handshake
5288
5291
5294
5296
5307
5316
5319
5322
5325 bool dc_deferred = false;
5326
5327 // END ProtoContext data members
5328};
5329
5330} // namespace openvpn
5331
5332#endif // OPENVPN_SSL_PROTO_H
#define OPENVPN_BS64_DATA_LIMIT
void swap(BufferAllocatedType< T_ > &other)
Swaps the contents of this BufferAllocatedType object with another BufferAllocatedType object.
Definition buffer.hpp:1796
bool advance(size_t size)
void put(BufferPtr bp)
report various types of exceptions or errors that may occur when working with buffers
Definition buffer.hpp:115
static Type parse_method(const std::string &method)
Definition compress.hpp:467
const char * options_string() const
Definition compress.hpp:391
unsigned int extra_payload_bytes() const
Definition compress.hpp:186
const char * str() const
Definition compress.hpp:411
static Type stub(const Type t)
Definition compress.hpp:488
const char * peer_info_string() const
Definition compress.hpp:278
static bool is_any_stub(const Type t)
Definition compress.hpp:507
virtual void decompress(BufferAllocated &buf)=0
virtual void compress(BufferAllocated &buf, const bool hint)=0
const T * c_data() const
Returns a const pointer to the start of the buffer.
Definition buffer.hpp:1193
T * prepend_alloc(const size_t size)
Allocate space for prepending data to the buffer.
Definition buffer.hpp:1594
void append(const B &other)
Append data from another buffer to this buffer.
Definition buffer.hpp:1623
void inc_size(const size_t delta)
Increment the size of the array (usually used in a similar context to set_size such as after mutable_...
Definition buffer.hpp:1389
size_t max_size() const
Return the maximum allowable size value in T objects given the current offset (without considering re...
Definition buffer.hpp:1374
void prepend(const T *data, const size_t size)
Prepend data to the buffer.
Definition buffer.hpp:1572
size_t size() const
Returns the size of the buffer in T objects.
Definition buffer.hpp:1241
T * data()
Get a mutable pointer to the start of the array.
Definition buffer.hpp:1447
void advance(const size_t delta)
Advances the buffer by the specified delta.
Definition buffer.hpp:1276
bool empty() const
Returns true if the buffer is empty.
Definition buffer.hpp:1235
void write(const T *data, const size_t size)
Write data to the buffer.
Definition buffer.hpp:1560
auto * read_alloc(const size_t size)
Allocate memory and read data from the buffer into the allocated memory.
Definition buffer.hpp:1342
T pop_front()
Removes and returns the first element from the buffer.
Definition buffer.hpp:1255
void push_front(const T &value)
Append a T object to the array, with possible resize.
Definition buffer.hpp:1487
void set_size(const size_t size)
After an external method, operating on the array as a mutable unsigned char buffer,...
Definition buffer.hpp:1381
void null_terminate()
Null-terminate the array.
Definition buffer.hpp:1505
void reset_size()
Resets the size of the buffer to zero.
Definition buffer.hpp:1169
void read(NCT *data, const size_t size)
Read data from the buffer into the specified memory location.
Definition buffer.hpp:1330
const char * name() const
virtual CryptoDCInstance::Ptr new_obj(const unsigned int key_id)=0
virtual size_t encap_overhead() const =0
virtual void explicit_exit_notify()
Definition cryptodc.hpp:78
virtual void init_pid(const char *recv_name, const int recv_unit, const SessionStats::Ptr &recv_stats_arg)=0
virtual unsigned int defined() const =0
virtual void init_remote_peer_id(const int remote_peer_id)
Definition cryptodc.hpp:72
virtual void init_hmac(StaticKey &&encrypt_key, StaticKey &&decrypt_key)=0
virtual void rekey(const RekeyType type)=0
virtual bool encrypt(BufferAllocated &buf, const unsigned char *op32)=0
virtual Error::Type decrypt(BufferAllocated &buf, std::time_t now, const unsigned char *op32)=0
virtual bool consider_compression(const CompressContext &comp_ctx)=0
virtual void init_cipher(StaticKey &&encrypt_key, StaticKey &&decrypt_key)=0
CryptoAlgs::Type cipher() const
Definition cryptodc.hpp:118
CryptoAlgs::KeyDerivation key_derivation() const
Definition cryptodc.hpp:145
CryptoAlgs::Type digest() const
Definition cryptodc.hpp:130
void set_key_derivation(CryptoAlgs::KeyDerivation method)
Definition cryptodc.hpp:140
CryptoDCContext & context()
Definition cryptodc.hpp:230
void set_use_epoch_keys(bool at_the_end)
Definition cryptodc.hpp:221
void set_digest(const CryptoAlgs::Type new_digest)
Definition cryptodc.hpp:212
void set_cipher(const CryptoAlgs::Type new_cipher)
Definition cryptodc.hpp:203
static const char * mode_str(const Mode m)
Definition datalimit.hpp:67
static const char * state_str(const State s)
Definition datalimit.hpp:80
unsigned int size_type
Definition datalimit.hpp:25
@ WRITE_SSL_CLEARTEXT
Definition frame.hpp:44
@ READ_BIO_MEMQ_STREAM
Definition frame.hpp:41
size_t prepare(const unsigned int context, Buffer &buf) const
Definition frame.hpp:263
const char * dev_type() const
Definition layer.hpp:48
static void mssfix(BufferAllocated &buf, uint16_t mss_fix)
Definition mssfix.hpp:31
bool is_server() const
Definition mode.hpp:36
bool is_client() const
Definition mode.hpp:40
const char * str() const
Definition mode.hpp:55
void XOR(const OpenVPNStaticKey &other)
unsigned char * raw_alloc()
void parse(const std::string &key_text)
StaticKey slice(unsigned int key_specifier) const
const Option * get_ptr(const std::string &name) const
Definition options.hpp:1179
bool exists(const std::string &name) const
Definition options.hpp:1313
const std::string & get(const size_t index, const size_t max_len) const
Definition options.hpp:189
T get_num(const size_t idx) const
Definition options.hpp:221
size_t size() const
Definition options.hpp:325
void min_args(const size_t n) const
Definition options.hpp:128
const std::string & ref(const size_t i) const
Definition options.hpp:351
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:4105
bool client_supports_auth_pending_kwargs() const
Definition proto.hpp:4077
IvProtoHelper(const OptionList &peer_info)
Definition proto.hpp:4057
bool client_supports_temp_auth_failed() const
Definition proto.hpp:4067
bool client_supports_exit_notify() const
Checks if the client is able to send an explicit EXIT message before exiting.
Definition proto.hpp:4093
bool client_supports_dynamic_tls_crypt() const
Checks if the client can handle dynamic TLS-crypt.
Definition proto.hpp:4099
void encapsulate(id_t id, Packet &pkt)
Definition proto.hpp:3496
static const char * event_type_string(const EventType et)
Definition proto.hpp:1808
bool decapsulate_post_process(Packet &pkt, ProtoSessionID &src_psid, const PacketIDControl pid)
Definition proto.hpp:3526
void kev_error(const EventType ev, const Error::Type reason)
Definition proto.hpp:3038
static BufferAllocated static_work
Definition proto.hpp:3985
static bool validate(const Buffer &net_buf, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2169
void set_protocol(const Protocol &p)
Definition proto.hpp:1868
void prepend_dest_psid_and_acks(Buffer &buf, unsigned int opcode)
Definition proto.hpp:3286
TLSPRFInstance::Ptr tlsprf
Definition proto.hpp:3972
bool net_recv(Packet &&pkt)
Definition proto.hpp:1953
static bool strip_resent_wkc(Buffer &recv, const ProtoConfig &proto_config)
Virtually remove a resent WKc from the end of a CONTROL_WKC_V1 packet.
Definition proto.hpp:2676
void set_state(const int newstate)
Definition proto.hpp:2886
std::deque< BufferPtr > app_pre_write_queue
Definition proto.hpp:3978
void recv_auth(BufferPtr buf)
Definition proto.hpp:3226
bool decapsulate_tls_plain(Packet &pkt)
Definition proto.hpp:3696
static bool validate_tls_plain(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2816
void app_recv(BufferPtr &&to_app_buf)
Definition proto.hpp:3133
bool pkt_from_peer
Set per packet by accept_peer(), read by decapsulate()
Definition proto.hpp:3966
void net_send(const Packet &net_pkt, const Base::NetSendType nstype)
Definition proto.hpp:3166
size_t control_channel_wrap_overhead() const
Definition proto.hpp:3457
void app_send(BufferPtr &&bp)
Definition proto.hpp:1941
static size_t tls_crypt_frame_size(const ProtoConfig &proto_config)
Smallest tls-crypt frame a WKc can be appended to.
Definition proto.hpp:2399
void set_event(const EventType current)
Definition proto.hpp:2894
void raw_recv(Packet &&raw_pkt)
Definition proto.hpp:3112
void gen_head(const unsigned int opcode, BufferAllocated &buf)
Definition proto.hpp:3424
size_t control_ciphertext_capacity(id_t id) const
Definition proto.hpp:3475
std::unique_ptr< DataLimit > data_limit
Definition proto.hpp:3981
void prepare_expire(const EventType current_ev=KeyContext::KEV_NONE)
Definition proto.hpp:2032
void decrypt(BufferAllocated &buf)
Definition proto.hpp:1982
void send_data_channel_message(const unsigned char *data, const size_t size)
Definition proto.hpp:2147
void gen_head_tls_crypt(const unsigned int opcode, BufferAllocated &buf)
Definition proto.hpp:3366
void gen_head_tls_plain(const unsigned int opcode, Buffer &buf)
Definition proto.hpp:3416
void encrypt(BufferAllocated &buf)
Definition proto.hpp:1961
void accept_peer(const ProtoSessionID &src_psid)
Adopt src_psid as our peer, and mark this packet as ours.
Definition proto.hpp:3324
bool recv_auth_complete(BufferComplete &bc) const
Definition proto.hpp:3243
static Error::Type unwrap_tls_crypt_wkc(Buffer &recv, const ProtoConfig &proto_config, TLSCryptInstance &tls_crypt_server, UnwrappedWkc &unwrapped)
Extract and process the TLS crypt WKc information.
Definition proto.hpp:2491
bool verify_src_psid(const ProtoSessionID &src_psid)
Definition proto.hpp:3304
void generate_ack(Packet &pkt)
Definition proto.hpp:3516
bool verify_dest_psid(Buffer &buf)
Definition proto.hpp:3331
Error::Type invalidation_reason() const
Definition proto.hpp:2088
bool tls_crypt_v2_wanted(const Packet &pkt) const
May this packet make a tls-auth server session a tls-crypt-v2 one?
Definition proto.hpp:3748
bool packet_carries_wkc(id_t id) const
Definition proto.hpp:3446
bool parse_early_negotiation(const Packet &pkt)
Definition proto.hpp:3068
void calculate_mssfix(ProtoConfig &c)
Definition proto.hpp:2230
bool decapsulate_tls_crypt(Packet &pkt)
Definition proto.hpp:3629
static bool validate_tls_crypt(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2741
void start(const ProtoSessionID cookie_psid=ProtoSessionID())
Initialize the state machine and start protocol negotiation.
Definition proto.hpp:1885
void invalidate(const Error::Type reason)
Definition proto.hpp:1912
static size_t wkc_overhead(const ProtoConfig &proto_config)
What a WKc holds besides the client key and the metadata.
Definition proto.hpp:2415
uint32_t get_tls_warnings() const
Definition proto.hpp:1873
static bool trailing_wkc_len(const Buffer &recv, const ProtoConfig &proto_config, const size_t min_wkc_len, uint16_t &wkc_len)
Read and validate the WKc length a tls-crypt-v2 packet ends with.
Definition proto.hpp:2436
void gen_head_tls_auth(const unsigned int opcode, Buffer &buf)
Definition proto.hpp:3344
void app_send_validate(BufferPtr &&bp)
Definition proto.hpp:1933
bool decapsulate_by_wrap_mode(Packet &pkt)
Decapsulate pkt with the wrap mode this session is in.
Definition proto.hpp:3833
OPENVPN_SIMPLE_EXCEPTION(tls_crypt_unwrap_wkc_error)
void data_limit_event(const DataLimit::Mode mode, const DataLimit::State state)
Definition proto.hpp:2959
CryptoDCInstance::Ptr crypto
Definition proto.hpp:3971
KeyContext(ProtoContext &p, const bool initiator, bool psid_cookie_mode=false)
Definition proto.hpp:1835
unsigned int key_id() const
Definition proto.hpp:2094
static bool validate_tls_auth(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2693
unsigned int initial_op(const bool sender, const bool tls_crypt_v2) const
Definition proto.hpp:3045
int seconds_until(const Time &next_time)
Definition proto.hpp:3945
static const char * state_string(const int s)
Definition proto.hpp:3913
void data_limit_notify(const DataLimit::Mode cdl_mode, const DataLimit::State cdl_status)
Definition proto.hpp:2381
bool do_encrypt(BufferAllocated &buf, const bool compress_hint)
Definition proto.hpp:2836
std::unique_ptr< DataChannelKey > data_channel_key
Definition proto.hpp:3979
bool data_limit_add(const DataLimit::Mode mode, const size_t size)
Definition proto.hpp:2948
void set_event(const EventType current, const EventType next, const Time &next_time)
Definition proto.hpp:2902
void rekey(const CryptoDCInstance::RekeyType type)
Definition proto.hpp:2111
bool decapsulate(Packet &pkt)
Definition proto.hpp:3757
void key_limit_reneg(const EventType ev, const Time &t)
Definition proto.hpp:2047
bool decapsulate_tls_auth(Packet &pkt)
Definition proto.hpp:3595
PacketType(const Buffer &buf, class ProtoContext &proto)
Definition proto.hpp:1348
bool contains_tls_ciphertext() const
Definition proto.hpp:1682
Packet(BufferPtr &&buf_arg, const unsigned int opcode_arg=CONTROL_V1)
Definition proto.hpp:1651
void frame_prepare(const Frame &frame, const unsigned int context)
Definition proto.hpp:1671
const Buffer & buffer() const
Definition proto.hpp:1694
const BufferPtr & buffer_ptr()
Definition proto.hpp:1690
void parse_pushed_peer_id(const OptionList &opt)
Definition proto.hpp:826
PeerInfo::Set::Ptr extra_peer_info
extra peer info key/value pairs generated by client app
Definition proto.hpp:462
std::string peer_info_string(bool supports_epoch_data) const
Definition proto.hpp:1144
void build_connect_time_peer_info_string(TransportClient::Ptr transport)
Definition proto.hpp:1126
std::string relay_prefix(const char *optname) const
Definition proto.hpp:1301
void load_common(const OptionList &opt, const ProtoContextCompressionOptions &pco, const LoadCommonType type)
Definition proto.hpp:1251
SSLFactoryAPI::Ptr ssl_factory
Definition proto.hpp:366
void set_protocol(const Protocol &p)
Definition proto.hpp:1017
TLSCryptContext::Ptr tls_crypt_context
Definition proto.hpp:445
TLSCryptFactory::Ptr tls_crypt_factory
Definition proto.hpp:444
TLSCryptMetadataFactory::Ptr tls_crypt_metadata_factory
Definition proto.hpp:447
bool tls_crypt_v2_serverkey_id
do we expect keys to contain a server key ID?
Definition proto.hpp:432
std::string tls_crypt_v2_serverkey_dir
server keys location, if tls_crypt_v2_serverkey_id is true
Definition proto.hpp:435
void show_cc_enc_option(std::ostringstream &os) const
Definition proto.hpp:978
BufferAllocated wkc
leave this undefined to disable tls-crypt-v2 on client
Definition proto.hpp:438
void set_tls_auth_digest(const CryptoAlgs::Type digest)
Definition proto.hpp:1023
void parse_pushed_data_channel_options(const OptionList &opt)
Definition proto.hpp:789
AppControlMessageReceiver app_control_recv
Definition proto.hpp:466
void get_data_channel_options(std::ostringstream &os) const
Definition proto.hpp:963
void set_xmit_creds(const bool xmit_creds_arg)
Definition proto.hpp:1045
void process_push(const OptionList &opt, const ProtoContextCompressionOptions &pco)
Definition proto.hpp:730
AppControlMessageConfig app_control_config
Definition proto.hpp:465
OpenVPNStaticKey tls_crypt_key
leave this undefined to disable tls-crypt/tls-crypt-v2
Definition proto.hpp:426
void load(const OptionList &opt, const ProtoContextCompressionOptions &pco, const int default_key_direction, const bool server)
Definition proto.hpp:497
void parse_pushed_protocol_flags(const OptionList &opt)
Definition proto.hpp:849
OpenVPNStaticKey tls_auth_key
leave this undefined to disable tls_auth
Definition proto.hpp:423
PeerInfo::Set::Ptr extra_peer_info_transport
Definition proto.hpp:469
std::string show_options() const
Definition proto.hpp:998
Time::Duration keepalive_timeout_early
Definition proto.hpp:459
unsigned tls_crypt_
needed to distinguish between tls-crypt and tls-crypt-v2 server mode
Definition proto.hpp:429
void parse_custom_app_control(const OptionList &opt)
Definition proto.hpp:761
void parse_pushed_compression(const OptionList &opt, const ProtoContextCompressionOptions &pco)
Definition proto.hpp:911
OvpnHMACContext::Ptr tls_auth_context
Definition proto.hpp:441
TLSPRFFactory::Ptr tlsprf_factory
Definition proto.hpp:372
StrongRandomAPI::Ptr rng
Definition proto.hpp:383
OvpnHMACFactory::Ptr tls_auth_factory
Definition proto.hpp:440
bool is_clients_handshake_ack_tls_auth() const
Returns true if this could be the third packet of the 3-way handshake (tls-auth/none).
Definition proto.hpp:4014
static unsigned char get_server_hard_reset_opfield()
Definition proto.hpp:4044
bool is_clients_handshake_ack_tls_crypt_v2() const
Returns true if this could be the third packet of the 3-way handshake (tls-crypt-v2).
Definition proto.hpp:4020
bool supports_early_negotiation(const PacketIDControl &pidc) const noexcept
Returns true if the peer supports early negotiation (i.e. is able to reply with CONTROL_WKC_V1).
Definition proto.hpp:4008
bool is_ack_v1() const
Returns true if the packet is a P_ACK_V1 (no own message-id field on the wire).
Definition proto.hpp:4026
PsidCookieHelper(unsigned int op_field)
Definition proto.hpp:3991
static void prepend_TLV(Buffer &payload)
Adds an {EARLY_NEG_FLAGS, 2, EARLY_NEG_FLAG_RESEND_WKC} TLV to a payload buffer (use with TLS crypt V...
Definition proto.hpp:4032
bool is_tls_crypt_v2() const noexcept
Returns true if this is a TLS crypt V2 protocol packet.
Definition proto.hpp:4002
TLSAuthPreValidate(const ProtoConfig &c, const bool server)
Definition proto.hpp:4128
OPENVPN_SIMPLE_EXCEPTION(tls_auth_pre_validate)
bool validate(const BufferAllocated &net_buf)
Definition proto.hpp:4155
OPENVPN_SIMPLE_EXCEPTION(tls_crypt_pre_validate)
TLSCryptPreValidate(const ProtoConfig &c, const bool server)
Definition proto.hpp:4189
bool validate(const BufferAllocated &net_buf)
Definition proto.hpp:4226
virtual bool validate(const BufferAllocated &net_buf)=0
void data_limit_notify(const unsigned int key_id, const DataLimit::Mode cdl_mode, const DataLimit::State cdl_status)
Definition proto.hpp:4866
bool control_net_recv(const PacketType &type, BufferPtr &&net_bp)
Definition proto.hpp:4688
void set_local_peer_id(const int local_peer_id)
Definition proto.hpp:4889
uint32_t get_tls_warnings() const
Definition proto.hpp:4332
void send_explicit_exit_notify()
Definition proto.hpp:4754
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, process_server_push_error)
bool is_client() const
Definition proto.hpp:4923
void net_send(const unsigned int key_id, const Packet &net_pkt)
Definition proto.hpp:5002
const Time::Duration & slowest_handshake()
Definition proto.hpp:4794
const Time & now() const
Definition proto.hpp:4895
CryptoDCSettings & dc_settings()
Definition proto.hpp:4877
void flush(const bool control_channel)
Definition proto.hpp:4615
void set_dynamic_tls_crypt(const ProtoConfig &c, const KeyContext::Ptr &key_ctx)
Definition proto.hpp:4362
OPENVPN_SIMPLE_EXCEPTION(select_key_context_error)
void control_send(BufferPtr &&app_bp)
Definition proto.hpp:4671
KeyContext & select_control_send_context()
Definition proto.hpp:5060
bool uses_bs64_cipher() const
Definition proto.hpp:4341
void process_secondary_event()
Definition proto.hpp:5176
void reset_tls_crypt(const ProtoConfig &c, const OpenVPNStaticKey &key)
Definition proto.hpp:4346
OpenVPNStaticKey tls_crypt_client_key
Kc, the tls-crypt-v2 client key this session's control channel is keyed with.
Definition proto.hpp:5306
PacketType packet_type(const Buffer &buf)
Definition proto.hpp:4565
void data_encrypt(BufferAllocated &in_out)
Definition proto.hpp:4709
void reset_tls_crypt_server(const ProtoConfig &c)
Definition proto.hpp:4412
bool dynamic_tls_crypt_keyed
Whether set_dynamic_tls_crypt() has keyed this session already.
Definition proto.hpp:5315
TLSCryptInstance::Ptr tls_crypt_recv
Definition proto.hpp:5293
bool is_keepalive_enabled() const
Definition proto.hpp:4842
KeyContext::Ptr primary
Definition proto.hpp:5323
TLSCryptInstance::Ptr tls_crypt_server
Definition proto.hpp:5295
const Frame & frame() const
Definition proto.hpp:4905
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:324
static S read_auth_string(Buffer &buf)
Definition proto.hpp:1584
ProtoConfig::Ptr conf_ptr() const
Definition proto.hpp:4947
ProtoSessionID psid_peer
Definition proto.hpp:5321
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_option_error)
void process_primary_event()
Definition proto.hpp:5137
const Mode & mode() const
Definition proto.hpp:4915
TLSCryptInstance::Ptr tls_crypt_send
Definition proto.hpp:5292
void process_push(const OptionList &opt, const ProtoContextCompressionOptions &pco)
Definition proto.hpp:4826
static void write_auth_string(const S &str, Buffer &buf)
Definition proto.hpp:1570
void client_auth(Buffer &buf)
Definition proto.hpp:4992
ProtoConfig & conf()
Definition proto.hpp:4943
static const char * opcode_name(const unsigned int opcode)
Definition proto.hpp:1429
static unsigned int opcode_extract(const unsigned int op)
Definition proto.hpp:309
void set_protocol(const Protocol &p)
Definition proto.hpp:4540
static unsigned int key_id_extract(const unsigned int op)
Definition proto.hpp:314
ProtoSessionID psid_self
Definition proto.hpp:5320
static S read_control_string(const Buffer &buf)
Definition proto.hpp:1610
void write_control_string(const S &str)
Definition proto.hpp:1631
bool data_channel_ready() const
Definition proto.hpp:4782
void keepalive_housekeeping()
Definition proto.hpp:5070
Time::Duration slowest_handshake_
Definition proto.hpp:5287
unsigned int upcoming_key_id
Definition proto.hpp:5280
static unsigned int op32_compose(const unsigned int opcode, const unsigned int key_id, const int op_peer_id)
Definition proto.hpp:331
size_t align_adjust_hint() const
Definition proto.hpp:4836
PacketIDControlReceive ta_pid_recv
Definition proto.hpp:5318
ProtoContextCallbackInterface * proto_callback
Definition proto.hpp:5272
void reset_tls_wrap_mode(const ProtoConfig &c)
Definition proto.hpp:4294
SessionStats & stat() const
Definition proto.hpp:4953
bool is_server() const
Definition proto.hpp:4919
OvpnHMACInstance::Ptr ta_hmac_recv
Definition proto.hpp:5290
std::string dump_packet(const Buffer &buf)
Definition proto.hpp:1455
void disconnect(const Error::Type reason)
Definition proto.hpp:4744
static uint16_t read_uint16_length(Buffer &buf)
Definition proto.hpp:1558
bool control_net_validate(const PacketType &type, const Buffer &net_buf)
Definition proto.hpp:4682
KeyContext & select_key_context(const PacketType &type, const bool control)
Definition proto.hpp:5029
static void write_empty_string(Buffer &buf)
Definition proto.hpp:1604
TLSWrapMode tls_wrap_mode
Definition proto.hpp:5278
void app_recv(const unsigned int key_id, BufferPtr &&to_app_buf)
Definition proto.hpp:5007
void keepalive_parms_modified()
Definition proto.hpp:5246
int primary_state() const
Definition proto.hpp:4965
static void write_control_string(const S &str, Buffer &buf)
Definition proto.hpp:1597
void control_send(BufferAllocated &&app_buf)
Definition proto.hpp:4676
bool data_decrypt(const PacketType &type, BufferAllocated &in_out)
Definition proto.hpp:4719
void disable_keepalive(unsigned int &keepalive_ping, unsigned int &keepalive_timeout)
Definition proto.hpp:4850
static constexpr PacketIDControl::id_t EARLY_NEG_MASK
Definition proto.hpp:307
static constexpr PacketIDControl::id_t EARLY_NEG_START
Definition proto.hpp:306
Error::Type invalidation_reason() const
Definition proto.hpp:4806
static size_t op_head_size(const unsigned int op)
Definition proto.hpp:319
void new_secondary_key(const bool initiator)
Definition proto.hpp:5115
void update_last_received()
Definition proto.hpp:4997
void promote_secondary_to_primary()
Definition proto.hpp:5127
bool is_state_client_wait_reset_ack() const
Definition proto.hpp:4959
unsigned int negotiations() const
Definition proto.hpp:4788
PacketIDControlSend ta_pid_send
Definition proto.hpp:5317
Time next_housekeeping() const
Definition proto.hpp:4653
ProtoContext(ProtoContextCallbackInterface *cb_arg, const ProtoConfig::Ptr &config_arg, const SessionStats::Ptr &stats_arg)
Definition proto.hpp:4281
static void write_uint16_length(const size_t size, Buffer &buf)
Definition proto.hpp:1550
SessionStats::Ptr stats
Definition proto.hpp:5275
static constexpr size_t OPCODE_SIZE
Definition proto.hpp:216
unsigned int n_key_ids
Definition proto.hpp:5281
void tls_crypt_append_wkc(BufferAllocated &dst)
Definition proto.hpp:5258
ProtoConfig::Ptr config
Definition proto.hpp:5274
bool control_net_recv(const PacketType &type, BufferAllocated &&net_buf)
pass received control channel network packets (ciphertext) into protocol object
Definition proto.hpp:4703
virtual ~ProtoContext()=default
std::string debug_prefix()
Definition proto.hpp:5218
static constexpr size_t APP_MSG_MAX
Definition proto.hpp:214
const Frame::Ptr & frameptr() const
Definition proto.hpp:4909
bool invalidated() const
Definition proto.hpp:4800
void reset(const ProtoSessionID cookie_psid=ProtoSessionID())
Resets ProtoContext *this to it's initial state.
Definition proto.hpp:4436
void start(const ProtoSessionID cookie_psid=ProtoSessionID())
Initialize the state machine and start protocol negotiation.
Definition proto.hpp:4578
bool renegotiate_request(Packet &pkt)
Definition proto.hpp:5013
static constexpr size_t MAX_CONTROL_WRAP_OVERHEAD
Definition proto.hpp:350
KeyContext::Ptr secondary
Definition proto.hpp:5324
unsigned int next_key_id()
Definition proto.hpp:5235
OvpnHMACInstance::Ptr ta_hmac_send
Definition proto.hpp:5289
const ProtoConfig & conf() const
Definition proto.hpp:4939
bool match(const ProtoSessionID &other) const
Definition psid.hpp:90
std::string str() const
Definition psid.hpp:95
constexpr bool defined() const
Definition psid.hpp:85
void randomize(StrongRandomAPI &rng)
Definition psid.hpp:52
void prepend(Buffer &buf) const
Definition psid.hpp:70
ReliableSendTemplate< Packet > ReliableSend
const AuthCert::Ptr & auth_cert() const
void export_key_material(OpenVPNStaticKey &key, const std::string &label) const
void invalidate(const Error::Type reason)
ReliableRecvTemplate< Packet > ReliableRecv
const char * occ_str(const bool server) const
Definition protocol.hpp:284
unsigned int extra_transport_bytes() const
Definition protocol.hpp:127
bool is_reliable() const
Definition protocol.hpp:87
bool is_ipv6() const
Definition protocol.hpp:95
Reference count base class for objects tracked by RCPtr. Allows copying and assignment.
Definition rc.hpp:975
void reset() noexcept
Points this RCPtr<T> to nullptr safely.
Definition rc.hpp:290
void swap(RCPtr &rhs) noexcept
swaps the contents of two RCPtr<T>
Definition rc.hpp:311
Reference count base class for objects tracked by RCPtr. Disallows copying and assignment.
Definition rc.hpp:908
static Ptr Create(ArgsT &&...args)
Creates a new instance of RcEnable with the given arguments.
Definition make_rc.hpp:43
static void prepend_id(Buffer &buf, const id_t id)
Definition relack.hpp:119
bool acks_ready() const
Definition relack.hpp:166
void push_back(id_t value)
Definition relack.hpp:39
void prepend(Buffer &buf, bool ackv1)
Definition relack.hpp:93
static id_t read_id(Buffer &buf)
Definition relack.hpp:125
static constexpr size_t maximum_acks_control_v1
Definition relack.hpp:32
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
void parse(const std::string &key_text)
void extract_wkc(BufferAllocated &wkc_out) const
void extract_key(OpenVPNStaticKey &tls_key)
void extract_key(OpenVPNStaticKey &tls_key)
void parse(const std::string &key_text)
virtual void self_write(Buffer &buf)=0
virtual void peer_read(Buffer &buf)=0
virtual void self_randomize(StrongRandomAPI &rng)=0
virtual void erase()=0
virtual void generate_key_expansion(OpenVPNStaticKey &dest, const ProtoSessionID &psid_self, const ProtoSessionID &psid_peer) const =0
virtual bool peer_read_complete(BufferComplete &bc)=0
T raw() const
Definition time.hpp:404
static TimeType infinite()
Definition time.hpp:254
void min(const TimeType &t)
Definition time.hpp:337
base_type seconds_since_epoch() const
Definition time.hpp:289
bool defined() const
Definition time.hpp:280
#define OPENVPN_THROW_ARG1(exc, arg, stuff)
#define OPENVPN_THROW(exc, stuff)
#define likely(x)
Definition likely.hpp:21
#define unlikely(x)
Definition likely.hpp:22
#define OPENVPN_LOG(args)
#define OVPN_LOG_DEBUG(args)
Definition logger.hpp:226
#define OVPN_LOG_INFO(args)
Definition logger.hpp:224
#define OVPN_LOG_VERBOSE(args)
Definition logger.hpp:225
void work(openvpn_io::io_context &io_context, ThreadCommon &tc, MyRunContext &runctx, const unsigned int unit)
constexpr BufferFlags DESTRUCT_ZERO(1U<< 1)
if enabled, destructor will zero data before deletion
constexpr BufferFlags CONSTRUCT_ZERO(1U<< 0)
if enabled, constructors/init will zero allocated space
Mode mode(const Type type)
Type lookup(const std::string &name)
size_t key_length(const Type type)
const char * name(const KeyDerivation kd)
size_t size(const Type type)
std::size_t for_each(std::function< bool(Type, const Alg &)> fn)
@ KEV_NEGOTIATE_ERROR
Definition error.hpp:99
@ KEEPALIVE_TIMEOUT
Definition error.hpp:61
@ N_KEY_LIMIT_RENEG
Definition error.hpp:88
@ HANDSHAKE_TIMEOUT
Definition error.hpp:60
@ TLS_CRYPT_META_FAIL
Definition error.hpp:78
@ EARLY_NEG_INVALID
Definition error.hpp:92
bool is_safe_conversion(InT inVal)
Returns true if the given value can be contained by the out type.
OutT clamp_to_typerange(InT inVal)
Clamps the input value to the legal range for the output type.
std::uint32_t id_t
Definition relcommon.hpp:22
std::vector< T > split(const T &str, const typename T::value_type sep, const int maxsplit=-1)
Definition string.hpp:452
std::string trim_crlf_copy(std::string str)
Definition string.hpp:180
const Option * load_duration_parm(Time::Duration &dur, const std::string &name, const OptionList &opt, const unsigned int min_value, const bool x2, const bool allow_ms)
Definition durhelper.hpp:41
void set_duration_parm(Time::Duration &dur, const std::string &name, const std::string &valstr, const unsigned int min_value, const bool x2, const bool ms)
Definition durhelper.hpp:20
std::string read_text(const std::string &filename, const std::uint64_t max_size=0)
Definition file.hpp:127
std::string to_string(const T &t)
Convert a value to a string.
Definition to_string.hpp:45
const char * platform_name()
@ TUN_MTU_DEFAULT
Definition tunmtu.hpp:20
std::string render_hex(const unsigned char *data, size_t size, const bool caps=false)
Definition hexstr.hpp:133
TimeType< oulong > Time
Definition time.hpp:487
unsigned int parse_tun_mtu_max(const OptionList &opt, unsigned int default_value)
Definition tunmtu.hpp:28
bool is_bs64_cipher(const CryptoAlgs::Type cipher)
unsigned int parse_tun_mtu(const OptionList &opt, unsigned int default_value)
Definition tunmtu.hpp:23
std::string get_hwaddr(IP::Addr server_addr)
Definition hwaddr.hpp:31
std::string dump_hex(const unsigned char *data, size_t size)
Definition hexstr.hpp:253
Implementation of the base classes for random number generators.
std::vector< std::string > supported_protocols
List of supported protocols.
int max_msg_size
Maximum size of each individual message/message fragment.
void parse_flags(const std::string &flags)
unsigned int mssfix_ctrl
Definition mssparms.hpp:87
void parse(const OptionList &opt, bool nothrow=false)
Definition mssparms.hpp:26
unsigned int mssfix
Definition mssparms.hpp:71
static constexpr size_t size()
constexpr std::size_t size() const
std::optional< CryptoDCInstance::RekeyType > rekey_type
Definition proto.hpp:1738
What a WKc yields, owned by whoever asked for the unwrap.
Definition proto.hpp:2476
OpenVPNStaticKey client_key
Kc, the client key the WKc wrapped.
Definition proto.hpp:2478
The metadata record a WKc carried, for TLSCryptMetadata::verify()
Definition proto.hpp:2462
int type
-1 when the WKc carried no metadata at all
Definition proto.hpp:2464
virtual IP::Addr server_endpoint_addr() const =0
static std::stringstream out
Definition test_path.cpp:10
const std::string optname
#define OPENVPN_VERSION
Definition version.hpp:17