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
2174 static bool opcode_carries_wkc(const unsigned int opcode)
2175 {
2176 return opcode == CONTROL_HARD_RESET_CLIENT_V3 || opcode == CONTROL_WKC_V1;
2177 }
2178
2186 static bool tls_crypt_v2_convertible(const ProtoContext &proto, const unsigned int opcode)
2187 {
2188 return proto.is_server()
2190 && !proto.psid_peer.defined()
2191 && proto.config->tls_crypt_v2_enabled()
2192 && opcode_carries_wkc(opcode);
2193 }
2194
2195 // validate the integrity of a packet
2196 static bool validate(const Buffer &net_buf, ProtoContext &proto, TimePtr now)
2197 {
2198 try
2199 {
2200 Buffer recv(net_buf);
2201
2202 switch (proto.tls_wrap_mode)
2203 {
2204 case TLS_AUTH:
2206 {
2207 // Still TLS_AUTH only because decapsulate() has not converted the
2208 // session yet; the tls-auth key would reject every genuine
2209 // tls-crypt-v2 client.
2210 OVPN_LOG_VERBOSE("SKIPPING VALIDATION OF WKc-BEARING PACKET");
2211 return true;
2212 }
2213 return validate_tls_auth(recv, proto, now);
2214 case TLS_CRYPT_V2:
2216 {
2217 // Nothing to judge it with: this packet keys the receive context.
2218 OVPN_LOG_VERBOSE("SKIPPING VALIDATION OF WKc-BEARING PACKET");
2219 return true;
2220 }
2221 /* no break */
2222 case TLS_CRYPT:
2223 return validate_tls_crypt(recv, proto, now);
2224 case TLS_PLAIN:
2225 return validate_tls_plain(recv, proto, now);
2226 }
2227 }
2228 catch ([[maybe_unused]] BufferException &e)
2229 {
2230 OVPN_LOG_VERBOSE("validate() exception: " << e.what());
2231 }
2232 return false;
2233 }
2234
2235 // Resets data_channel_key but also retains old
2236 // rekey_defined and rekey_type from previous instance.
2238 {
2239 std::unique_ptr<DataChannelKey> dck(new DataChannelKey());
2240
2241 if (proto.config->dc.key_derivation() == CryptoAlgs::KeyDerivation::TLS_EKM)
2242 {
2243 // USE RFC 5705 key material export
2244 export_key_material(dck->key, "EXPORTER-OpenVPN-datakeys");
2245 }
2246 else
2247 {
2248 // use the TLS PRF construction to exchange session keys for building
2249 // the data channel crypto context
2251 }
2252 tlsprf->erase();
2254 << " KEY " << CryptoAlgs::name(proto.config->dc.key_derivation())
2255 << " " << proto.mode().str() << ' ' << dck->key.render());
2256
2257 if (data_channel_key)
2258 {
2259 dck->rekey_type = data_channel_key->rekey_type;
2260 }
2261 dck.swap(data_channel_key);
2262 }
2263
2265 {
2266 if (c.mss_parms.fixed)
2267 {
2268 // substract IPv4 and TCP overhead, mssfix method will add extra 20 bytes for IPv6
2269 c.mss_fix = c.mss_parms.mssfix - (20 + 20);
2270 OPENVPN_LOG("fixed mssfix=" << c.mss_fix);
2271 return;
2272 }
2273
2274 /* If we are running default mssfix but have a different tun-mtu pushed
2275 * disable mssfix */
2276 if (c.tun_mtu != TUN_MTU_DEFAULT && c.tun_mtu != 0 && c.mss_parms.mssfix_default)
2277 {
2278 c.mss_fix = 0;
2279 OPENVPN_LOG("mssfix disabled since tun-mtu is non-default ("
2280 << c.tun_mtu << ")");
2281 return;
2282 }
2283
2284 auto payload_overhead = size_t(0);
2285
2286 // compv2 doesn't increase payload size
2287 switch (c.comp_ctx.type())
2288 {
2292 break;
2293 default:
2294 payload_overhead += 1;
2295 }
2296
2298 payload_overhead += PacketIDData::size(false);
2299
2300 // account for IPv4 and TCP headers of the payload, mssfix method
2301 // will add 20 extra bytes if payload is IPv6
2302 payload_overhead += 20 + 20;
2303
2304 auto overhead = c.protocol.extra_transport_bytes()
2305 + (enable_op32 ? OP_SIZE_V2 : 1)
2306 + c.dc.context().encap_overhead();
2307
2308 // in CBC mode, the packet id is part of the payload size / overhead
2310 overhead += PacketIDData::size(false);
2311
2312 if (c.mss_parms.mtu)
2313 {
2314 overhead += c.protocol.is_ipv6()
2315 ? sizeof(struct IPv6Header)
2316 : sizeof(struct IPv4Header);
2317 overhead += proto.is_tcp()
2318 ? sizeof(struct TCPHeader)
2319 : sizeof(struct UDPHeader);
2320 }
2321
2322 auto target = c.mss_parms.mssfix - overhead;
2323 if (CryptoAlgs::mode(c.dc.cipher()) == CryptoAlgs::CBC_HMAC)
2324 {
2325 // openvpn3 crypto includes blocksize in overhead, but we can
2326 // be a bit smarter here and instead make sure that resulting
2327 // ciphertext size (which is always multiple blocksize) is not
2328 // larger than target by running down target to the nearest
2329 // multiple of multiple and substracting 1.
2330
2331 auto block_size = CryptoAlgs::block_size(c.dc.cipher());
2332 target += block_size;
2333 target = (target / block_size) * block_size;
2334 target -= 1;
2335 }
2336
2337 if (!is_safe_conversion<decltype(c.mss_fix)>(target - payload_overhead))
2338 {
2339 OPENVPN_LOG("mssfix disabled since computed value is outside type bounds ("
2340 << c.mss_fix << ")");
2341 c.mss_fix = 0;
2342 return;
2343 }
2344
2345 c.mss_fix = static_cast<decltype(c.mss_fix)>(target - payload_overhead);
2346 OVPN_LOG_VERBOSE("mssfix=" << c.mss_fix
2347 << " (upper bound=" << c.mss_parms.mssfix
2348 << ", overhead=" << overhead
2349 << ", payload_overhead=" << payload_overhead
2350 << ", target=" << target << ")");
2351 }
2352
2353 // Initialize the components of the OpenVPN data channel protocol
2355 {
2356 // don't run until our prerequisites are satisfied
2357 if (!data_channel_key)
2358 return;
2360
2361 // set up crypto for data channel
2362 bool enable_compress = true;
2363 ProtoConfig &c = *proto.config;
2364 const unsigned int key_dir = proto.is_server() ? OpenVPNStaticKey::INVERSE : OpenVPNStaticKey::NORMAL;
2365 const OpenVPNStaticKey &key = data_channel_key->key;
2366
2367 // special data limits for 64-bit block-size ciphers (CVE-2016-6329)
2368 if (is_bs64_cipher(c.dc.cipher()))
2369 {
2373 OVPN_LOG_INFO("Per-Key Data Limit: "
2374 << dp.encrypt_red_limit << '/' << dp.decrypt_red_limit);
2375 data_limit.reset(new DataLimit(dp));
2376 }
2377
2378 // build crypto context for data channel encryption/decryption
2381
2386
2390
2391 crypto->init_pid("DATA",
2392 int(key_id_),
2393 proto.stats);
2394
2396
2397 enable_compress = crypto->consider_compression(proto.config->comp_ctx);
2398
2399 if (data_channel_key->rekey_type.has_value())
2400 crypto->rekey(data_channel_key->rekey_type.value());
2401 data_channel_key.reset();
2402
2403 // set up compression for data channel
2404 if (enable_compress)
2405 compress = proto.config->comp_ctx.new_compressor(proto.config->frame, proto.stats);
2406 else
2407 compress.reset();
2408
2409 // cache op32 for hot path in do_encrypt
2410 cache_op32();
2411
2413 }
2414
2416 const DataLimit::State cdl_status)
2417 {
2418 if (data_limit)
2419 data_limit_event(cdl_mode, data_limit->update_state(cdl_mode, cdl_status));
2420 }
2421
2422 int get_state() const
2423 {
2424 return state;
2425 }
2426
2433 static size_t tls_crypt_frame_size(const ProtoConfig &proto_config)
2434 {
2436 + proto_config.tls_crypt_context->digest_size()
2437 // the following is the tls-crypt payload
2438 + sizeof(char) // length of ACK array
2439 + sizeof(id_t); // reliable ID
2440 }
2441
2449 static size_t wkc_overhead(const ProtoConfig &proto_config)
2450 {
2451 return sizeof(uint16_t)
2452 + proto_config.tls_crypt_context->digest_size()
2453 + (proto_config.tls_crypt_v2_serverkey_id ? sizeof(uint32_t) : 0);
2454 }
2455
2470 static bool trailing_wkc_len(const Buffer &recv,
2471 const ProtoConfig &proto_config,
2472 const size_t min_wkc_len,
2473 uint16_t &wkc_len)
2474 {
2475 const size_t frame_size = tls_crypt_frame_size(proto_config);
2476 const size_t orig_size = recv.size();
2477
2478 if (orig_size < (frame_size + sizeof(wkc_len)))
2479 return false;
2480
2481 // avoid unaligned access
2482 std::memcpy(&wkc_len, recv.c_data() + orig_size - sizeof(wkc_len), sizeof(wkc_len));
2483 wkc_len = ntohs(wkc_len);
2484
2485 return wkc_len >= min_wkc_len && wkc_len <= (orig_size - frame_size);
2486 }
2487
2496 {
2498 int type = -1;
2500 };
2501
2515
2526 const ProtoConfig &proto_config,
2528 UnwrappedWkc &unwrapped)
2529 {
2530 // the ``WKc`` is located at the end of the packet, after the tls-crypt
2531 // payload.
2532 //
2533 // K_id is optional, and controlled by proto_config.tls_crypt_v2_serverkey_id.
2534 // If it is missing, we will use a single server key for all clients.
2535 //
2536 // Format is as follows:
2537 //
2538 // ``len = len(WKc)`` (16 bit, network byte order)
2539 // ``T = HMAC-SHA256(Ka, len || K_id || Kc || metadata)``
2540 // ``IV = 128 most significant bits of T``
2541 // ``WKc = T || AES-256-CTR(Ke, IV, Kc || metadata) || K_id || len``
2542
2543 const unsigned char *orig_data = recv.data();
2544 const size_t orig_size = recv.size();
2545 const size_t hmac_size = proto_config.tls_crypt_context->digest_size();
2546 const size_t tls_frame_size = tls_crypt_frame_size(proto_config);
2547
2548 uint32_t k_id = 0;
2549 const size_t serverkey_id_size = proto_config.tls_crypt_v2_serverkey_id ? sizeof(k_id) : 0;
2550
2551 // Establishes ``wkc_overhead() <= wkc_len <= orig_size - tls_frame_size``, so
2552 // the WKc holds its own length field, the authentication tag ``T`` and the
2553 // optional ``K_id``, and fits behind the tls-crypt frame. Both wkc_raw_size
2554 // expressions below then come to at least ``hmac_size + serverkey_id_size``,
2555 // which is what keeps the ``K_id`` read and the ciphertext length handed to
2556 // decrypt() from underflowing.
2557 uint16_t wkc_len;
2558 if (!trailing_wkc_len(recv, proto_config, wkc_overhead(proto_config), wkc_len))
2559 return Error::CC_ERROR;
2560
2561 // A CONTROL_HARD_RESET_CLIENT_V3 carries nothing but the ``WKc`` behind the
2562 // tls-crypt frame, so its extent follows from the sizes; a P_CONTROL_WKC_V1
2563 // carries a payload as well, and only ``wkc_len`` locates the ``WKc`` in it.
2564 const unsigned char *wkc_raw;
2565 size_t wkc_raw_size;
2566 if (opcode_extract(orig_data[0]) == CONTROL_HARD_RESET_CLIENT_V3)
2567 {
2568 wkc_raw = orig_data + tls_frame_size;
2569 wkc_raw_size = orig_size - tls_frame_size - sizeof(wkc_len);
2570 }
2571 else
2572 {
2573 wkc_raw = orig_data + orig_size - wkc_len;
2574 wkc_raw_size = wkc_len - sizeof(wkc_len);
2575 }
2576
2577 if (proto_config.tls_crypt_v2_serverkey_id)
2578 {
2579 std::memcpy(&k_id, wkc_raw + wkc_raw_size - serverkey_id_size, sizeof(k_id));
2580 k_id = ntohl(k_id);
2581 }
2582
2583 // length sanity check (the size of the ``len`` field is included in the value)
2584 if ((wkc_len - sizeof(uint16_t)) != wkc_raw_size)
2585 return Error::CC_ERROR;
2586
2588 // plaintext will be used to compute the Auth Tag, therefore start by prepending
2589 // the WKc length in network order
2590 const uint16_t net_wkc_len = htons(wkc_len);
2591 plaintext.write(&net_wkc_len, sizeof(net_wkc_len));
2592
2593 if (proto_config.tls_crypt_v2_serverkey_id)
2594 {
2595 const std::string serverkey_fn = render_hex_number(k_id, true) + ".key";
2596 const std::string serverkey_path = proto_config.tls_crypt_v2_serverkey_dir + "/"
2597 + serverkey_fn.substr(0, 2) + "/" + serverkey_fn;
2598
2599 // The K_id came off the wire, so a client whose key we never had -- or a
2600 // forgery -- names a file that is not there. That is a WKc we cannot unwrap
2601 // and nothing more, so nothing here may leave as an exception: decapsulate()
2602 // catches BufferException alone and open_file_error is not one.
2603 try
2604 {
2605 TLSCryptV2ServerKey tls_crypt_v2_key;
2606 tls_crypt_v2_key.parse(read_text(serverkey_path));
2607
2608 // Ka/Ke are of use only for the unwrap they key below, so they stay here
2609 // rather than on the config the cookie layer shares between sessions.
2610 OpenVPNStaticKey serverkey_material;
2611 tls_crypt_v2_key.extract_key(serverkey_material);
2612
2613 // the server key is composed by one key set only, therefore direction and
2614 // mode should not be specified when slicing
2615 tls_crypt_server.init(proto_config.ssl_factory->libctx(),
2616 serverkey_material.slice(OpenVPNStaticKey::HMAC),
2617 serverkey_material.slice(OpenVPNStaticKey::CIPHER));
2618 }
2619 catch (const std::exception &e)
2620 {
2621 OVPN_LOG_VERBOSE("DROPPING WKc NAMING TLS-crypt-V2 server key "
2622 << serverkey_path << ": " << e.what());
2623 return Error::DECRYPT_ERROR;
2624 }
2625
2626 OVPN_LOG_VERBOSE("Using TLS-crypt-V2 server key " << serverkey_path);
2627
2628 k_id = htonl(k_id);
2629 plaintext.write(&k_id, sizeof(k_id));
2630 }
2631 else
2632 {
2633 // Same key for every client, straight off the config. Keying the context is
2634 // this function's business in either mode: a caller that had to do it for one
2635 // mode and not the other could forget.
2636 if (!proto_config.tls_crypt_key.defined())
2637 {
2638 OVPN_LOG_VERBOSE("DROPPING WKc WITH NO TLS-crypt-V2 SERVER KEY TO UNWRAP IT");
2639 return Error::DECRYPT_ERROR;
2640 }
2641
2642 tls_crypt_server.init(proto_config.ssl_factory->libctx(),
2645 }
2646
2647 // the ``len || K_id`` prefix written above is part of the authenticated
2648 // plaintext, but the decrypted key material goes behind it
2649 const size_t plaintext_prefix_size = sizeof(wkc_len) + serverkey_id_size;
2650
2651 const size_t plaintext_max_size = plaintext.max_size();
2652 if (plaintext_max_size <= plaintext_prefix_size)
2653 return Error::DECRYPT_ERROR;
2654
2655 const size_t decrypt_bytes = tls_crypt_server.decrypt(wkc_raw,
2656 plaintext.data() + plaintext_prefix_size,
2657 plaintext_max_size - plaintext_prefix_size,
2658 wkc_raw + hmac_size,
2659 wkc_raw_size - hmac_size - serverkey_id_size);
2660 plaintext.inc_size(decrypt_bytes);
2661
2662 // The decrypted part must hold a full 2048-bit client key; metadata behind it is
2663 // optional. Measure decrypt_bytes, not plaintext.size(), which also counts the
2664 // length prefix and K_id written above.
2665 if (decrypt_bytes < OpenVPNStaticKey::KEY_SIZE)
2666 return Error::DECRYPT_ERROR;
2667
2668 if (!tls_crypt_server.hmac_cmp(wkc_raw, 0, plaintext.c_data(), plaintext.size()))
2669 return Error::HMAC_ERROR;
2670
2671 // we can now remove the WKc length (and the server key ID, if present)
2672 // from the plaintext, as they are not really part of the key material
2673 plaintext.advance(sizeof(wkc_len));
2674
2675 if (proto_config.tls_crypt_v2_serverkey_id)
2676 plaintext.advance(sizeof(k_id));
2677
2678 plaintext.read(unwrapped.client_key.raw_alloc(), OpenVPNStaticKey::KEY_SIZE);
2679
2680 // what is left of the plaintext is the metadata, its type byte in front
2681 if (!plaintext.empty())
2682 unwrapped.metadata.type = plaintext.pop_front();
2683 unwrapped.metadata.payload = std::move(plaintext);
2684
2685 // virtually remove the WKc from the packet
2686 recv.set_size(orig_size - wkc_len);
2687
2688 return Error::SUCCESS;
2689 }
2690
2707 static bool strip_resent_wkc(Buffer &recv, const ProtoConfig &proto_config)
2708 {
2709 // nothing is unwrapped here, but a WKc that could not hold the client key is
2710 // malformed all the same
2711 uint16_t wkc_len;
2712 if (!trailing_wkc_len(recv,
2713 proto_config,
2715 wkc_len))
2716 return false;
2717
2718 recv.set_size(recv.size() - wkc_len);
2719
2720 return true;
2721 }
2722
2723 private:
2725 {
2726 const unsigned char *orig_data = recv.data();
2727 const size_t orig_size = recv.size();
2728
2729 // advance buffer past initial op byte
2730 recv.advance(1);
2731
2732 // get source PSID
2733 ProtoSessionID src_psid(recv);
2734
2735 // verify HMAC
2736 {
2737 recv.advance(proto.hmac_size);
2738 if (!proto.ta_hmac_recv->ovpn_hmac_cmp(orig_data,
2739 orig_size,
2743 {
2744 return false;
2745 }
2746 }
2747
2748 // verify source PSID; a session has none until accept_peer() pins one
2749 if (proto.psid_peer.defined() && !proto.psid_peer.match(src_psid))
2750 return false;
2751
2752 // read tls_auth packet ID
2753 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
2754
2755 // get current time_t
2757
2758 // verify tls_auth packet ID
2759 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
2760
2761 // make sure that our own PSID is contained in packet received from peer
2762 if (ReliableAck::ack_skip(recv))
2763 {
2764 ProtoSessionID dest_psid(recv);
2765 if (!proto.psid_self.match(dest_psid))
2766 return false;
2767 }
2768
2769 return pid_ok;
2770 }
2771
2773 {
2774 // in TLS_CRYPT_V2 mode the receive context stays unset until a WKc has been
2775 // unwrapped, so a packet reaching here before that has nothing to be judged
2776 // with -- whichever opcodes validate() lets past it
2777 if (!proto.tls_crypt_recv)
2778 return false;
2779
2780 const unsigned char *orig_data = recv.data();
2781 const size_t orig_size = recv.size();
2782
2783 // advance buffer past initial op byte
2784 recv.advance(1);
2785 // get source PSID
2786 ProtoSessionID src_psid(recv);
2787 // read tls_auth packet ID
2788 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
2789
2790 recv.advance(proto.hmac_size);
2791
2792 const size_t head_size = OPCODE_SIZE + ProtoSessionID::SIZE + PacketIDControl::size();
2793 const size_t data_offset = head_size + proto.hmac_size;
2794 if (orig_size < data_offset)
2795 return false;
2796
2797 // we need a buffer to perform the payload decryption and being this a static
2798 // function we can't use the instance member like in decapsulate_tls_crypt()
2800 proto.config->frame->prepare(Frame::DECRYPT_WORK, work);
2801
2802 // decrypt payload from 'recv' into 'work'
2803 const size_t decrypt_bytes = proto.tls_crypt_recv->decrypt(orig_data + head_size,
2804 work.data(),
2805 work.max_size(),
2806 recv.c_data(),
2807 recv.size());
2808 if (!decrypt_bytes)
2809 return false;
2810
2811 work.inc_size(decrypt_bytes);
2812
2813 // verify HMAC
2814 if (!proto.tls_crypt_recv->hmac_cmp(orig_data,
2816 work.c_data(),
2817 work.size()))
2818 return false;
2819
2820 // verify source PSID, never pin it: only accept_peer() may name our peer
2821 if (proto.psid_peer.defined() && !proto.psid_peer.match(src_psid))
2822 return false;
2823
2824 // get current time_t
2826
2827 // verify tls_auth packet ID
2828 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
2829 // make sure that our own PSID is contained in packet received from peer
2831 {
2832 ProtoSessionID dest_psid(work);
2833 if (!proto.psid_self.match(dest_psid))
2834 return false;
2835 }
2836
2837 return pid_ok;
2838 }
2839
2841 {
2842 // advance buffer past initial op byte
2843 recv.advance(1);
2844
2845 ProtoSessionID src_psid(recv);
2846 // verify source PSID; a session has none until accept_peer() pins one
2847 if (proto.psid_peer.defined() && !proto.psid_peer.match(src_psid))
2848 return false;
2849
2850 // make sure that our own PSID is contained in packet received from peer
2851 if (ReliableAck::ack_skip(recv))
2852 {
2853 ProtoSessionID dest_psid(recv);
2854 if (!proto.psid_self.match(dest_psid))
2855 return false;
2856 }
2857 return true;
2858 }
2859
2860 bool do_encrypt(BufferAllocated &buf, const bool compress_hint)
2861 {
2862 if (!is_safe_conversion<uint16_t>(proto.config->mss_fix))
2863 return false;
2864
2865 // set MSS for segments client can receive
2866 if (proto.config->mss_fix > 0)
2867 MSSFix::mssfix(buf, static_cast<uint16_t>(proto.config->mss_fix));
2868
2869 // compress packet
2870 if (compress)
2871 compress->compress(buf, compress_hint);
2872
2873 // trigger renegotiation if we hit encrypt data limit
2874 if (data_limit)
2876 return false;
2877
2878 bool pid_wrap;
2879
2880 if (enable_op32)
2881 {
2882 const std::uint32_t op32 = htonl(op32_compose(DATA_V2, key_id_, remote_peer_id));
2883
2884 static_assert(sizeof(op32) == OP_SIZE_V2, "OP_SIZE_V2 inconsistency");
2885
2886 // encrypt packet
2887 pid_wrap = crypto->encrypt(buf, (const unsigned char *)&op32);
2888
2889 // prepend op
2890 buf.prepend((const unsigned char *)&op32, sizeof(op32));
2891 }
2892 else
2893 {
2894 // encrypt packet
2895 pid_wrap = crypto->encrypt(buf, nullptr);
2896
2897 // prepend op
2899 }
2900 return pid_wrap;
2901 }
2902
2903 // cache op32 and remote_peer_id
2905 {
2906 enable_op32 = proto.config->enable_op32;
2907 remote_peer_id = proto.config->remote_peer_id;
2908 }
2909
2910 void set_state(const int newstate)
2911 {
2913 << " KeyContext[" << key_id_ << "] "
2914 << state_string(state) << " -> " << state_string(newstate));
2915 state = newstate;
2916 }
2917
2918 void set_event(const EventType current)
2919 {
2921 << " KeyContext[" << key_id_ << "] "
2922 << event_type_string(current));
2923 current_event = current;
2924 }
2925
2926 void set_event(const EventType current, const EventType next, const Time &next_time)
2927 {
2929 << " KeyContext[" << key_id_ << "] "
2930 << event_type_string(current) << " -> " << event_type_string(next)
2931 << '(' << seconds_until(next_time) << ')');
2932 current_event = current;
2933 next_event = next;
2934 next_event_time = next_time;
2935 }
2936
2937 void invalidate_callback() // called by ProtoStackBase when session is invalidated
2938 {
2942 }
2943
2944 // Trigger a renegotiation based on data flow condition such
2945 // as per-key data limit or packet ID approaching wraparound.
2947 {
2949 {
2950 OVPN_LOG_VERBOSE(proto.debug_prefix() << " SCHEDULE KEY LIMIT RENEGOTIATION");
2951
2954
2955 // If primary, renegotiate now (within a second or two).
2956 // If secondary, queue the renegotiation request until
2957 // key reaches primary.
2958 if (next_event == KEV_BECOME_PRIMARY) // secondary key before transition to primary?
2959 {
2960 // reneg request crosses over to primary,
2961 // doesn't wipe next_event (KEV_BECOME_PRIMARY)
2963 }
2964 else
2965 {
2967 }
2968 }
2969 }
2970
2971 // Handle data-limited keys such as Blowfish and other 64-bit block-size ciphers.
2972 bool data_limit_add(const DataLimit::Mode mode, const size_t size)
2973 {
2974 if (is_safe_conversion<DataLimit::size_type>(size))
2975 return false;
2976 const DataLimit::State state = data_limit->add(mode, static_cast<DataLimit::size_type>(size));
2977 if (state > DataLimit::None)
2979 return true;
2980 }
2981
2982 // Handle a DataLimit event.
2984 {
2986 << " DATA LIMIT " << DataLimit::mode_str(mode)
2987 << ' ' << DataLimit::state_str(state)
2988 << " key_id=" << key_id_);
2989
2990 // State values:
2991 // DataLimit::Green -- first packet received and decrypted.
2992 // DataLimit::Red -- data limit has been exceeded, so trigger a renegotiation.
2993 if (state == DataLimit::Red)
2995
2996 // When we are in KEV_PRIMARY_PENDING state, we must receive at least
2997 // one packet from the peer on this key before we transition to
2998 // KEV_BECOME_PRIMARY so we can transmit on it.
2999 if (next_event == KEV_PRIMARY_PENDING && data_limit->is_decrypt_green())
3000 set_event(KEV_NONE, KEV_BECOME_PRIMARY, *now + Time::Duration::seconds(1));
3001 }
3002
3003 // Should we enter KEV_PRIMARY_PENDING state? Do it if:
3004 // 1. we are a client,
3005 // 2. data limit is enabled,
3006 // 3. this is a renegotiated key in secondary context, i.e. not the first key, and
3007 // 4. no data received yet from peer on this key.
3008 bool data_limit_defer() const
3009 {
3010 return !proto.is_server()
3011 && data_limit
3012 && key_id_
3013 && !data_limit->is_decrypt_green();
3014 }
3015
3016 // General expiration set when key hits data limit threshold.
3018 {
3019 return *now + (proto.config->handshake_window * 2);
3020 }
3021
3023 {
3026 reached_active() + proto.config->become_primary);
3027 }
3028
3030 {
3031 if (*now >= next_event_time)
3032 {
3033 switch (next_event)
3034 {
3035 case KEV_BECOME_PRIMARY:
3036 if (data_limit_defer())
3038 else
3041 construct_time + proto.config->renegotiate);
3042 break;
3043 case KEV_RENEGOTIATE:
3046 break;
3047 case KEV_NEGOTIATE:
3049 break;
3052 break;
3053 case KEV_EXPIRE:
3055 break;
3056 default:
3057 break;
3058 }
3059 }
3060 }
3061
3062 void kev_error(const EventType ev, const Error::Type reason)
3063 {
3064 proto.stats->error(reason);
3065 invalidate(reason);
3066 set_event(ev);
3067 }
3068
3069 unsigned int initial_op(const bool sender, const bool tls_crypt_v2) const
3070 {
3071 if (key_id_)
3072 {
3073 return CONTROL_SOFT_RESET_V1;
3074 }
3075
3076 if (proto.is_server() == sender)
3078
3079 if (!tls_crypt_v2)
3082 }
3083
3085 {
3086 Packet pkt;
3089 raw_send(std::move(pkt));
3090 }
3091
3093 {
3094 /* The data in the early negotiation packet is structured as
3095 * TLV (type, length, value) */
3096
3097 Buffer buf = pkt.buffer();
3098 while (!buf.empty())
3099 {
3100 if (buf.size() < 4)
3101 {
3102 /* Buffer does not have enough bytes for type (uint16) and length (uint16) */
3103 return false;
3104 }
3105
3106 uint16_t type = read_uint16_length(buf);
3107 uint16_t len = read_uint16_length(buf);
3108
3109 /* TLV defines a length that is larger than the remainder in the buffer. */
3110 if (buf.size() < len)
3111 return false;
3112
3113 if (type == EARLY_NEG_FLAGS)
3114 {
3115 if (len != 2)
3116 return false;
3117 uint16_t flags = read_uint16_length(buf);
3118
3119 if (flags & EARLY_NEG_FLAG_RESEND_WKC)
3120 {
3121 resend_wkc = true;
3122 }
3123 }
3124 else
3125 {
3126 /* skip over unknown types. We rather ignore undefined TLV to
3127 * not needing to add bits initial reset message (where space
3128 * is really tight) for optional features. */
3129 buf.advance(len);
3130 }
3131 }
3132 return true;
3133 }
3134
3135
3136 void raw_recv(Packet &&raw_pkt) // called by ProtoStackBase
3137 {
3138 if (raw_pkt.opcode == initial_op(false, proto.tls_wrap_mode == TLS_CRYPT_V2))
3139 {
3140 switch (state)
3141 {
3142 case C_WAIT_RESET:
3144 if (!parse_early_negotiation(raw_pkt))
3145 {
3147 }
3148 break;
3149 case S_WAIT_RESET:
3150 send_reset();
3152 break;
3153 }
3154 }
3155 }
3156
3157 void app_recv(BufferPtr &&to_app_buf) // called by ProtoStackBase
3158 {
3159 app_recv_buf.put(std::move(to_app_buf));
3161 throw proto_error("app_recv: received control message is too large");
3163 switch (state)
3164 {
3165 case C_WAIT_AUTH:
3166 if (recv_auth_complete(bcc))
3167 {
3168 recv_auth(bcc.get());
3170 }
3171 break;
3172 case S_WAIT_AUTH:
3173 if (recv_auth_complete(bcc))
3174 {
3175 recv_auth(bcc.get());
3176 send_auth();
3178 }
3179 break;
3180 case S_WAIT_AUTH_ACK:
3181 // rare case where client receives auth, goes ACTIVE,
3182 // but the ACK response is dropped
3183 case ACTIVE:
3184 if (bcc.advance_to_null()) // does composed buffer contain terminating null char?
3185 proto.app_recv(key_id_, bcc.get());
3186 break;
3187 }
3188 }
3189
3190 void net_send(const Packet &net_pkt, const Base::NetSendType nstype) // called by ProtoStackBase
3191 {
3192 if (!is_reliable || nstype != Base::NET_SEND_RETRANSMIT) // retransmit packets on UDP only, not TCP
3193 proto.net_send(key_id_, net_pkt);
3194 }
3195
3197 {
3199 {
3200 switch (state)
3201 {
3202 case C_WAIT_RESET_ACK:
3204 send_auth();
3206 break;
3207 case S_WAIT_RESET_ACK:
3210 break;
3211 case C_WAIT_AUTH_ACK:
3212 active();
3214 break;
3215 case S_WAIT_AUTH_ACK:
3216 active();
3218 break;
3219 }
3220 }
3221 }
3222
3224 {
3225 auto buf = BufferAllocatedRc::Create();
3226 proto.config->frame->prepare(Frame::WRITE_SSL_CLEARTEXT, *buf);
3227 buf->write(proto_context_private::auth_prefix, sizeof(proto_context_private::auth_prefix));
3229 tlsprf->self_write(*buf);
3230 const std::string options = proto.config->options_string();
3231 write_auth_string(options, *buf);
3232 if (!proto.is_server())
3233 {
3234 OVPN_LOG_INFO("Tunnel Options:" << options);
3235 buf->add_flags(BufAllocFlags::DESTRUCT_ZERO);
3236 if (proto.config->xmit_creds)
3237 proto.client_auth(*buf);
3238 else
3239 {
3240 write_empty_string(*buf); // username
3241 write_empty_string(*buf); // password
3242 }
3243 const std::string peer_info = proto.config->peer_info_string(proto.proto_callback->supports_epoch_data());
3244 write_auth_string(peer_info, *buf);
3245 }
3246 app_send_validate(std::move(buf));
3247 dirty = true;
3248 }
3249
3251 {
3252 const unsigned char *buf_pre = buf->read_alloc(sizeof(proto_context_private::auth_prefix));
3253 if (std::memcmp(buf_pre, proto_context_private::auth_prefix, sizeof(proto_context_private::auth_prefix)))
3254 throw proto_error("bad_auth_prefix");
3255 tlsprf->peer_read(*buf);
3256 const std::string options = read_auth_string<std::string>(*buf);
3257 if (proto.is_server())
3258 {
3259 const std::string username = read_auth_string<std::string>(*buf);
3260 const SafeString password = read_auth_string<SafeString>(*buf);
3261 const std::string peer_info = read_auth_string<std::string>(*buf);
3262 proto.proto_callback->server_auth(username, password, peer_info, Base::auth_cert());
3263 }
3264 }
3265
3266 // return true if complete recv_auth message is contained in buffer
3268 {
3269 if (!bc.advance(sizeof(proto_context_private::auth_prefix)))
3270 return false;
3271 if (!tlsprf->peer_read_complete(bc))
3272 return false;
3273 if (!bc.advance_string()) // options
3274 return false;
3275 if (proto.is_server())
3276 {
3277 if (!bc.advance_string()) // username
3278 return false;
3279 if (!bc.advance_string()) // password
3280 return false;
3281 if (!bc.advance_string()) // peer_info
3282 return false;
3283 }
3284 return true;
3285 }
3286
3287 void active()
3288 {
3289 OVPN_LOG_INFO("TLS Handshake: " << Base::ssl_handshake_details());
3290
3291 /* Our internal state machine only decides after push request what protocol
3292 * options we want to use. Therefore we also have to postpone data key
3293 * generation until this happens, create a empty DataChannelKey as
3294 * placeholder */
3295 data_channel_key.reset(new DataChannelKey());
3296 if (!proto.dc_deferred)
3298
3299 while (!app_pre_write_queue.empty())
3300 {
3301 app_send_validate(std::move(app_pre_write_queue.front()));
3302 app_pre_write_queue.pop_front();
3303 dirty = true;
3304 }
3307 active_event();
3308 }
3309
3310 void prepend_dest_psid_and_acks(Buffer &buf, unsigned int opcode)
3311 {
3312 // if sending ACKs, prepend dest PSID
3313 if (xmit_acks.acks_ready())
3314 {
3315 if (proto.psid_peer.defined())
3316 proto.psid_peer.prepend(buf);
3317 else
3318 {
3320 throw proto_error("peer_psid_undef");
3321 }
3322 }
3323
3324 // prepend ACKs for messages received from peer
3325 xmit_acks.prepend(buf, opcode == ACK_V1);
3326 }
3327
3328 bool verify_src_psid(const ProtoSessionID &src_psid)
3329 {
3330 if (proto.psid_peer.defined() && !proto.psid_peer.match(src_psid))
3331 {
3333 if (proto.is_tcp())
3335 return false;
3336 }
3337 return true;
3338 }
3339
3348 void accept_peer(const ProtoSessionID &src_psid)
3349 {
3350 pkt_from_peer = true;
3351 if (!proto.psid_peer.defined())
3352 proto.psid_peer = src_psid;
3353 }
3354
3356 {
3357 ProtoSessionID dest_psid(buf);
3358 if (!proto.psid_self.match(dest_psid))
3359 {
3361 if (proto.is_tcp())
3363 return false;
3364 }
3365 return true;
3366 }
3367
3368 void gen_head_tls_auth(const unsigned int opcode, Buffer &buf)
3369 {
3370 // write tls-auth packet ID
3372
3373 // make space for tls-auth HMAC
3375
3376 // write source PSID
3377 proto.psid_self.prepend(buf);
3378
3379 // write opcode
3380 buf.push_front(op_compose(opcode, key_id_));
3381
3382 // write hmac
3384 buf.size(),
3388 }
3389
3390 void gen_head_tls_crypt(const unsigned int opcode, BufferAllocated &buf)
3391 {
3392 // The send context stays unset until a WKc has been unwrapped, and decapsulate()
3393 // can put a session into TLS_CRYPT_V2 mode before that ever happens. Giving up
3394 // this session is caught per session, where the dereference below would not be.
3395 if (!proto.tls_crypt_send)
3396 throw proto_error("gen_head_tls_crypt: no tls-crypt send context");
3397
3398 // in 'work' we store all the fields that are not supposed to be encrypted
3399 proto.config->frame->prepare(Frame::ENCRYPT_WORK, work);
3400 // make space for HMAC
3402 // write tls-crypt packet ID
3404 // write source PSID
3406 // write opcode
3408
3409 // compute HMAC using header fields (from 'work') and plaintext
3410 // payload (from 'buf')
3413 buf.c_data(),
3414 buf.size());
3415
3416 const size_t data_offset = TLSCryptContext::hmac_offset + proto.hmac_size;
3417
3418 // encrypt the content of 'buf' (packet payload) into 'work'
3419 const size_t encrypt_bytes = proto.tls_crypt_send->encrypt(work.c_data() + TLSCryptContext::hmac_offset,
3420 work.data() + data_offset,
3421 work.max_size() - data_offset,
3422 buf.c_data(),
3423 buf.size());
3424 if (!encrypt_bytes)
3425 {
3426 buf.reset_size();
3427 return;
3428 }
3429 work.inc_size(encrypt_bytes);
3430
3431 // append WKc to wrapped packet for tls-crypt-v2
3434
3435 // 'work' now contains the complete packet ready to go. swap it with 'buf'
3436 buf.swap(work);
3437 }
3438
3439 void gen_head_tls_plain(const unsigned int opcode, Buffer &buf)
3440 {
3441 // write source PSID
3442 proto.psid_self.prepend(buf);
3443 // write opcode
3444 buf.push_front(op_compose(opcode, key_id_));
3445 }
3446
3447 void gen_head(const unsigned int opcode, BufferAllocated &buf)
3448 {
3449 switch (proto.tls_wrap_mode)
3450 {
3451 case TLS_AUTH:
3452 gen_head_tls_auth(opcode, buf);
3453 break;
3454 case TLS_CRYPT:
3455 case TLS_CRYPT_V2:
3456 gen_head_tls_crypt(opcode, buf);
3457 break;
3458 case TLS_PLAIN:
3459 gen_head_tls_plain(opcode, buf);
3460 break;
3461 }
3462 }
3463
3464 // True if the control packet with the given reliable-layer id will
3465 // carry the tls-crypt-v2 wrapped client key (WKc), appended after the
3466 // payload during encapsulation. Used both to select the CONTROL_WKC_V1
3467 // opcode and to reserve room for the WKc when filling the packet with
3468 // ciphertext.
3470 {
3471 return id == 1 && resend_wkc && proto.tls_wrap_mode == TLS_CRYPT_V2;
3472 }
3473
3474 // Worst-case number of bytes this control packet will carry around
3475 // the SSL ciphertext once encapsulated and wrapped: the tls wrap
3476 // header (opcode, session id, packet id, hmac) plus the reliable
3477 // layer message id and the largest possible piggybacked ACK block.
3478 // ACKs must be accounted for at their maximum, since retransmits
3479 // re-run encapsulate() with whatever ACKs are pending at that time.
3481 {
3482 size_t overhead = OPCODE_SIZE + ProtoSessionID::SIZE + proto.hmac_size;
3484 overhead += PacketIDControl::size();
3485 // reliable layer message id
3486 overhead += sizeof(id_t);
3487 // worst-case ACK block: count byte + ACK ids + dest session id
3488 overhead += 1 + sizeof(id_t) * ReliableAck::maximum_acks_control_v1
3490 return overhead;
3491 }
3492
3493 // Maximum amount of SSL ciphertext that may be placed into the control
3494 // packet with the given id, such that the fully wrapped packet does
3495 // not exceed the mssfix_ctrl limit. For the packet that also carries
3496 // the WKc, the WKc length is subtracted as well. Called by
3497 // ProtoStackBase.
3499 {
3500 size_t capacity = (*proto.config->frame)[Frame::READ_BIO_MEMQ_STREAM].payload();
3501
3502 // never let the fully wrapped packet exceed mssfix_ctrl
3503 size_t wire_budget = proto.config->mssfix_ctrl;
3504 wire_budget -= std::min(wire_budget, control_channel_wrap_overhead());
3505 capacity = std::min(capacity, wire_budget);
3506
3507 if (packet_carries_wkc(id) && proto.config->wkc.defined())
3508 {
3509 // clamp: a large WKc could exceed a small budget (mssfix-ctrl
3510 // can go as low as 256); never let the subtraction wrap. A
3511 // zero capacity yields a CONTROL_WKC_V1 packet carrying the
3512 // WKc alone, with all ciphertext deferred to the following
3513 // messages.
3514 capacity -= std::min(capacity, proto.config->wkc.size());
3515 }
3516 return capacity;
3517 }
3518
3519 void encapsulate(id_t id, Packet &pkt) // called by ProtoStackBase
3520 {
3521 BufferAllocated &buf = *pkt.buf;
3522
3523 // prepend message sequence number
3524 ReliableAck::prepend_id(buf, id);
3525
3526 // prepend dest PSID and ACKs to reply to peer
3528
3529 // generate message head
3530 int opcode = pkt.opcode;
3531 if (packet_carries_wkc(id))
3532 {
3533 opcode = CONTROL_WKC_V1;
3534 }
3535
3536 gen_head(opcode, buf);
3537 }
3538
3539 void generate_ack(Packet &pkt) // called by ProtoStackBase
3540 {
3541 BufferAllocated &buf = *pkt.buf;
3542
3543 // prepend dest PSID and ACKs to reply to peer
3545
3546 gen_head(ACK_V1, buf);
3547 }
3548
3550 {
3551 Buffer &recv = *pkt.buf;
3552
3553 // update our last-packet-received time
3555
3556 // verify source PSID
3557 if (!verify_src_psid(src_psid))
3558 return false;
3559
3560 // get current time_t
3562 // verify tls_auth/crypt packet ID
3563 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
3564
3565 // process ACKs sent by peer (if packet ID check failed,
3566 // read the ACK IDs, but don't modify the rel_send object).
3567 if (ReliableAck::ack(rel_send, recv, pid_ok))
3568 {
3569 // make sure that our own PSID is contained in packet received from peer
3570 if (!verify_dest_psid(recv))
3571 return false;
3572 }
3573
3574 accept_peer(src_psid);
3575
3576 // for CONTROL packets only, not ACK
3577 if (pkt.opcode != ACK_V1)
3578 {
3579 // get message sequence number
3580 const id_t id = ReliableAck::read_id(recv);
3581
3582 if (pid_ok)
3583 {
3584 // try to push message into reliable receive object
3585 const unsigned int rflags = rel_recv.receive(pkt, id);
3586
3587 // should we ACK packet back to sender?
3588 if (rflags & ReliableRecv::ACK_TO_SENDER)
3589 xmit_acks.push_back(id); // ACK packet to sender
3590
3591 // was packet accepted by reliable receive object?
3592 if (rflags & ReliableRecv::IN_WINDOW)
3593 {
3594 // remember tls_auth packet ID so that it can't be replayed
3595 proto.ta_pid_recv.test_add(pid, t, true);
3596 return true;
3597 }
3598 }
3599 else // treat as replay
3600 {
3602 if (pid.is_valid())
3603 // even replayed packets must be ACKed or protocol could deadlock
3604 xmit_acks.push_back(id);
3605 }
3606 }
3607 else
3608 {
3609 if (pid_ok)
3610 // remember tls_auth packet ID of ACK packet to prevent replay
3611 proto.ta_pid_recv.test_add(pid, t, true);
3612 else
3614 }
3615 return false;
3616 }
3617
3619 {
3620 Buffer &recv = *pkt.buf;
3621 const unsigned char *orig_data = recv.data();
3622 const size_t orig_size = recv.size();
3623
3624 // advance buffer past initial op byte
3625 recv.advance(1);
3626
3627 // get source PSID
3628 ProtoSessionID src_psid(recv);
3629
3630 // verify HMAC
3631 {
3632 recv.advance(proto.hmac_size);
3633 if (!proto.ta_hmac_recv->ovpn_hmac_cmp(orig_data,
3634 orig_size,
3638 {
3640 if (proto.is_tcp())
3642 return false;
3643 }
3644 }
3645
3646 // read tls_auth packet ID
3647 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
3648
3649 return decapsulate_post_process(pkt, src_psid, pid);
3650 }
3651
3653 {
3654 // in TLS_CRYPT_V2 mode the receive context stays unset until a WKc has been
3655 // unwrapped, so any other opcode reaching us before that has no key to be
3656 // decrypted with
3657 if (!proto.tls_crypt_recv)
3658 {
3660 if (proto.is_tcp())
3662 return false;
3663 }
3664
3665 auto &recv = *pkt.buf;
3666 const unsigned char *orig_data = recv.data();
3667 const size_t orig_size = recv.size();
3668
3669 // advance buffer past initial op byte
3670 recv.advance(1);
3671 // get source PSID
3672 ProtoSessionID src_psid(recv);
3673 // get tls-crypt packet ID
3674 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
3675 // skip the hmac
3676 recv.advance(proto.hmac_size);
3677
3678 const size_t data_offset = TLSCryptContext::hmac_offset + proto.hmac_size;
3679 if (orig_size < data_offset)
3680 return false;
3681
3682 // decrypt payload
3683 proto.config->frame->prepare(Frame::DECRYPT_WORK, work);
3684
3685 const size_t decrypt_bytes = proto.tls_crypt_recv->decrypt(orig_data + TLSCryptContext::hmac_offset,
3686 work.data(),
3687 work.max_size(),
3688 recv.c_data(),
3689 recv.size());
3690 if (!decrypt_bytes)
3691 {
3693 if (proto.is_tcp())
3695 return false;
3696 }
3697
3698 work.inc_size(decrypt_bytes);
3699
3700 // verify HMAC
3701 if (!proto.tls_crypt_recv->hmac_cmp(orig_data,
3703 work.c_data(),
3704 work.size()))
3705 {
3707 if (proto.is_tcp())
3709 return false;
3710 }
3711
3712 // move the decrypted payload to 'recv', so that the processing of the
3713 // packet can continue
3714 recv.swap(work);
3715
3716 return decapsulate_post_process(pkt, src_psid, pid);
3717 }
3718
3720 {
3721 Buffer &recv = *pkt.buf;
3722
3723 // update our last-packet-received time
3725
3726 // advance buffer past initial op byte
3727 recv.advance(1);
3728
3729 // verify source PSID
3730 ProtoSessionID src_psid(recv);
3731 if (!verify_src_psid(src_psid))
3732 return false;
3733
3734 // process ACKs sent by peer
3735 if (ReliableAck::ack(rel_send, recv, true))
3736 {
3737 // make sure that our own PSID is in packet received from peer
3738 if (!verify_dest_psid(recv))
3739 return false;
3740 }
3741
3742 accept_peer(src_psid);
3743
3744 // for CONTROL packets only, not ACK
3745 if (pkt.opcode != ACK_V1)
3746 {
3747 // get message sequence number
3748 const id_t id = ReliableAck::read_id(recv);
3749
3750 // try to push message into reliable receive object
3751 const unsigned int rflags = rel_recv.receive(pkt, id);
3752
3753 // should we ACK packet back to sender?
3754 if (rflags & ReliableRecv::ACK_TO_SENDER)
3755 xmit_acks.push_back(id); // ACK packet to sender
3756
3757 // was packet accepted by reliable receive object?
3758 if (rflags & ReliableRecv::IN_WINDOW)
3759 return true;
3760 }
3761 return false;
3762 }
3763
3771 bool tls_crypt_v2_wanted(const Packet &pkt) const
3772 {
3774 }
3775
3776 bool decapsulate(Packet &pkt) // called by ProtoStackBase
3777 {
3778 const bool detect_tls_crypt_v2 = tls_crypt_v2_wanted(pkt);
3779 const size_t tls_auth_hmac_size = proto.hmac_size;
3780 const bool had_client_key = bool(proto.tls_crypt_recv);
3781 bool authenticated = false;
3782
3783 pkt_from_peer = false;
3784
3785 try
3786 {
3787 if (detect_tls_crypt_v2)
3788 {
3789 // Create the server context the client's WKc is unwrapped with,
3790 // keyed only at unwrap time, when the WKc names its key. tls-crypt
3791 // session key setup is postponed to reception of the WKc too.
3793
3795 proto.hmac_size = proto.config->tls_crypt_context->digest_size();
3796
3797 // init tls_crypt packet ID; the send half waits until the packet has
3798 // earned it, below, since putting the previous id back is not possible
3799 proto.ta_pid_recv.init("SSL-CC", 0, proto.stats);
3800 }
3801
3802 authenticated = decapsulate_by_wrap_mode(pkt);
3803 }
3804 catch (const BufferException &)
3805 {
3807 if (proto.is_tcp())
3809 }
3810
3811 if (!pkt_from_peer && !had_client_key && proto.tls_crypt_recv)
3812 {
3813 // Drop a packet that's not ours.
3817 }
3818
3819 if (detect_tls_crypt_v2)
3820 {
3821 if (!pkt_from_peer)
3822 {
3823 // Not our peer's packet, so leave the session as tls-auth had it. The
3824 // receive packet id needs no undoing: reset() initialises it the same
3825 // way and nothing of our peer's has moved it.
3827 proto.hmac_size = tls_auth_hmac_size;
3828 }
3829 else
3830 {
3834 }
3835 }
3836
3837 return authenticated;
3838 }
3839
3849 {
3850 if (!proto.config->tls_crypt_metadata_factory)
3851 return true;
3852
3853 const TLSCryptMetadata::Ptr recorder = proto.config->tls_crypt_metadata_factory->new_obj();
3854
3855 if (recorder->verify(metadata.type, metadata.payload))
3856 return true;
3857
3859
3860 // Unconditional, unlike the drops above: this packet authenticated, so the
3861 // session ended is the one the record belongs to. The key stays -- the
3862 // decapsulation left an ACK to be wrapped.
3864 return false;
3865 }
3866
3880 {
3881 switch (proto.tls_wrap_mode)
3882 {
3883 case TLS_AUTH:
3884 return decapsulate_tls_auth(pkt);
3885 case TLS_CRYPT_V2:
3886 // The client key comes from this packet and nowhere else; later copies carry
3887 // the WKc too and only need it stripped.
3889 {
3890 if (!proto.tls_crypt_recv)
3891 {
3893 {
3895 << " DROPPING WKc WITH NO SERVER CONTEXT");
3896 return false;
3897 }
3898
3899 UnwrappedWkc unwrapped;
3900 const Error::Type unwrap_wkc_result = unwrap_tls_crypt_wkc(*pkt.buf,
3901 *proto.config,
3903 unwrapped);
3904 switch (unwrap_wkc_result)
3905 {
3907 case Error::HMAC_ERROR:
3908 proto.stats->error(unwrap_wkc_result);
3909 if (proto.is_tcp())
3910 invalidate(unwrap_wkc_result);
3911 return false;
3912 case Error::SUCCESS:
3913 break;
3914 default:
3915 return false;
3916 }
3917
3918 // The WKc holds up under the server key, so the client key inside it
3919 // is one this server issued. Key the session with it.
3920 proto.tls_crypt_client_key = std::move(unwrapped.client_key);
3922
3923 // That says the WKc is ours, not that the sender holds the Kc inside:
3924 // a replayed one unwraps just as well. Only the frame verifying under
3925 // that Kc says so, hence decapsulate before judging the record.
3926 const bool authenticated = decapsulate_tls_crypt(pkt);
3927
3928 if (pkt_from_peer && !verify_wkc_metadata(unwrapped.metadata))
3929 return false;
3930
3931 return authenticated;
3932 }
3933 else if (!strip_resent_wkc(*pkt.buf, *proto.config))
3934 {
3936 if (proto.is_tcp())
3938 return false;
3939 }
3940 }
3941 // now that the tls-crypt contexts have been initialized it is
3942 // possible to proceed with the standard tls-crypt decapsulation
3943 [[fallthrough]];
3944 case TLS_CRYPT:
3945 return decapsulate_tls_crypt(pkt);
3946 case TLS_PLAIN:
3947 return decapsulate_tls_plain(pkt);
3948 }
3949 return false;
3950 }
3951
3952 // for debugging
3953 static const char *state_string(const int s)
3954 {
3955 switch (s)
3956 {
3957 case C_WAIT_RESET_ACK:
3958 return "C_WAIT_RESET_ACK";
3959 case C_WAIT_AUTH_ACK:
3960 return "C_WAIT_AUTH_ACK";
3961 case S_WAIT_RESET_ACK:
3962 return "S_WAIT_RESET_ACK";
3963 case S_WAIT_AUTH_ACK:
3964 return "S_WAIT_AUTH_ACK";
3965 case C_INITIAL:
3966 return "C_INITIAL";
3967 case C_WAIT_RESET:
3968 return "C_WAIT_RESET";
3969 case C_WAIT_AUTH:
3970 return "C_WAIT_AUTH";
3971 case S_INITIAL:
3972 return "S_INITIAL";
3973 case S_WAIT_RESET:
3974 return "S_WAIT_RESET";
3975 case S_WAIT_AUTH:
3976 return "S_WAIT_AUTH";
3977 case ACTIVE:
3978 return "ACTIVE";
3979 default:
3980 return "STATE_UNDEF";
3981 }
3982 }
3983
3984 // for debugging
3985 int seconds_until(const Time &next_time)
3986 {
3987 Time::Duration d = next_time - *now;
3988 if (d.is_infinite())
3989 return -1;
3990 return numeric_cast<int>(d.to_seconds());
3991 }
3992
3993 // BEGIN KeyContext data members
3994
3997 unsigned int key_id_;
3998 unsigned int crypto_flags;
3999 int remote_peer_id; // -1 to disable
4001 /* early negotiation enabled resending of wrapped tls-crypt-v2 client key
4002 * with third packet of the three-way handshake
4003 */
4004 bool resend_wkc = false;
4006 bool pkt_from_peer = false;
4007 bool dirty;
4018 std::deque<BufferPtr> app_pre_write_queue;
4019 std::unique_ptr<DataChannelKey> data_channel_key;
4021 std::unique_ptr<DataLimit> data_limit;
4023
4024 // static member used by validate_tls_crypt()
4026 };
4027
4029 {
4030 public:
4031 PsidCookieHelper(unsigned int op_field)
4032 : op_code_(opcode_extract(op_field)), key_id_(key_id_extract(op_field))
4033 {
4034 }
4035
4037 {
4038 return key_id_ == 0 && (op_code_ == CONTROL_HARD_RESET_CLIENT_V2 || op_code_ == CONTROL_HARD_RESET_CLIENT_V3);
4039 }
4040
4042 bool is_tls_crypt_v2() const noexcept
4043 {
4044 return op_code_ == CONTROL_HARD_RESET_CLIENT_V3 || op_code_ == CONTROL_WKC_V1;
4045 }
4046
4048 bool supports_early_negotiation(const PacketIDControl &pidc) const noexcept
4049 {
4050 return (pidc.id & EARLY_NEG_MASK) == EARLY_NEG_START;
4051 }
4052
4055 {
4056 return key_id_ == 0 && (op_code_ == CONTROL_V1 || op_code_ == ACK_V1);
4057 }
4058
4061 {
4062 return key_id_ == 0 && op_code_ == CONTROL_WKC_V1;
4063 }
4064
4066 bool is_ack_v1() const
4067 {
4068 return op_code_ == ACK_V1;
4069 }
4070
4072 static void prepend_TLV(Buffer &payload)
4073 {
4074 // The only supported TLV payload for now.
4075 const uint16_t type = htons(EARLY_NEG_FLAGS);
4076 const uint16_t len = htons(sizeof(uint16_t));
4077 const uint16_t flags = htons(EARLY_NEG_FLAG_RESEND_WKC);
4078
4079 payload.prepend(&flags, sizeof(flags));
4080 payload.prepend(&len, sizeof(len));
4081 payload.prepend(&type, sizeof(type));
4082 }
4083
4084 static unsigned char get_server_hard_reset_opfield()
4085 {
4086 return op_compose(CONTROL_HARD_RESET_SERVER_V2, 0);
4087 }
4088
4089 private:
4090 const unsigned int op_code_;
4091 const unsigned int key_id_;
4092 };
4093
4095 {
4096 public:
4097 IvProtoHelper(const OptionList &peer_info)
4098 : proto_field_(peer_info.get_num<unsigned int>("IV_PROTO", 1, 0))
4099 {
4100 }
4101
4103 {
4104 return proto_field_ & iv_proto_flag::IV_PROTO_TLS_KEY_EXPORT;
4105 }
4106
4108 {
4109 return proto_field_ & iv_proto_flag::IV_PROTO_AUTH_FAIL_TEMP;
4110 }
4111
4113 {
4114 return proto_field_ & iv_proto_flag::IV_PROTO_DATA_V2;
4115 }
4116
4118 {
4119 return proto_field_ & iv_proto_flag::IV_PROTO_AUTH_PENDING_KW;
4120 }
4121
4123 {
4124 return proto_field_ & iv_proto_flag::IV_PROTO_PUSH_UPDATE;
4125 }
4126
4128 {
4129 return proto_field_ & iv_proto_flag::IV_PROTO_REQUEST_PUSH;
4130 }
4131
4134 {
4135 return proto_field_ & iv_proto_flag::IV_PROTO_CC_EXIT_NOTIFY;
4136 }
4137
4140 {
4141 return proto_field_ & iv_proto_flag::IV_PROTO_DYN_TLS_CRYPT;
4142 }
4143
4146 {
4147 return proto_field_ & iv_proto_flag::IV_PROTO_DNS_OPTION_V2;
4148 }
4149
4150 private:
4151 unsigned int proto_field_;
4152 };
4153
4154 class TLSWrapPreValidate : public RC<thread_unsafe_refcount>
4155 {
4156 public:
4158
4159 virtual bool validate(const BufferAllocated &net_buf) = 0;
4160 };
4161
4162 // Validate the integrity of a packet, only considering tls-auth HMAC.
4164 {
4165 public:
4166 OPENVPN_SIMPLE_EXCEPTION(tls_auth_pre_validate);
4167
4168 TLSAuthPreValidate(const ProtoConfig &c, const bool server)
4169 {
4170 if (!c.tls_auth_enabled())
4171 throw tls_auth_pre_validate();
4172
4173 // save hard reset op we expect to receive from peer
4174 reset_op = server ? CONTROL_HARD_RESET_CLIENT_V2 : CONTROL_HARD_RESET_SERVER_V2;
4175
4176 // init OvpnHMACInstance
4177 ta_hmac_recv = c.tls_auth_context->new_obj();
4178
4179 // init tls_auth hmac
4180 if (c.key_direction >= 0)
4181 {
4182 // key-direction is 0 or 1
4183 const unsigned int key_dir = c.key_direction
4184 ? OpenVPNStaticKey::INVERSE
4185 : OpenVPNStaticKey::NORMAL;
4186 ta_hmac_recv->init(c.tls_auth_key.slice(OpenVPNStaticKey::HMAC | OpenVPNStaticKey::DECRYPT | key_dir));
4187 }
4188 else
4189 {
4190 // key-direction bidirectional mode
4191 ta_hmac_recv->init(c.tls_auth_key.slice(OpenVPNStaticKey::HMAC));
4192 }
4193 }
4194
4195 bool validate(const BufferAllocated &net_buf)
4196 {
4197 try
4198 {
4199 if (net_buf.empty())
4200 return false;
4201
4202 const unsigned int op = net_buf[0];
4203 if (opcode_extract(op) != reset_op || key_id_extract(op) != 0)
4204 return false;
4205
4206 return ta_hmac_recv->ovpn_hmac_cmp(net_buf.c_data(),
4207 net_buf.size(),
4208 OPCODE_SIZE + ProtoSessionID::SIZE,
4209 ta_hmac_recv->output_size(),
4210 PacketIDControl::size());
4211 }
4212 catch (const BufferException &)
4213 {
4214 }
4215
4216 return false;
4217 }
4218
4219 private:
4221 unsigned int reset_op;
4222 };
4223
4225 {
4226 public:
4227 OPENVPN_SIMPLE_EXCEPTION(tls_crypt_pre_validate);
4228
4229 TLSCryptPreValidate(const ProtoConfig &c, const bool server)
4230 {
4231 const bool tls_crypt_v2_enabled = c.tls_crypt_v2_enabled();
4232
4233 if (!c.tls_crypt_enabled() && !tls_crypt_v2_enabled)
4234 throw tls_crypt_pre_validate();
4235
4236 // save hard reset op we expect to receive from peer
4237 reset_op = CONTROL_HARD_RESET_SERVER_V2;
4238
4239 if (server)
4240 {
4241 // We can't pre-validate because we haven't extracted the server key from
4242 // the server key ID that's present in the client key yet.
4243 if (tls_crypt_v2_enabled && c.tls_crypt_v2_serverkey_id)
4244 {
4245 disabled = true;
4246 return;
4247 }
4248
4249 reset_op = tls_crypt_v2_enabled
4250 ? CONTROL_HARD_RESET_CLIENT_V3
4251 : CONTROL_HARD_RESET_CLIENT_V2;
4252 }
4253
4254 tls_crypt_recv = c.tls_crypt_context->new_obj_recv();
4255
4256 // static direction assignment - not user configurable
4257 const unsigned int key_dir = server ? OpenVPNStaticKey::NORMAL : OpenVPNStaticKey::INVERSE;
4258 tls_crypt_recv->init(c.ssl_factory->libctx(),
4259 c.tls_crypt_key.slice(OpenVPNStaticKey::HMAC | OpenVPNStaticKey::DECRYPT | key_dir),
4260 c.tls_crypt_key.slice(OpenVPNStaticKey::CIPHER | OpenVPNStaticKey::DECRYPT | key_dir));
4261
4262 // needed to create the decrypt buffer during validation
4263 frame = c.frame;
4264 }
4265
4266 bool validate(const BufferAllocated &net_buf)
4267 {
4268 if (disabled)
4269 return true;
4270
4271 try
4272 {
4273 if (net_buf.empty())
4274 return false;
4275
4276 const unsigned int op = net_buf[0];
4277 if (opcode_extract(op) != reset_op || key_id_extract(op) != 0)
4278 return false;
4279
4280 const size_t data_offset = TLSCryptContext::hmac_offset + tls_crypt_recv->output_hmac_size();
4281 if (net_buf.size() < data_offset)
4282 return false;
4283
4284 frame->prepare(Frame::DECRYPT_WORK, work);
4285
4286 // decrypt payload from 'net_buf' into 'work'
4287 const size_t decrypt_bytes = tls_crypt_recv->decrypt(net_buf.c_data() + TLSCryptContext::hmac_offset,
4288 work.data(),
4289 work.max_size(),
4290 net_buf.c_data() + data_offset,
4291 net_buf.size() - data_offset);
4292 if (!decrypt_bytes)
4293 return false;
4294
4295 work.inc_size(decrypt_bytes);
4296
4297 // verify HMAC
4298 return tls_crypt_recv->hmac_cmp(net_buf.c_data(),
4299 TLSCryptContext::hmac_offset,
4300 work.data(),
4301 work.size());
4302 }
4303 catch (const BufferException &)
4304 {
4305 }
4306 return false;
4307 }
4308
4309 protected:
4310 unsigned int reset_op;
4311
4312 private:
4316 bool disabled = false;
4317 };
4318
4319 OPENVPN_SIMPLE_EXCEPTION(select_key_context_error);
4320
4322 const ProtoConfig::Ptr &config_arg, // configuration
4323 const SessionStats::Ptr &stats_arg) // error stats
4324 : proto_callback(cb_arg),
4325 config(config_arg),
4326 stats(stats_arg),
4327 mode_(config_arg->ssl_factory->mode()),
4328 n_key_ids(0),
4329 now_(config_arg->now)
4330 {
4332 }
4333
4335 {
4336 // Prefer TLS auth as the default if both TLS crypt V2 and TLS auth
4337 // are enabled.
4338 if (c.tls_crypt_v2_enabled() && !c.tls_auth_enabled())
4339 {
4341
4342 // get HMAC size from Digest object
4344
4345 return;
4346 }
4347
4348 if (c.tls_crypt_enabled() && !c.tls_auth_enabled())
4349 {
4351
4352 // get HMAC size from Digest object
4354
4355 return;
4356 }
4357
4358 if (c.tls_auth_enabled())
4359 {
4361
4362 // get HMAC size from Digest object
4364
4365 return;
4366 }
4367
4369 hmac_size = 0;
4370 }
4371
4372 uint32_t get_tls_warnings() const
4373 {
4374 if (primary)
4375 return primary->get_tls_warnings();
4376
4377 OPENVPN_LOG("TLS: primary key context uninitialized. Can't retrieve TLS warnings");
4378 return 0;
4379 }
4380
4381 bool uses_bs64_cipher() const
4382 {
4383 return is_bs64_cipher(conf().dc.cipher());
4384 }
4385
4387 {
4390
4391 // static direction assignment - not user configurable
4393
4400 }
4401
4403 {
4404 // Both call sites fire on primary->key_id() == 0, which a duplicated -- or
4405 // corrupted, then retransmitted -- soft reset satisfies twice. The switch below
4406 // reads tls_wrap_mode, which this function ends by overwriting, so a second
4407 // pass would land on TLS_CRYPT and mix c.tls_crypt_key: the wrong key, and on
4408 // a tls_crypt_v2_serverkey_id server not a defined one. There is nothing new
4409 // to derive anyway -- same TLS session, same exported material.
4411 return;
4412
4413 OpenVPNStaticKey dyn_key;
4414 key_ctx->export_key_material(dyn_key, "EXPORTER-OpenVPN-dynamic-tls-crypt");
4415
4416 // The mode this session settled on, not what the config allows. A server holding
4417 // both a tls-auth key and tls-crypt-v2 starts every session as TLS_AUTH and only
4418 // decapsulate() converts it, so asking the config here would have such a server
4419 // mix tls_auth_key while its converted tls-crypt-v2 client mixes Kc.
4420 switch (tls_wrap_mode)
4421 {
4422 case TLS_AUTH:
4423 dyn_key.XOR(c.tls_auth_key);
4424 break;
4425 case TLS_CRYPT_V2:
4426 // Kc, this session's own: c.tls_crypt_key is the client's Kc on a client but the
4427 // server key on a server, and with tls_crypt_v2_serverkey_id not even defined, so
4428 // mixing it in would have the two ends derive different keys.
4430 throw proto_error("dynamic tls-crypt with no tls-crypt-v2 client key");
4431 dyn_key.XOR(tls_crypt_client_key);
4432 break;
4433 case TLS_CRYPT:
4434 dyn_key.XOR(c.tls_crypt_key);
4435 break;
4436 case TLS_PLAIN:
4437 break;
4438 }
4439
4441
4442 // get HMAC size from Digest object
4444
4445 ta_pid_send.init();
4446 ta_pid_recv.init("SSL-CC", 0, stats);
4447
4448 reset_tls_crypt(c, dyn_key);
4450 }
4451
4453 {
4454 // The session key is derived from the WKc riding on the first packet we
4455 // decapsulate, so there is nothing to install here -- see decapsulate(). Any key
4456 // this session already holds is left alone: decapsulate() can bring us back here
4457 // for a session already running, and dropping its contexts would leave the next
4458 // control packet it sends with nothing to authenticate itself with.
4459
4460 // Server context, used only to process incoming WKc's. Left unkeyed:
4461 // unwrap_tls_crypt_wkc() keys it, since only it knows which key the WKc needs.
4463 }
4464
4476 void reset(const ProtoSessionID cookie_psid = ProtoSessionID())
4477 {
4478 const ProtoConfig &c = *config;
4479
4480 // defer data channel initialization until after client options pull?
4482
4483 // clear key contexts
4484 reset_all();
4485
4486 // Drop the contexts a previous handshake set up: until the peer is known, no key may
4487 // be left that could authenticate its packets. reset_tls_crypt_server() cannot do it,
4488 // since decapsulate() also calls that for a session already running.
4494
4495 // start with key ID 0
4496 upcoming_key_id = 0;
4497
4498 unsigned int key_dir;
4499
4500 // tls-auth initialization
4502 switch (tls_wrap_mode)
4503 {
4504 case TLS_CRYPT:
4506 // init tls_crypt packet ID
4507 ta_pid_send.init();
4508 ta_pid_recv.init("SSL-CC", 0, stats);
4509 break;
4510 case TLS_CRYPT_V2:
4511 if (is_server())
4512 // Create the server context the client's WKc is unwrapped with,
4513 // keyed only at unwrap time, when the WKc names its key. tls-crypt
4514 // session key setup is postponed to reception of the WKc too.
4516 else
4517 {
4518 // a client's own Kc, the one its WKc carries to the server
4521 }
4524 // init tls_crypt packet ID
4526 ta_pid_recv.init("SSL-CC", 0, stats);
4527 break;
4528 case TLS_AUTH:
4529 // init OvpnHMACInstance
4532
4533 // init tls_auth hmac
4534 if (c.key_direction >= 0)
4535 {
4536 // key-direction is 0 or 1
4540 }
4541 else
4542 {
4543 // key-direction bidirectional mode
4546 }
4547
4557 ta_pid_send.init(cookie_psid.defined() ? 1 : 0);
4558 ta_pid_recv.init("SSL-CC", 0, stats);
4559 break;
4560 case TLS_PLAIN:
4561 break;
4562 }
4563
4564 // initialize proto session ID
4565 if (cookie_psid.defined())
4566 psid_self = cookie_psid;
4567 else
4569 psid_peer.reset();
4570
4571 // initialize key contexts
4572 primary.reset(new KeyContext(*this, is_client(), cookie_psid.defined()));
4573 OVPN_LOG_VERBOSE(debug_prefix() << " New KeyContext PRIMARY id=" << primary->key_id());
4574
4575 // initialize keepalive timers
4576 keepalive_expire = Time::infinite(); // initially disabled
4577 update_last_sent(); // set timer for initial keepalive send
4578 }
4579
4580 void set_protocol(const Protocol &p)
4581 {
4582 config->set_protocol(p);
4583 if (primary)
4584 primary->set_protocol(p);
4585 if (secondary)
4586 secondary->set_protocol(p);
4587 }
4588
4589 // Free up space when parent object has been halted but
4590 // object destruction is not immediately scheduled.
4592 {
4593 reset_all();
4594 }
4595
4596 // Is primary key defined
4598 {
4599 return bool(primary);
4600 }
4601
4602 virtual ~ProtoContext() = default;
4603
4604 // return the PacketType of an incoming network packet
4606 {
4607 return PacketType(buf, *this);
4608 }
4609
4618 void start(const ProtoSessionID cookie_psid = ProtoSessionID())
4619 {
4620 if (!primary)
4621 throw proto_error("start: no primary key");
4622 primary->start(cookie_psid);
4623 update_last_received(); // set an upper bound on when we expect a response
4624 }
4625
4626#ifdef UNIT_TEST
4627 // Test seam: pretend the server requested resending the tls-crypt-v2 WKc
4628 // (EARLY_NEG_FLAG_RESEND_WKC), so the first control packet carrying SSL
4629 // ciphertext is emitted as CONTROL_WKC_V1 with the WKc appended.
4630 void force_resend_wkc()
4631 {
4632 if (primary)
4633 primary->resend_wkc = true;
4634 }
4635#endif
4636
4637 // trigger a protocol renegotiation
4639 {
4640 // set up dynamic tls-crypt keys when the first rekeying happens
4641 // primary key_id 0 indicates that it is the first rekey
4642 if (conf().dynamic_tls_crypt_enabled() && primary && primary->key_id() == 0)
4644
4645 // initialize secondary key context
4646 new_secondary_key(true);
4647 secondary->start();
4648 }
4649
4650 // Should be called at the end of sequence of send/recv
4651 // operations on underlying protocol object.
4652 // If control_channel is true, do a full flush.
4653 // If control_channel is false, optimize flush for data
4654 // channel only.
4655 void flush(const bool control_channel)
4656 {
4657 if (control_channel || process_events())
4658 {
4659 do
4660 {
4661 if (primary)
4662 primary->flush();
4663 if (secondary)
4664 secondary->flush();
4665 } while (process_events());
4666 }
4667 }
4668
4669 // Perform various time-based housekeeping tasks such as retransmiting
4670 // unacknowleged packets as part of the reliability layer and testing
4671 // for keepalive timouts.
4672 // Should be called at the time returned by next_housekeeping.
4674 {
4675 // handle control channel retransmissions on primary
4676 if (primary)
4677 primary->retransmit();
4678
4679 // handle control channel retransmissions on secondary
4680 if (secondary)
4681 secondary->retransmit();
4682
4683 // handle possible events
4684 flush(false);
4685
4686 // handle keepalive/expiration
4688 }
4689
4690 // When should we next call housekeeping?
4691 // Will return a time value for immediate execution
4692 // if session has been invalidated.
4694 {
4695 if (!invalidated())
4696 {
4697 Time ret = Time::infinite();
4698 if (primary)
4699 ret.min(primary->next_retransmit());
4700 if (secondary)
4701 ret.min(secondary->next_retransmit());
4702 ret.min(keepalive_xmit);
4703 ret.min(keepalive_expire);
4704 return ret;
4705 }
4706 return Time();
4707 }
4708
4709 // send app-level cleartext to remote peer
4710
4712 {
4713 select_control_send_context().app_send(std::move(app_bp));
4714 }
4715
4717 {
4718 control_send(BufferAllocatedRc::Create(std::move(app_buf)));
4719 }
4720
4721 // validate a control channel network packet
4722 bool control_net_validate(const PacketType &type, const Buffer &net_buf)
4723 {
4724 return type.is_defined() && KeyContext::validate(net_buf, *this, now_);
4725 }
4726
4727 // pass received control channel network packets (ciphertext) into protocol object
4728 bool control_net_recv(const PacketType &type, BufferPtr &&net_bp)
4729 {
4730 Packet pkt(std::move(net_bp), type.opcode);
4731 if (type.is_soft_reset() && !renegotiate_request(pkt))
4732 return false;
4733 return select_key_context(type, true).net_recv(std::move(pkt));
4734 }
4735
4743 bool control_net_recv(const PacketType &type, BufferAllocated &&net_buf)
4744 {
4745 return control_net_recv(type, BufferAllocatedRc::Create(std::move(net_buf)));
4746 }
4747
4748 // encrypt a data channel packet using primary KeyContext
4750 {
4751 OVPN_LOG_DEBUG(debug_prefix() << " DATA ENCRYPT size=" << in_out.size());
4752 if (!primary)
4753 throw proto_error("data_encrypt: no primary key");
4754 primary->encrypt(in_out);
4755 }
4756
4757 // decrypt a data channel packet (automatically select primary
4758 // or secondary KeyContext based on packet content)
4759 bool data_decrypt(const PacketType &type, BufferAllocated &in_out)
4760 {
4761 bool ret = false;
4762
4763 OVPN_LOG_DEBUG(debug_prefix() << " DATA DECRYPT key_id=" << select_key_context(type, false).key_id() << " size=" << in_out.size());
4764
4765 select_key_context(type, false).decrypt(in_out);
4766
4767 // update time of most recent packet received
4768 if (!in_out.empty())
4769 {
4771 ret = true;
4772 }
4773
4774 // discard keepalive packets
4775 if (proto_context_private::is_keepalive(in_out))
4776 {
4777 in_out.reset_size();
4778 }
4779
4780 return ret;
4781 }
4782
4783 // enter disconnected state
4784 void disconnect(const Error::Type reason)
4785 {
4786 if (primary)
4787 primary->invalidate(reason);
4788 if (secondary)
4789 secondary->invalidate(reason);
4790 }
4791
4792 // normally used by UDP clients to tell the server that
4793 // they are disconnecting
4795 {
4796#ifndef OPENVPN_DISABLE_EXPLICIT_EXIT // explicit exit should always be enabled in production
4797 if (!is_client() || !is_udp() || !primary)
4798 {
4799 return;
4800 }
4801
4802 if (config->cc_exit_notify)
4803 {
4804 write_control_string(std::string("EXIT"));
4805 primary->flush();
4806 }
4807 else
4808 {
4809 primary->send_explicit_exit_notify();
4810 }
4811#endif // OPENVPN_DISABLE_EXPLICIT_EXIT
4812 }
4813
4814 // should be called after a successful network packet transmit
4816 {
4817 keepalive_xmit = *now_ + config->keepalive_ping;
4818 }
4819
4820 // Can we call data_encrypt or data_decrypt yet?
4821 // Returns true if primary data channel is in ACTIVE state.
4823 {
4824 return primary && primary->data_channel_ready();
4825 }
4826
4827 // total number of SSL/TLS negotiations during lifetime of ProtoContext object
4828 unsigned int negotiations() const
4829 {
4830 return n_key_ids;
4831 }
4832
4833 // worst-case handshake time
4834 const Time::Duration &slowest_handshake()
4835 {
4836 return slowest_handshake_;
4837 }
4838
4839 // was primary context invalidated by an exception?
4840 bool invalidated() const
4841 {
4842 return primary && primary->invalidated();
4843 }
4844
4845 // reason for invalidation if invalidated() above returns true
4847 {
4848 return primary->invalidation_reason();
4849 }
4850
4851 // Do late initialization of data channel, for example
4852 // on client after server push, or on server after client
4853 // capabilities are known.
4855 {
4856 dc_deferred = false;
4857
4858 // initialize data channel (crypto & compression)
4859 if (primary)
4860 primary->init_data_channel();
4861 if (secondary)
4862 secondary->init_data_channel();
4863 }
4864
4865 // Call on client with server-pushed options
4867 {
4868 // modify config with pushed options
4869 config->process_push(opt, pco);
4870
4871 // in case keepalive parms were modified by push
4873 }
4874
4875 // Return the current transport alignment adjustment
4876 size_t align_adjust_hint() const
4877 {
4878 return config->enable_op32 ? 0 : 1;
4879 }
4880
4881 // Return true if keepalive parameter(s) are enabled
4883 {
4884 return config->keepalive_ping.enabled()
4885 || config->keepalive_timeout.enabled();
4886 }
4887
4888 // Disable keepalive for rest of session,
4889 // but return the previous keepalive parameters.
4890 void disable_keepalive(unsigned int &keepalive_ping,
4891 unsigned int &keepalive_timeout)
4892 {
4893 keepalive_ping = config->keepalive_ping.enabled()
4894 ? clamp_to_typerange<std::remove_reference_t<decltype(keepalive_ping)>>(config->keepalive_ping.to_seconds())
4895 : 0;
4896 keepalive_timeout = config->keepalive_timeout.enabled()
4897 ? clamp_to_typerange<std::remove_reference_t<decltype(keepalive_timeout)>>(config->keepalive_timeout.to_seconds())
4898 : 0;
4899 config->keepalive_ping = Time::Duration::infinite();
4900 config->keepalive_timeout = Time::Duration::infinite();
4901 config->keepalive_timeout_early = Time::Duration::infinite();
4903 }
4904
4905 // Notify our component KeyContext when per-key Data Limits have been reached
4906 void data_limit_notify(const unsigned int key_id,
4907 const DataLimit::Mode cdl_mode,
4908 const DataLimit::State cdl_status)
4909 {
4910 if (primary && key_id == primary->key_id())
4911 primary->data_limit_notify(cdl_mode, cdl_status);
4912 else if (secondary && key_id == secondary->key_id())
4913 secondary->data_limit_notify(cdl_mode, cdl_status);
4914 }
4915
4916 // access the data channel settings
4918 {
4919 return config->dc;
4920 }
4921
4922 // reset the data channel factory
4924 {
4925 config->dc.reset();
4926 }
4927
4928 // set the local peer ID (or -1 to disable)
4929 void set_local_peer_id(const int local_peer_id)
4930 {
4931 config->local_peer_id = local_peer_id;
4932 }
4933
4934 // current time
4935 const Time &now() const
4936 {
4937 return *now_;
4938 }
4940 {
4941 now_->update();
4942 }
4943
4944 // frame
4945 const Frame &frame() const
4946 {
4947 return *config->frame;
4948 }
4949 const Frame::Ptr &frameptr() const
4950 {
4951 return config->frame;
4952 }
4953
4954 // client or server?
4955 const Mode &mode() const
4956 {
4957 return mode_;
4958 }
4959 bool is_server() const
4960 {
4961 return mode_.is_server();
4962 }
4963 bool is_client() const
4964 {
4965 return mode_.is_client();
4966 }
4967
4968 // tcp/udp mode
4969 bool is_tcp()
4970 {
4971 return config->protocol.is_tcp();
4972 }
4973 bool is_udp()
4974 {
4975 return config->protocol.is_udp();
4976 }
4977
4978 // configuration
4979 const ProtoConfig &conf() const
4980 {
4981 return *config;
4982 }
4984 {
4985 return *config;
4986 }
4988 {
4989 return config;
4990 }
4991
4992 // stats
4994 {
4995 return *stats;
4996 }
4997
4998 // debugging
5000 {
5001 return primary_state() == C_WAIT_RESET_ACK;
5002 }
5003
5004 protected:
5005 int primary_state() const
5006 {
5007 if (primary)
5008 return primary->get_state();
5009 return STATE_UNDEF;
5010 }
5011
5012 private:
5013 // TLS wrapping mode for the control channel
5021
5023 {
5024 if (primary)
5026 primary.reset();
5027 secondary.reset();
5028 }
5029
5030 // Called on client to request username/password credentials.
5031 // delegated to the callback/parent
5033 {
5035 }
5036
5038 {
5039 keepalive_expire = *now_ + (data_channel_ready() ? config->keepalive_timeout : config->keepalive_timeout_early);
5040 }
5041
5042 void net_send(const unsigned int key_id, const Packet &net_pkt)
5043 {
5045 }
5046
5047 void app_recv(const unsigned int key_id, BufferPtr &&to_app_buf)
5048 {
5050 }
5051
5052 // we're getting a request from peer to renegotiate.
5054 {
5055 // set up dynamic tls-crypt keys when the first rekeying happens
5056 // primary key_id 0 indicates that it is the first rekey
5057 if (conf().dynamic_tls_crypt_enabled() && primary && primary->key_id() == 0)
5059
5060 if (KeyContext::validate(pkt.buffer(), *this, now_))
5061 {
5062 new_secondary_key(false);
5063 return true;
5064 }
5065 return false;
5066 }
5067
5068 // select a KeyContext (primary or secondary) for received network packets
5069 KeyContext &select_key_context(const PacketType &type, const bool control)
5070 {
5071 const unsigned int flags = type.flags & (PacketType::DEFINED | PacketType::SECONDARY | PacketType::CONTROL);
5072 if (!control)
5073 {
5074 if (flags == (PacketType::DEFINED) && primary)
5075 return *primary;
5077 return *secondary;
5078 }
5079 else
5080 {
5082 {
5083 return *primary;
5084 }
5086 && secondary)
5087 {
5088 return *secondary;
5089 }
5090 }
5091 throw select_key_context_error();
5092 }
5093
5094 // Select a KeyContext (primary or secondary) for control channel sends.
5095 // Even after new key context goes active, we still wait for
5096 // KEV_BECOME_PRIMARY event (controlled by the become_primary duration
5097 // in Config) before we use it for app-level control-channel
5098 // transmissions. Simulations have found this method to be more reliable
5099 // than the immediate rollover practiced by OpenVPN 2.x.
5101 {
5102 OVPN_LOG_VERBOSE(debug_prefix() << " CONTROL SEND");
5103 if (!primary)
5104 throw proto_error("select_control_send_context: no primary key");
5105 return *primary;
5106 }
5107
5108 // Possibly send a keepalive message, and check for expiration
5109 // of session due to lack of received packets from peer.
5111 {
5112 const Time now = *now_;
5113
5114 // check for keepalive timeouts
5115 if (now >= keepalive_xmit && primary)
5116 {
5117 primary->send_keepalive();
5119 }
5120 if (now >= keepalive_expire)
5121 {
5122 // no contact with peer, disconnect
5125 }
5126 }
5127
5128 // Process KEV_x events
5129 // Return true if any events were processed.
5131 {
5132 bool did_work = false;
5133
5134 // primary
5135 if (primary && primary->event_pending())
5136 {
5138 did_work = true;
5139 }
5140
5141 // secondary
5142 if (secondary && secondary->event_pending())
5143 {
5145 did_work = true;
5146 }
5147
5148 return did_work;
5149 }
5150
5151 // Create a new secondary key.
5152 // initiator --
5153 // false : remote renegotiation request
5154 // true : local renegotiation request
5155 void new_secondary_key(const bool initiator)
5156 {
5157 // Create the secondary
5158 secondary.reset(new KeyContext(*this, initiator));
5160 << " New KeyContext SECONDARY id=" << secondary->key_id()
5161 << (initiator ? " local-triggered" : " remote-triggered"));
5162 }
5163
5164 // Promote a newly renegotiated KeyContext to primary status.
5165 // This is usually triggered by become_primary variable (Time::Duration)
5166 // in Config.
5168 {
5170 if (primary)
5172 if (secondary)
5173 secondary->prepare_expire();
5174 OVPN_LOG_VERBOSE(debug_prefix() << " PRIMARY_SECONDARY_SWAP");
5175 }
5176
5178 {
5179 const KeyContext::EventType ev = primary->get_event();
5180 if (ev != KeyContext::KEV_NONE)
5181 {
5182 primary->reset_event();
5183 switch (ev)
5184 {
5186 OVPN_LOG_VERBOSE(debug_prefix() << " SESSION_ACTIVE");
5188 proto_callback->active(true);
5189 break;
5192 renegotiate();
5193 break;
5195 if (secondary && !secondary->invalidated())
5197 else
5198 {
5200 // primary context expired and no secondary context available
5202 }
5203 break;
5206 // primary negotiation failed
5208 break;
5209 default:
5210 break;
5211 }
5212 }
5213 primary->set_next_event_if_unspecified();
5214 }
5215
5217 {
5218 const KeyContext::EventType ev = secondary->get_event();
5219 if (ev != KeyContext::KEV_NONE)
5220 {
5221 secondary->reset_event();
5222 switch (ev)
5223 {
5226 if (primary)
5227 primary->prepare_expire();
5228 proto_callback->active(false);
5229 break;
5231 if (!secondary->invalidated())
5233 break;
5236 secondary.reset();
5237 break;
5239 if (primary)
5241 secondary->become_primary_time());
5242 break;
5245 [[fallthrough]];
5248 renegotiate();
5249 break;
5250 default:
5251 break;
5252 }
5253 }
5254 if (secondary)
5255 secondary->set_next_event_if_unspecified();
5256 }
5257
5258 std::string debug_prefix()
5259 {
5260 std::string ret = openvpn::to_string(now_->raw());
5261 ret += is_server() ? " SERVER[" : " CLIENT[";
5262 if (primary)
5263 ret += openvpn::to_string(primary->key_id());
5264 if (secondary)
5265 {
5266 ret += '/';
5267 ret += openvpn::to_string(secondary->key_id());
5268 }
5269 ret += ']';
5270 return ret;
5271 }
5272
5273 // key_id starts at 0, increments to KEY_ID_MASK, then recycles back to 1.
5274 // Therefore, if key_id is 0, it is the first key.
5275 unsigned int next_key_id()
5276 {
5277 ++n_key_ids;
5278 unsigned int ret = upcoming_key_id;
5279 if ((upcoming_key_id = (upcoming_key_id + 1) & KEY_ID_MASK) == 0)
5280 upcoming_key_id = 1;
5281 return ret;
5282 }
5283
5284 // call whenever keepalive parms are modified,
5285 // to reset timers
5287 {
5289
5290 // For keepalive_xmit timer, don't reschedule current cycle
5291 // unless it would fire earlier. Subsequent cycles will
5292 // time according to new keepalive_ping value.
5293 const Time kx = *now_ + config->keepalive_ping;
5294 if (kx < keepalive_xmit)
5295 keepalive_xmit = kx;
5296 }
5297
5299 {
5300 if (!config->wkc.defined())
5301 throw proto_error("Client Key Wrapper undefined");
5302 dst.append(config->wkc);
5303 }
5304
5305 // BEGIN ProtoContext data members
5306
5313
5316
5319 Mode mode_; // client or server
5320 unsigned int upcoming_key_id = 0;
5321 unsigned int n_key_ids;
5322
5323 TimePtr now_; // pointer to current time (a clone of config->now)
5324 Time keepalive_xmit; // time in future when we will transmit a keepalive (subject to continuous change)
5325 Time keepalive_expire; // time in future when we must have received a packet from peer or we will timeout session
5326
5327 Time::Duration slowest_handshake_; // longest time to reach a successful handshake
5328
5331
5334
5336
5347
5356
5359
5362
5365 bool dc_deferred = false;
5366
5367 // END ProtoContext data members
5368};
5369
5370} // namespace openvpn
5371
5372#endif // OPENVPN_SSL_PROTO_H
#define OPENVPN_BS64_DATA_LIMIT
void swap(BufferAllocatedType< T_ > &other)
Swaps the contents of this BufferAllocatedType object with another BufferAllocatedType object.
Definition buffer.hpp:1799
bool advance(size_t size)
void put(BufferPtr bp)
report various types of exceptions or errors that may occur when working with buffers
Definition buffer.hpp:115
static Type parse_method(const std::string &method)
Definition compress.hpp:467
const char * options_string() const
Definition compress.hpp:391
unsigned int extra_payload_bytes() const
Definition compress.hpp:186
const char * str() const
Definition compress.hpp:411
static Type stub(const Type t)
Definition compress.hpp: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:1597
void append(const B &other)
Append data from another buffer to this buffer.
Definition buffer.hpp:1626
void inc_size(const size_t delta)
Increment the size of the array (usually used in a similar context to set_size such as after mutable_...
Definition buffer.hpp:1390
size_t max_size() const
Return the maximum allowable size value in T objects given the current offset (without considering re...
Definition buffer.hpp:1375
void prepend(const T *data, const size_t size)
Prepend data to the buffer.
Definition buffer.hpp:1574
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:1448
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:1561
auto * read_alloc(const size_t size)
Allocate memory and read data from the buffer into the allocated memory.
Definition buffer.hpp:1343
T pop_front()
Removes and returns the first element from the buffer.
Definition buffer.hpp:1255
void push_front(const T &value)
Append a T object to the array, with possible resize.
Definition buffer.hpp:1488
void set_size(const size_t size)
After an external method, operating on the array as a mutable unsigned char buffer,...
Definition buffer.hpp:1382
void null_terminate()
Null-terminate the array.
Definition buffer.hpp:1506
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:4145
bool client_supports_auth_pending_kwargs() const
Definition proto.hpp:4117
IvProtoHelper(const OptionList &peer_info)
Definition proto.hpp:4097
bool client_supports_temp_auth_failed() const
Definition proto.hpp:4107
bool client_supports_exit_notify() const
Checks if the client is able to send an explicit EXIT message before exiting.
Definition proto.hpp:4133
bool client_supports_dynamic_tls_crypt() const
Checks if the client can handle dynamic TLS-crypt.
Definition proto.hpp:4139
void encapsulate(id_t id, Packet &pkt)
Definition proto.hpp:3519
static bool opcode_carries_wkc(const unsigned int opcode)
Does a packet with this opcode carry a WKc?
Definition proto.hpp:2174
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:3549
void kev_error(const EventType ev, const Error::Type reason)
Definition proto.hpp:3062
static bool tls_crypt_v2_convertible(const ProtoContext &proto, const unsigned int opcode)
May a packet with this opcode convert a tls-auth session to tls-crypt-v2?
Definition proto.hpp:2186
static BufferAllocated static_work
Definition proto.hpp:4025
static bool validate(const Buffer &net_buf, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2196
void set_protocol(const Protocol &p)
Definition proto.hpp:1868
void prepend_dest_psid_and_acks(Buffer &buf, unsigned int opcode)
Definition proto.hpp:3310
TLSPRFInstance::Ptr tlsprf
Definition proto.hpp:4012
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:2707
void set_state(const int newstate)
Definition proto.hpp:2910
std::deque< BufferPtr > app_pre_write_queue
Definition proto.hpp:4018
void recv_auth(BufferPtr buf)
Definition proto.hpp:3250
bool decapsulate_tls_plain(Packet &pkt)
Definition proto.hpp:3719
static bool validate_tls_plain(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2840
void app_recv(BufferPtr &&to_app_buf)
Definition proto.hpp:3157
bool pkt_from_peer
Set per packet by accept_peer(), read by decapsulate()
Definition proto.hpp:4006
void net_send(const Packet &net_pkt, const Base::NetSendType nstype)
Definition proto.hpp:3190
size_t control_channel_wrap_overhead() const
Definition proto.hpp:3480
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:2433
void set_event(const EventType current)
Definition proto.hpp:2918
void raw_recv(Packet &&raw_pkt)
Definition proto.hpp:3136
void gen_head(const unsigned int opcode, BufferAllocated &buf)
Definition proto.hpp:3447
size_t control_ciphertext_capacity(id_t id) const
Definition proto.hpp:3498
std::unique_ptr< DataLimit > data_limit
Definition proto.hpp:4021
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:3390
void gen_head_tls_plain(const unsigned int opcode, Buffer &buf)
Definition proto.hpp:3439
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:3348
bool recv_auth_complete(BufferComplete &bc) const
Definition proto.hpp:3267
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:2525
bool verify_src_psid(const ProtoSessionID &src_psid)
Definition proto.hpp:3328
void generate_ack(Packet &pkt)
Definition proto.hpp:3539
bool verify_dest_psid(Buffer &buf)
Definition proto.hpp:3355
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:3771
bool packet_carries_wkc(id_t id) const
Definition proto.hpp:3469
bool parse_early_negotiation(const Packet &pkt)
Definition proto.hpp:3092
void calculate_mssfix(ProtoConfig &c)
Definition proto.hpp:2264
bool decapsulate_tls_crypt(Packet &pkt)
Definition proto.hpp:3652
static bool validate_tls_crypt(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2772
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:2449
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:2470
void gen_head_tls_auth(const unsigned int opcode, Buffer &buf)
Definition proto.hpp:3368
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:3879
OPENVPN_SIMPLE_EXCEPTION(tls_crypt_unwrap_wkc_error)
void data_limit_event(const DataLimit::Mode mode, const DataLimit::State state)
Definition proto.hpp:2983
CryptoDCInstance::Ptr crypto
Definition proto.hpp:4011
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:2724
unsigned int initial_op(const bool sender, const bool tls_crypt_v2) const
Definition proto.hpp:3069
int seconds_until(const Time &next_time)
Definition proto.hpp:3985
static const char * state_string(const int s)
Definition proto.hpp:3953
void data_limit_notify(const DataLimit::Mode cdl_mode, const DataLimit::State cdl_status)
Definition proto.hpp:2415
bool verify_wkc_metadata(WkcMetadata &metadata)
Put the record a WKc carried to the embedder's hook, if it installed one.
Definition proto.hpp:3848
bool do_encrypt(BufferAllocated &buf, const bool compress_hint)
Definition proto.hpp:2860
std::unique_ptr< DataChannelKey > data_channel_key
Definition proto.hpp:4019
bool data_limit_add(const DataLimit::Mode mode, const size_t size)
Definition proto.hpp:2972
void set_event(const EventType current, const EventType next, const Time &next_time)
Definition proto.hpp:2926
void rekey(const CryptoDCInstance::RekeyType type)
Definition proto.hpp:2111
bool decapsulate(Packet &pkt)
Definition proto.hpp:3776
void key_limit_reneg(const EventType ev, const Time &t)
Definition proto.hpp:2047
bool decapsulate_tls_auth(Packet &pkt)
Definition proto.hpp:3618
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:4054
static unsigned char get_server_hard_reset_opfield()
Definition proto.hpp:4084
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:4060
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:4048
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:4066
PsidCookieHelper(unsigned int op_field)
Definition proto.hpp:4031
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:4072
bool is_tls_crypt_v2() const noexcept
Returns true if this is a TLS crypt V2 protocol packet.
Definition proto.hpp:4042
TLSAuthPreValidate(const ProtoConfig &c, const bool server)
Definition proto.hpp:4168
OPENVPN_SIMPLE_EXCEPTION(tls_auth_pre_validate)
bool validate(const BufferAllocated &net_buf)
Definition proto.hpp:4195
OPENVPN_SIMPLE_EXCEPTION(tls_crypt_pre_validate)
TLSCryptPreValidate(const ProtoConfig &c, const bool server)
Definition proto.hpp:4229
bool validate(const BufferAllocated &net_buf)
Definition proto.hpp:4266
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:4906
bool control_net_recv(const PacketType &type, BufferPtr &&net_bp)
Definition proto.hpp:4728
void set_local_peer_id(const int local_peer_id)
Definition proto.hpp:4929
uint32_t get_tls_warnings() const
Definition proto.hpp:4372
void send_explicit_exit_notify()
Definition proto.hpp:4794
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, process_server_push_error)
bool is_client() const
Definition proto.hpp:4963
void net_send(const unsigned int key_id, const Packet &net_pkt)
Definition proto.hpp:5042
const Time::Duration & slowest_handshake()
Definition proto.hpp:4834
const Time & now() const
Definition proto.hpp:4935
CryptoDCSettings & dc_settings()
Definition proto.hpp:4917
void flush(const bool control_channel)
Definition proto.hpp:4655
void set_dynamic_tls_crypt(const ProtoConfig &c, const KeyContext::Ptr &key_ctx)
Definition proto.hpp:4402
OPENVPN_SIMPLE_EXCEPTION(select_key_context_error)
void control_send(BufferPtr &&app_bp)
Definition proto.hpp:4711
KeyContext & select_control_send_context()
Definition proto.hpp:5100
bool uses_bs64_cipher() const
Definition proto.hpp:4381
void process_secondary_event()
Definition proto.hpp:5216
void reset_tls_crypt(const ProtoConfig &c, const OpenVPNStaticKey &key)
Definition proto.hpp:4386
OpenVPNStaticKey tls_crypt_client_key
Kc, the tls-crypt-v2 client key this session's control channel is keyed with.
Definition proto.hpp:5346
PacketType packet_type(const Buffer &buf)
Definition proto.hpp:4605
void data_encrypt(BufferAllocated &in_out)
Definition proto.hpp:4749
void reset_tls_crypt_server(const ProtoConfig &c)
Definition proto.hpp:4452
bool dynamic_tls_crypt_keyed
Whether set_dynamic_tls_crypt() has keyed this session already.
Definition proto.hpp:5355
TLSCryptInstance::Ptr tls_crypt_recv
Definition proto.hpp:5333
bool is_keepalive_enabled() const
Definition proto.hpp:4882
KeyContext::Ptr primary
Definition proto.hpp:5363
TLSCryptInstance::Ptr tls_crypt_server
Definition proto.hpp:5335
const Frame & frame() const
Definition proto.hpp:4945
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:4987
ProtoSessionID psid_peer
Definition proto.hpp:5361
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_option_error)
void process_primary_event()
Definition proto.hpp:5177
const Mode & mode() const
Definition proto.hpp:4955
TLSCryptInstance::Ptr tls_crypt_send
Definition proto.hpp:5332
void process_push(const OptionList &opt, const ProtoContextCompressionOptions &pco)
Definition proto.hpp:4866
static void write_auth_string(const S &str, Buffer &buf)
Definition proto.hpp:1570
void client_auth(Buffer &buf)
Definition proto.hpp:5032
ProtoConfig & conf()
Definition proto.hpp:4983
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:4580
static unsigned int key_id_extract(const unsigned int op)
Definition proto.hpp:314
ProtoSessionID psid_self
Definition proto.hpp:5360
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:4822
void keepalive_housekeeping()
Definition proto.hpp:5110
Time::Duration slowest_handshake_
Definition proto.hpp:5327
unsigned int upcoming_key_id
Definition proto.hpp:5320
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:4876
PacketIDControlReceive ta_pid_recv
Definition proto.hpp:5358
ProtoContextCallbackInterface * proto_callback
Definition proto.hpp:5312
void reset_tls_wrap_mode(const ProtoConfig &c)
Definition proto.hpp:4334
SessionStats & stat() const
Definition proto.hpp:4993
bool is_server() const
Definition proto.hpp:4959
OvpnHMACInstance::Ptr ta_hmac_recv
Definition proto.hpp:5330
std::string dump_packet(const Buffer &buf)
Definition proto.hpp:1455
void disconnect(const Error::Type reason)
Definition proto.hpp:4784
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:4722
KeyContext & select_key_context(const PacketType &type, const bool control)
Definition proto.hpp:5069
static void write_empty_string(Buffer &buf)
Definition proto.hpp:1604
TLSWrapMode tls_wrap_mode
Definition proto.hpp:5318
void app_recv(const unsigned int key_id, BufferPtr &&to_app_buf)
Definition proto.hpp:5047
void keepalive_parms_modified()
Definition proto.hpp:5286
int primary_state() const
Definition proto.hpp:5005
static void write_control_string(const S &str, Buffer &buf)
Definition proto.hpp:1597
void control_send(BufferAllocated &&app_buf)
Definition proto.hpp:4716
bool data_decrypt(const PacketType &type, BufferAllocated &in_out)
Definition proto.hpp:4759
void disable_keepalive(unsigned int &keepalive_ping, unsigned int &keepalive_timeout)
Definition proto.hpp:4890
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:4846
static size_t op_head_size(const unsigned int op)
Definition proto.hpp:319
void new_secondary_key(const bool initiator)
Definition proto.hpp:5155
void update_last_received()
Definition proto.hpp:5037
void promote_secondary_to_primary()
Definition proto.hpp:5167
bool is_state_client_wait_reset_ack() const
Definition proto.hpp:4999
unsigned int negotiations() const
Definition proto.hpp:4828
PacketIDControlSend ta_pid_send
Definition proto.hpp:5357
Time next_housekeeping() const
Definition proto.hpp:4693
ProtoContext(ProtoContextCallbackInterface *cb_arg, const ProtoConfig::Ptr &config_arg, const SessionStats::Ptr &stats_arg)
Definition proto.hpp:4321
static void write_uint16_length(const size_t size, Buffer &buf)
Definition proto.hpp:1550
SessionStats::Ptr stats
Definition proto.hpp:5315
static constexpr size_t OPCODE_SIZE
Definition proto.hpp:216
unsigned int n_key_ids
Definition proto.hpp:5321
void tls_crypt_append_wkc(BufferAllocated &dst)
Definition proto.hpp:5298
ProtoConfig::Ptr config
Definition proto.hpp:5314
bool control_net_recv(const PacketType &type, BufferAllocated &&net_buf)
pass received control channel network packets (ciphertext) into protocol object
Definition proto.hpp:4743
virtual ~ProtoContext()=default
std::string debug_prefix()
Definition proto.hpp:5258
static constexpr size_t APP_MSG_MAX
Definition proto.hpp:214
const Frame::Ptr & frameptr() const
Definition proto.hpp:4949
bool invalidated() const
Definition proto.hpp:4840
void reset(const ProtoSessionID cookie_psid=ProtoSessionID())
Resets ProtoContext *this to it's initial state.
Definition proto.hpp:4476
void start(const ProtoSessionID cookie_psid=ProtoSessionID())
Initialize the state machine and start protocol negotiation.
Definition proto.hpp:4618
bool renegotiate_request(Packet &pkt)
Definition proto.hpp:5053
static constexpr size_t MAX_CONTROL_WRAP_OVERHEAD
Definition proto.hpp:350
KeyContext::Ptr secondary
Definition proto.hpp:5364
unsigned int next_key_id()
Definition proto.hpp:5275
OvpnHMACInstance::Ptr ta_hmac_send
Definition proto.hpp:5329
const ProtoConfig & conf() const
Definition proto.hpp:4979
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
@ TUN_MTU_DEFAULT
Definition tunmtu.hpp:20
const Option * load_duration_parm(Time::Duration &dur, const std::string &name, const OptionList &opt, const unsigned int min_value, const bool x2, const bool allow_ms)
Definition durhelper.hpp:41
void set_duration_parm(Time::Duration &dur, const std::string &name, const std::string &valstr, const unsigned int min_value, const bool x2, const bool ms)
Definition durhelper.hpp:20
std::string read_text(const std::string &filename, const std::uint64_t max_size=0)
Definition file.hpp:127
std::string to_string(const T &t)
Convert a value to a string.
Definition to_string.hpp:45
const char * platform_name()
std::string render_hex(const unsigned char *data, size_t size, const bool caps=false)
Definition hexstr.hpp:133
TimeType< oulong > Time
Definition time.hpp:487
unsigned int parse_tun_mtu_max(const OptionList &opt, unsigned int default_value)
Definition tunmtu.hpp:28
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 render_hex_number(T value, const bool caps=false)
Definition hexstr.hpp:459
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:2510
OpenVPNStaticKey client_key
Kc, the client key the WKc wrapped.
Definition proto.hpp:2512
The metadata record a WKc carried, for TLSCryptMetadata::verify()
Definition proto.hpp:2496
int type
-1 when the WKc carried no metadata at all
Definition proto.hpp:2498
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