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 CONTROL_OOB_V1 = 12, // out-of-band control message (belongs to no session)
231 CONTROL_OOB_WKC_V1 = 13, // out-of-band control message + wrapped client key appended
232 ACK_V1 = 5, // acknowledgement for packets received
233 DATA_V1 = 6, // data channel packet with 1-byte header
234 DATA_V2 = 9, // data channel packet with 4-byte header
235
236 // indicates key_method >= 2
237 CONTROL_HARD_RESET_CLIENT_V2 = 7, // initial key from client, forget previous state
238 CONTROL_HARD_RESET_CLIENT_V3 = 10, // initial key from client, forget previous state
239 CONTROL_HARD_RESET_SERVER_V2 = 8, // initial key from server, forget previous state
240
242
243 // DATA_V2 constants
244 OP_SIZE_V2 = 4, // size of initial packet opcode
245 OP_PEER_ID_UNDEF = 0x00FFFFFF, // indicates that Peer ID is undefined
246
247 // states
248 // C_x : client states
249 // S_x : server states
250
251 // ACK states -- must be first before other states
257 LAST_ACK_STATE = 3, // all ACK states must be <= this value
258
259 // key negotiation states (client)
261 C_WAIT_RESET = 5, // must be C_INITIAL+1
263
264 // key negotiation states (server)
266 S_WAIT_RESET = 8, // must be S_INITIAL+1
268
269 // key negotiation states (client and server)
270 ACTIVE = 10,
271 };
272
273 enum iv_proto_flag : unsigned int
274 {
275 // See ssl.h in openvpn2 for detailed documentation of IV_PROTO
276 //
277 // NOTE: Bit field (1 << 0) is reserved for historic reasons
278 // and not expected to be set. Do not use this field.
279 //
284 IV_PROTO_NCP_P2P = (1 << 5), // not implemented
285 IV_PROTO_DNS_OPTION = (1 << 6), // outdated, don't send
291 IV_PROTO_PUSH_UPDATE = (1 << 12)
292 };
293
294 enum tlv_types : uint16_t
295 {
296 EARLY_NEG_FLAGS = 0x0001
297 };
298
299 enum early_neg_flags : uint16_t
300 {
302 };
303
308 static constexpr PacketIDControl::id_t EARLY_NEG_START = 0x0f000000;
309 static constexpr PacketIDControl::id_t EARLY_NEG_MASK = 0xff000000;
310
311 static unsigned int opcode_extract(const unsigned int op)
312 {
313 return op >> OPCODE_SHIFT;
314 }
315
316 static unsigned int key_id_extract(const unsigned int op)
317 {
318 return op & KEY_ID_MASK;
319 }
320
321 static size_t op_head_size(const unsigned int op)
322 {
323 return opcode_extract(op) == DATA_V2 ? OP_SIZE_V2 : 1;
324 }
325
326 static unsigned char op_compose(const unsigned int opcode, const unsigned int key_id)
327 {
328 // As long as 'opcode' stays within the range specified by the enum the cast should be safe.
329 // TODO: Use a more constrained type for opcode to ensure range violations can't happen.
330 return static_cast<unsigned char>((opcode << OPCODE_SHIFT) | key_id);
331 }
332
333 static unsigned int op32_compose(const unsigned int opcode,
334 const unsigned int key_id,
335 const int op_peer_id)
336 {
337 return (op_compose(opcode, key_id) << 24) | (op_peer_id & 0x00FFFFFF);
338 }
339
340 public:
341 OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_error);
342 OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, process_server_push_error);
343 OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_option_error);
344
345 // Worst-case number of bytes added around the SSL ciphertext of a
346 // control channel packet: opcode, session id, tls-auth/tls-crypt
347 // packet id, the largest supported HMAC digest (SHA512, tls-auth),
348 // the reliable-layer message id and the largest possible piggybacked
349 // ACK block (count byte + ACK ids + dest session id). Used to size
350 // the control channel ciphertext chunks such that the final wrapped
351 // packet cannot exceed the mssfix_ctrl limit.
352 static constexpr size_t MAX_CONTROL_WRAP_OVERHEAD =
356 + 64 // largest supported HMAC digest (SHA512, tls-auth)
357 + sizeof(reliable::id_t)
360
361 // configuration data passed to ProtoContext constructor
362 class ProtoConfig : public RCCopyable<thread_unsafe_refcount>
363 {
364 public:
366
367 // master SSL context factory
369
370 // data channel
372
373 // TLSPRF factory
375
376 // master Frame object
378
379 // (non-smart) pointer to current time
381
382 // Random number generator.
383 // Use-cases demand highest cryptographic strength
384 // such as key generation.
386
387 // Pseudo-random number generator.
388 // Use-cases demand cryptographic strength
389 // combined with high performance. Used for
390 // IV and ProtoSessionID generation.
392
393 // If relay mode is enabled, connect to a special OpenVPN
394 // server that acts as a relay/proxy to a second server.
395 bool relay_mode = false;
396
397 // defer data channel initialization until after client options pull
398 bool dc_deferred = false;
399
400 // transmit username/password creds to server (client-only)
401 bool xmit_creds = true;
402
403 // send client exit notifications via control channel
404 bool cc_exit_notify = false;
405
406 // Transport protocol, i.e. UDPv4, etc.
407 Protocol protocol; // set with set_protocol()
408
409 // OSI layer
411
412 // compressor
414
415 // tls_auth/crypt parms
417 {
418 None = 0,
419 V1 = (1 << 0),
420 V2 = (1 << 1),
421 Dynamic = (1 << 2)
422 };
423
426
429
432
435
438
441
444 int key_direction = -1; // 0, 1, or -1 for bidirectional
445
448
450
451 // timeout parameters, relative to construction of KeyContext object
452 Time::Duration handshake_window; // SSL/TLS negotiation must complete by this time
453 Time::Duration become_primary; // KeyContext (that is ACTIVE) becomes primary at this time
454 Time::Duration renegotiate; // start SSL/TLS renegotiation at this time
455 Time::Duration expire; // KeyContext expires at this time
456 Time::Duration tls_timeout; // Packet retransmit timeout on TLS control channel
457
458 // keepalive parameters
459 Time::Duration keepalive_ping; // ping xmit period
460 Time::Duration keepalive_timeout; // timeout period after primary KeyContext reaches ACTIVE state
461 Time::Duration keepalive_timeout_early; // timeout period before primary KeyContext reaches ACTIVE state
462
465
466 // App control config
472
476
477 // op header
478 bool enable_op32 = false;
479 int remote_peer_id = -1; // -1 to disable
480 int local_peer_id = -1; // -1 to disable
481
482 // MTU
483 unsigned int tun_mtu = TUN_MTU_DEFAULT;
484 unsigned int tun_mtu_max = TUN_MTU_DEFAULT + 100;
486 unsigned int mss_fix = 0;
487
488 // maximum size of a control channel packet on the wire, after all
489 // wrapping (tls-auth/tls-crypt/tls-crypt-v2) has been applied;
490 // 1280 == IPv6 minimum MTU
491 size_t mssfix_ctrl = 1280;
492
493 // For compatibility with openvpn2 we send initial options on rekeying,
494 // instead of possible modifications caused by NCP
495 std::string initial_options;
496
497 bool auth_nocache = false;
498
499 void load(const OptionList &opt,
501 const int default_key_direction,
502 const bool server)
503 {
504 // first set defaults
505 handshake_window = Time::Duration::seconds(60);
506 renegotiate = Time::Duration::seconds(3600);
507 tls_timeout = Time::Duration::seconds(1);
508 keepalive_ping = Time::Duration::seconds(8);
509 keepalive_timeout = Time::Duration::seconds(40);
512 protocol = Protocol();
513 key_direction = default_key_direction;
514
515 // layer
516 {
517 const Option *dev = opt.get_ptr("dev-type");
518 if (!dev)
519 dev = opt.get_ptr("dev");
520 if (!dev)
521 throw proto_option_error(ERR_INVALID_CONFIG, "missing dev-type or dev option");
522 const std::string &dev_type = dev->get(1, 64);
523 if (dev_type.starts_with("tun"))
525 else if (dev_type.starts_with("tap"))
526 throw proto_option_error(ERR_INVALID_CONFIG, "TAP mode is not supported");
527 else
528 throw proto_option_error(ERR_INVALID_OPTION_VAL, "bad dev-type");
529 }
530
531 // cipher/digest/tls-auth/tls-crypt
532 {
535
536 // data channel cipher
537 {
538 const Option *o = opt.get_ptr("cipher");
539 if (o)
540 {
541 const std::string &cipher_name = o->get(1, 128);
542 if (cipher_name != "none")
543 cipher = CryptoAlgs::lookup(cipher_name);
544 }
545 else
546 cipher = CryptoAlgs::lookup("BF-CBC");
547 }
548
549 // data channel HMAC
550 {
551 const Option *o = opt.get_ptr("auth");
552 if (o)
553 {
554 const std::string &auth_name = o->get(1, 128);
555 if (auth_name != "none")
556 digest = CryptoAlgs::lookup(auth_name);
557 }
558 else
559 digest = CryptoAlgs::lookup("SHA1");
560 }
561 dc.set_cipher(cipher);
562 dc.set_digest(digest);
563
564 // tls-auth
565 {
566 const Option *o = opt.get_ptr(relay_prefix("tls-auth"));
567 if (o)
568 {
569 if (!server && tls_crypt_context)
570 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-auth and tls-crypt are mutually exclusive");
571
572 tls_auth_key.parse(o->get(1, 0));
573
574 const Option *tad = opt.get_ptr(relay_prefix("tls-auth-digest"));
575 if (tad)
576 digest = CryptoAlgs::lookup(tad->get(1, 128));
577 if (digest != CryptoAlgs::NONE)
578 set_tls_auth_digest(digest);
579 }
580 }
581
582 // tls-crypt
583 {
584 const Option *o = opt.get_ptr(relay_prefix("tls-crypt"));
585 if (o)
586 {
587 if (!server && tls_auth_context)
588 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-auth and tls-crypt are mutually exclusive");
590 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-crypt and tls-crypt-v2 are mutually exclusive");
591
593 tls_crypt_key.parse(o->get(1, 0));
594
596 }
597 }
598
599 // tls-crypt-v2
600 {
601 const Option *o = opt.get_ptr(relay_prefix("tls-crypt-v2"));
602 if (o)
603 {
604 if (!server && tls_auth_context)
605 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-auth and tls-crypt-v2 are mutually exclusive");
607 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-crypt and tls-crypt-v2 are mutually exclusive");
608
609 // initialize tls_crypt_context
611
612 std::string keyfile = o->get(1, 0);
613
614 if (opt.exists("client"))
615 {
616 // in client mode expect the key to be a PEM encoded tls-crypt-v2 client key (key + WKc)
617 TLSCryptV2ClientKey tls_crypt_v2_key(tls_crypt_context);
618 tls_crypt_v2_key.parse(keyfile);
619 tls_crypt_v2_key.extract_key(tls_crypt_key);
620 tls_crypt_v2_key.extract_wkc(wkc);
621 }
622 else
623 {
625 {
626 // in server mode this is a PEM encoded tls-crypt-v2 server key
627 TLSCryptV2ServerKey tls_crypt_v2_key;
628 tls_crypt_v2_key.parse(keyfile);
629 tls_crypt_v2_key.extract_key(tls_crypt_key);
630 }
631 }
633 }
634 }
635 }
636
637 // key-direction
638 {
639 if (key_direction >= -1 && key_direction <= 1)
640 {
641 const Option *o = opt.get_ptr(relay_prefix("key-direction"));
642 if (o)
643 {
644 const std::string &dir = o->get(1, 16);
645 if (dir == "0")
646 key_direction = 0;
647 else if (dir == "1")
648 key_direction = 1;
649 else if (dir == "bidirectional" || dir == "bi")
650 key_direction = -1;
651 else
652 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "bad key-direction parameter");
653 }
654 }
655 else
656 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "bad key-direction default");
657 }
658
659 // compression
660 {
661 const Option *o = opt.get_ptr("compress");
662 if (o)
663 {
664 if (o->size() >= 2)
665 {
666 const std::string meth_name = o->get(1, 128);
668 if (meth == CompressContext::NONE)
669 OPENVPN_THROW_ARG1(proto_option_error, ERR_INVALID_OPTION_VAL, "Unknown compressor: '" << meth_name << '\'');
671 }
672 else
674 }
675 else
676 {
677 o = opt.get_ptr("comp-lzo");
678 if (o)
679 {
680 if (o->size() == 2 && o->ref(1) == "no")
681 {
682 // On the client, by using ANY instead of ANY_LZO, we are telling the server
683 // that it's okay to use any of our supported compression methods.
685 }
686 else
687 {
689 }
690 }
691 }
692 }
693
694 // tun-mtu
697
698 // mssfix
699 mss_parms.parse(opt, true);
701 {
703 {
705 mss_parms.mtu = true;
706 }
707 else
708 {
710 mss_parms.fixed = true;
711 }
712 }
713
714 // mssfix-ctrl: cap on the wrapped size of control channel packets
716
717 // load parameters that can be present in both config file or pushed options
719 }
720
730
731 // load options string pushed by server
733 {
734 // data channel
736
737 // protocol-flags
739
740 // compression
741 parse_pushed_compression(opt, pco);
742
743 // peer ID
745
746 // custom app control channel options
748
749 try
750 {
751 // load parameters that can be present in both config file or pushed options
753 }
754 catch (const std::exception &e)
755 {
756 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed parameter: " << e.what());
757 }
758
759 // show negotiated options
761 }
762
764 {
765 try
766 {
767 const Option *o = opt.get_ptr("custom-control");
768 if (o)
769 {
770 app_control_config.max_msg_size = o->get_num(1, 1, std::numeric_limits<int>::max());
771 const auto &flags = o->get(2, 1024);
772 const auto &protocols = o->get(3, 1024);
774
776
777 /* This implementation always wants to have at least both base64 and text encoding */
779 {
780 OPENVPN_LOG("Warning: custom app control requires base64 encoding to properly work");
781 }
782 }
783 }
784 catch (const std::exception &e)
785 {
786 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed parameter: " << e.what());
788 }
789 }
790
792 {
793 // cipher
794 std::string new_cipher;
795 try
796 {
797 const Option *o = opt.get_ptr("cipher");
798 if (o)
799 {
800 new_cipher = o->get(1, 128);
801 if (new_cipher != "none")
802 dc.set_cipher(CryptoAlgs::lookup(new_cipher));
803 }
804 }
805 catch (const std::exception &e)
806 {
807 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed cipher '" << new_cipher << "': " << e.what());
808 }
809
810 // digest
811 std::string new_digest;
812 try
813 {
814 const Option *o = opt.get_ptr("auth");
815 if (o)
816 {
817 new_digest = o->get(1, 128);
818 if (new_digest != "none")
819 dc.set_digest(CryptoAlgs::lookup(new_digest));
820 }
821 }
822 catch (const std::exception &e)
823 {
824 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed digest '" << new_digest << "': " << e.what());
825 }
826 }
827
829 {
830 try
831 {
832 const Option *o = opt.get_ptr("peer-id");
833 if (o)
834 {
835 bool status = parse_number_validate<int>(o->get(1, 16),
836 16,
837 -1,
838 0xFFFFFE,
840 if (!status)
841 throw Exception("parse/range issue");
842 enable_op32 = true;
843 }
844 }
845 catch (const std::exception &e)
846 {
847 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed peer-id: " << e.what());
848 }
849 }
850
852 {
853 // tls key-derivation method with old key-derivation option
854 std::string key_method;
855 try
856 {
857 const Option *o = opt.get_ptr("key-derivation");
858 if (o)
859 {
860 key_method = o->get(1, 128);
861 if (key_method == "tls-ekm")
863 else
864 OPENVPN_THROW(process_server_push_error, "Problem accepting key-derivation method '" << key_method << "'");
865 }
866 else
868 }
869 catch (const std::exception &e)
870 {
871 OPENVPN_THROW(process_server_push_error, "Problem accepting key-derivation method '" << key_method << "': " << e.what());
872 }
873
874 try
875 {
876 const Option *o = opt.get_ptr("protocol-flags");
877 if (o)
878 {
879 o->min_args(2);
880 for (std::size_t i = 1; i < o->size(); i++)
881 {
882 std::string flag = o->get(i, 128);
883 if (flag == "cc-exit")
884 {
885 cc_exit_notify = true;
886 }
887 else if (flag == "dyn-tls-crypt")
888 {
890 }
891 else if (flag == "tls-ekm")
892 {
893 // Overrides "key-derivation" method set above
895 }
896 else if (flag == "aead-epoch")
897 {
899 }
900 else
901 {
902 OPENVPN_THROW(process_server_push_error, "unknown flag '" << flag << "'");
903 }
904 }
905 }
906 }
907 catch (const std::exception &e)
908 {
909 OPENVPN_THROW(process_server_push_error, "Problem accepting protocol-flags: " << e.what());
910 }
911 }
912
914 {
915 std::string new_comp;
916 try
917 {
918 const Option *o;
919 o = opt.get_ptr("compress");
920 if (o)
921 {
922 new_comp = o->get(1, 128);
924 if (meth != CompressContext::NONE)
925 {
926 // if compression is not availabe, CompressContext ctor throws an exception
927 if (pco.is_comp())
929 else
930 {
931 // server pushes compression but client has compression disabled
932 // degrade to asymmetric compression (downlink only)
933 comp_ctx = CompressContext(meth, true);
934 if (!comp_ctx.is_any_stub(meth))
935 {
936 OPENVPN_LOG("Server has pushed compressor "
937 << comp_ctx.str()
938 << ", but client has disabled compression, switching to asymmetric");
939 }
940 }
941 }
942 }
943 else
944 {
945 o = opt.get_ptr("comp-lzo");
946 if (o)
947 {
948 if (o->size() == 2 && o->ref(1) == "no")
949 {
951 }
952 else
953 {
955 }
956 }
957 }
958 }
959 catch (const std::exception &e)
960 {
961 OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed compressor '" << new_comp << "': " << e.what());
962 }
963 }
964
965 void get_data_channel_options(std::ostringstream &os) const
966 {
967 os << " data channel:";
968 os << " cipher " << CryptoAlgs::name(dc.cipher());
970 os << ", digest " << CryptoAlgs::name(dc.digest());
971
972 os << ", peer-id " << remote_peer_id;
973
974 if (dc.useEpochKeys())
975 os << ", aead-epoch";
976
977 os << '\n';
978 }
979
980 void show_cc_enc_option(std::ostringstream &os) const
981 {
982 if (tls_auth_enabled())
983 {
984 os << " control channel: tls-auth enabled\n";
985 }
987 {
988 os << " control channel: tls-crypt v2 enabled\n";
989 }
990 else if (tls_crypt_enabled())
991 {
992 os << " control channel: tls-crypt enabled\n";
993 }
994 else if (dynamic_tls_crypt_enabled())
995 {
996 os << " control channel: dynamic tls-crypt enabled\n";
997 }
998 }
999
1000 std::string show_options() const
1001 {
1002 std::ostringstream os;
1003 os << "PROTOCOL OPTIONS:\n";
1004 os << " key-derivation: " << CryptoAlgs::name(dc.key_derivation()) << '\n';
1006 os << " compress: " << comp_ctx.str() << '\n';
1007
1010
1012 {
1013 os << " app custom control channel: " << app_control_config.str() << '\n';
1014 }
1015
1016 return os.str();
1017 }
1018
1019 void set_protocol(const Protocol &p)
1020 {
1021 // adjust options for new transport protocol
1022 protocol = p;
1023 }
1024
1026 {
1028 }
1029
1031 {
1033 return;
1034
1035 auto digest = CryptoAlgs::lookup("SHA256");
1036 auto cipher = CryptoAlgs::lookup("AES-256-CTR");
1037
1038 if ((digest == CryptoAlgs::NONE) || (cipher == CryptoAlgs::NONE))
1039 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "missing support for tls-crypt algorithms");
1040
1041 /* TODO: we currently use the default SSL library context here as the
1042 * library context is not available this early. This should not matter
1043 * for the algorithms used by tls_crypt */
1044 tls_crypt_context = tls_crypt_factory->new_obj(nullptr, digest, cipher);
1045 }
1046
1047 void set_xmit_creds(const bool xmit_creds_arg)
1048 {
1049 xmit_creds = xmit_creds_arg;
1050 }
1051
1052 bool tls_auth_enabled() const
1053 {
1055 }
1056
1058 {
1060 }
1061
1066
1068 {
1069 return (tls_crypt_ & TLSCrypt::Dynamic);
1070 }
1071
1072 // generate a string summarizing options that will be
1073 // transmitted to peer for options consistency check
1074 std::string options_string()
1075 {
1076 if (!initial_options.empty())
1077 return initial_options;
1078
1079 std::ostringstream out;
1080
1081 const bool server = ssl_factory->mode().is_server();
1082 const unsigned int l2extra = (layer() == Layer::OSI_LAYER_2 ? 32 : 0);
1083
1084 out << "V4";
1085
1086 out << ",dev-type " << layer.dev_type();
1087 out << ",link-mtu " << tun_mtu + link_mtu_adjust() + l2extra;
1088 out << ",tun-mtu " << tun_mtu + l2extra;
1089 out << ",proto " << protocol.occ_str(server);
1090
1091 {
1092 const char *compstr = comp_ctx.options_string();
1093 if (compstr)
1094 out << ',' << compstr;
1095 }
1096
1097 if (tls_auth_context && (key_direction >= 0))
1098 out << ",keydir " << key_direction;
1099
1100 out << ",cipher " << CryptoAlgs::name(dc.cipher(), "[null-cipher]");
1101 out << ",auth " << CryptoAlgs::name(dc.digest(), "[null-digest]");
1102 out << ",keysize " << (CryptoAlgs::key_length(dc.cipher()) * 8);
1103
1104 if (tls_auth_context)
1105 out << ",tls-auth";
1106
1107 // sending tls-crypt does not make sense. If we got to this point it
1108 // means that tls-crypt was already there and it worked fine.
1109 // tls-auth has to be kept for backward compatibility as it is there
1110 // since a bit.
1111
1112 out << ",key-method 2";
1113
1114 if (server)
1115 out << ",tls-server";
1116 else
1117 out << ",tls-client";
1118
1119 initial_options = out.str();
1120
1121 return initial_options;
1122 }
1123
1129 {
1132 {
1133 /* check if the IV_HWADDR is already present in the extra_peer_info set as it has then been
1134 * statically been overridden */
1135 if (!extra_peer_info->contains_key("IV_HWADDR"))
1136 {
1137 std::string hwaddr = get_hwaddr(transport->server_endpoint_addr());
1138 if (!hwaddr.empty())
1139 extra_peer_info_transport->emplace_back("IV_HWADDR", hwaddr);
1140 }
1141 }
1142 }
1143
1144 // generate a string summarizing information about the client
1145 // including capabilities
1146 std::string peer_info_string(bool supports_epoch_data) const
1147 {
1148 std::ostringstream out;
1149 const char *compstr = nullptr;
1150
1151 // supports op32 and P_DATA_V2 and expects a push reply
1152 unsigned int iv_proto = IV_PROTO_DATA_V2
1159
1160 if (supports_epoch_data)
1161 iv_proto |= IV_PROTO_DATA_EPOCH;
1162
1163 if (CryptoAlgs::lookup("SHA256") != CryptoAlgs::NONE && CryptoAlgs::lookup("AES-256-CTR") != CryptoAlgs::NONE)
1164 iv_proto |= IV_PROTO_DYN_TLS_CRYPT;
1165
1166 if (SSLLib::SSLAPI::support_key_material_export())
1167 {
1168 iv_proto |= IV_PROTO_TLS_KEY_EXPORT;
1169 }
1170
1171 out << "IV_VER=" << OPENVPN_VERSION << '\n';
1172 out << "IV_PLAT=" << platform_name() << '\n';
1173 out << "IV_NCP=2\n"; // negotiable crypto parameters V2
1174 out << "IV_TCPNL=1\n"; // supports TCP non-linear packet ID
1175 out << "IV_PROTO=" << iv_proto << '\n';
1176 out << "IV_MTU=" << tun_mtu_max << "\n";
1177 /*
1178 * OpenVPN3 allows to be pushed any cipher that it supports as it
1179 * only implements secure ones and BF-CBC for backwards
1180 * compatibility and generally adopts the concept of the server being
1181 * responsible for sensible choices. Include the cipher here since
1182 * OpenVPN 2.5 will otherwise ignore it and break on conrer cases
1183 * like --cipher AES-128-CBC on client and --data-ciphers "AES-128-CBC"
1184 * on server.
1185 *
1186 */
1187 out << "IV_CIPHERS=";
1189 [&out](CryptoAlgs::Type type, const CryptoAlgs::Alg &alg) -> bool
1190 {
1191 if (!alg.dc_cipher())
1192 return false;
1193 out << alg.name() << ':';
1194 return true;
1195 });
1196 out.seekp(-1, std::ios_base::cur);
1197 out << "\n";
1198
1199 compstr = comp_ctx.peer_info_string();
1200
1201 if (compstr)
1202 out << compstr;
1203 if (extra_peer_info)
1204 out << extra_peer_info->to_string();
1206 out << extra_peer_info_transport->to_string();
1207 if (is_bs64_cipher(dc.cipher()))
1208 out << "IV_BS64DL=1\n"; // indicate support for data limits when using 64-bit block-size ciphers, version 1 (CVE-2016-6329)
1209 if (relay_mode)
1210 out << "IV_RELAY=1\n";
1211
1212
1213 const std::string ret = out.str();
1214 OVPN_LOG_INFO("Sending Peer Info:\n"
1215 << ret);
1216 return ret;
1217 }
1218
1219 // Used to generate link_mtu option sent to peer.
1220 // Not const because dc.context() caches the DC context.
1221 unsigned int link_mtu_adjust()
1222 {
1223 size_t dc_overhead;
1224 if (dc.cipher() == CryptoAlgs::BF_CBC)
1225 {
1226 /* since often configuration lack BF-CBC, we hardcode the overhead for BF-CBC to avoid
1227 * trying to load BF-CBC, which is not available anymore in modern crypto libraries */
1228 dc_overhead = CryptoAlgs::size(dc.digest()) // HMAC
1229 + 64 / 8 // Cipher IV
1230 + 64 / 8; // worst-case PKCS#7 padding expansion (blocksize)
1231 }
1232 else
1233 {
1234 dc_overhead = dc.context().encap_overhead();
1235 }
1236 const size_t adj = protocol.extra_transport_bytes() + // extra 2 bytes for TCP-streamed packet length
1237 (enable_op32 ? 4 : 1) + // leading op
1238 comp_ctx.extra_payload_bytes() + // compression header
1239 PacketIDData::size(false) + // sequence number
1240 dc_overhead; // data channel crypto layer overhead
1241 return (unsigned int)adj;
1242 }
1243
1244 private:
1251
1252 // load parameters that can be present in both config file or pushed options
1253 void load_common(const OptionList &opt,
1255 const LoadCommonType type)
1256 {
1257 // duration parms
1258 load_duration_parm(renegotiate, "reneg-sec", opt, 10, false, false);
1260 load_duration_parm(expire, "tran-window", opt, 10, false, false);
1262 load_duration_parm(handshake_window, "hand-window", opt, 10, false, false);
1263 if (is_bs64_cipher(dc.cipher())) // special data limits for 64-bit block-size ciphers (CVE-2016-6329)
1264 {
1265 become_primary = Time::Duration::seconds(5);
1266 tls_timeout = Time::Duration::milliseconds(1000);
1267 }
1268 else
1269 become_primary = Time::Duration::seconds(std::min(handshake_window.to_seconds(),
1270 renegotiate.to_seconds() / 2));
1271 load_duration_parm(become_primary, "become-primary", opt, 0, false, false);
1272 load_duration_parm(tls_timeout, "tls-timeout", opt, 100, false, true);
1273
1274 if (type == LOAD_COMMON_SERVER)
1275 renegotiate += handshake_window; // avoid renegotiation collision with client
1276
1277 // keepalive, ping, ping-restart
1278 {
1279 const Option *o = opt.get_ptr("keepalive");
1280 if (o)
1281 {
1282 set_duration_parm(keepalive_ping, "keepalive ping", o->get(1, 16), 1, false, false);
1283 set_duration_parm(keepalive_timeout, "keepalive timeout", o->get(2, 16), 1, type == LOAD_COMMON_SERVER, false);
1284
1285 if (o->size() >= 4)
1286 set_duration_parm(keepalive_timeout_early, "keepalive timeout early", o->get(3, 16), 1, false, false);
1287 else
1289 }
1290 else
1291 {
1292 load_duration_parm(keepalive_ping, "ping", opt, 1, false, false);
1293 load_duration_parm(keepalive_timeout, "ping-restart", opt, 1, false, false);
1294 }
1295 }
1296
1297 if ((type == LOAD_COMMON_CLIENT) || (type == LOAD_COMMON_CLIENT_PUSHED))
1298 {
1299 auth_nocache = opt.exists("auth-nocache");
1300 }
1301 }
1302
1303 std::string relay_prefix(const char *optname) const
1304 {
1305 std::string ret;
1306 if (relay_mode)
1307 ret = "relay-";
1308 ret += optname;
1309 return ret;
1310 }
1311 };
1312
1313 // Used to describe an incoming network packet
1315 {
1316 friend class ProtoContext;
1317
1318 enum
1319 {
1320 DEFINED = 1 << 0, // packet is valid (otherwise invalid)
1321 CONTROL = 1 << 1, // packet for control channel (otherwise for data channel)
1322 SECONDARY = 1 << 2, // packet is associated with secondary KeyContext (otherwise primary)
1323 SOFT_RESET = 1 << 3, // packet is a CONTROL_SOFT_RESET_V1 msg indicating a request for SSL/TLS renegotiate
1324 };
1325
1326 public:
1327 bool is_defined() const
1328 {
1329 return flags & DEFINED;
1330 }
1331 bool is_control() const
1332 {
1333 return (flags & (CONTROL | DEFINED)) == (CONTROL | DEFINED);
1334 }
1335 bool is_data() const
1336 {
1337 return (flags & (CONTROL | DEFINED)) == DEFINED;
1338 }
1339 bool is_soft_reset() const
1340 {
1341 return (flags & (CONTROL | DEFINED | SECONDARY | SOFT_RESET))
1343 }
1344 int peer_id() const
1345 {
1346 return peer_id_;
1347 }
1348
1349 private:
1350 PacketType(const Buffer &buf, class ProtoContext &proto)
1352 {
1353 if (likely(buf.size()))
1354 {
1355 // get packet header byte
1356 const unsigned int op = buf[0];
1357
1358 // examine opcode
1359 {
1360 const unsigned int opc = opcode_extract(op);
1361 switch (opc)
1362 {
1364 case CONTROL_V1:
1365 case ACK_V1:
1366 {
1367 flags |= CONTROL;
1368 opcode = opc;
1369 break;
1370 }
1371 case DATA_V2:
1372 {
1373 if (unlikely(buf.size() < 4))
1374 return;
1375 std::uint32_t opi;
1376 // avoid unaligned access
1377 std::memcpy(&opi, buf.c_data(), sizeof(opi));
1378 opi = ntohl(opi) & 0x00FFFFFF;
1379 if (opi != OP_PEER_ID_UNDEF)
1380 peer_id_ = opi;
1381 opcode = opc;
1382 break;
1383 }
1384 case DATA_V1:
1385 {
1386 opcode = opc;
1387 break;
1388 }
1391 {
1392 if (!proto.is_server())
1393 return;
1394 flags |= CONTROL;
1395 opcode = opc;
1396 break;
1397 }
1399 if (proto.is_server())
1400 return;
1401 [[fallthrough]];
1402 case CONTROL_WKC_V1:
1403 {
1404 flags |= CONTROL;
1405 opcode = opc;
1406 break;
1407 }
1408 default:
1409 return;
1410 }
1411 }
1412
1413 // examine key ID
1414 {
1415 const unsigned int kid = key_id_extract(op);
1416 if (proto.primary && kid == proto.primary->key_id())
1417 flags |= DEFINED;
1418 else if (proto.secondary && kid == proto.secondary->key_id())
1419 flags |= (DEFINED | SECONDARY);
1420 else if (opcode == CONTROL_SOFT_RESET_V1 && kid == proto.upcoming_key_id)
1422 }
1423 }
1424 }
1425
1426 unsigned int flags;
1427 unsigned int opcode;
1429 };
1430
1431 static const char *opcode_name(const unsigned int opcode)
1432 {
1433 switch (opcode)
1434 {
1436 return "CONTROL_SOFT_RESET_V1";
1437 case CONTROL_V1:
1438 return "CONTROL_V1";
1439 case ACK_V1:
1440 return "ACK_V1";
1441 case DATA_V1:
1442 return "DATA_V1";
1443 case DATA_V2:
1444 return "DATA_V2";
1446 return "CONTROL_HARD_RESET_CLIENT_V2";
1448 return "CONTROL_HARD_RESET_CLIENT_V3";
1450 return "CONTROL_HARD_RESET_SERVER_V2";
1451 case CONTROL_WKC_V1:
1452 return "CONTROL_WKC_V1";
1453 }
1454 return nullptr;
1455 }
1456
1457 std::string dump_packet(const Buffer &buf)
1458 {
1459 std::ostringstream out;
1460 try
1461 {
1462 Buffer b(buf);
1463 const size_t orig_size = b.size();
1464 const unsigned int op = b.pop_front();
1465
1466 const unsigned int opcode = opcode_extract(op);
1467 const char *op_name = opcode_name(opcode);
1468 if (op_name)
1469 out << op_name << '/' << key_id_extract(op);
1470 else
1471 return "BAD_PACKET";
1472
1473 if (opcode == DATA_V1 || opcode == DATA_V2)
1474 {
1475 if (opcode == DATA_V2)
1476 {
1477 const unsigned int p1 = b.pop_front();
1478 const unsigned int p2 = b.pop_front();
1479 const unsigned int p3 = b.pop_front();
1480 const unsigned int peer_id = (p1 << 16) + (p2 << 8) + p3;
1481 if (peer_id != 0xFFFFFF)
1482 out << " PEER_ID=" << peer_id;
1483 }
1484 out << " SIZE=" << b.size() << '/' << orig_size;
1485 }
1486 else
1487 {
1488 {
1489 ProtoSessionID src_psid(b);
1490 out << " SRC_PSID=" << src_psid.str();
1491 }
1492
1494 {
1495 PacketIDControl pid;
1496 pid.read(b);
1497 out << " PID=" << pid.str();
1498
1499 const unsigned char *hmac = b.read_alloc(hmac_size);
1500 out << " HMAC=" << render_hex(hmac, hmac_size);
1501 out << " TLS-CRYPT ENCRYPTED PAYLOAD=" << b.size() << " bytes";
1502 }
1503 else
1504 {
1505 if (tls_wrap_mode == TLS_AUTH)
1506 {
1507 const unsigned char *hmac = b.read_alloc(hmac_size);
1508 out << " HMAC=" << render_hex(hmac, hmac_size);
1509
1510 PacketIDControl pid;
1511 pid.read(b);
1512 out << " PID=" << pid.str();
1513 }
1514
1515 ReliableAck ack{};
1516 ack.read(b);
1517 const bool dest_psid_defined = !ack.empty();
1518 out << " ACK=[";
1519 while (!ack.empty())
1520 {
1521 out << " " << ack.front();
1522 ack.pop_front();
1523 }
1524 out << " ]";
1525
1526 if (dest_psid_defined)
1527 {
1528 ProtoSessionID dest_psid(b);
1529 out << " DEST_PSID=" << dest_psid.str();
1530 }
1531
1532 if (opcode != ACK_V1)
1533 out << " MSG_ID=" << ReliableAck::read_id(b);
1534
1535 out << " SIZE=" << b.size() << '/' << orig_size;
1536 }
1537 }
1538#ifdef OPENVPN_DEBUG_PROTO_DUMP
1539 out << '\n'
1541#endif
1542 }
1543 catch (const std::exception &e)
1544 {
1545 out << " EXCEPTION: " << e.what();
1546 }
1547 return out.str();
1548 }
1549
1550 // used for reading/writing authentication strings (username, password, etc.) from buffer using the
1551 // 2 byte prefix for length
1552 static void write_uint16_length(const size_t size, Buffer &buf)
1553 {
1554 if (size > 0xFFFF)
1555 throw proto_error("auth_string_overflow");
1556 const std::uint16_t net_size = htons(static_cast<std::uint16_t>(size));
1557 buf.write((const unsigned char *)&net_size, sizeof(net_size));
1558 }
1559
1560 static uint16_t read_uint16_length(Buffer &buf)
1561 {
1562 if (!buf.empty())
1563 {
1564 std::uint16_t net_size;
1565 buf.read((unsigned char *)&net_size, sizeof(net_size));
1566 return ntohs(net_size);
1567 }
1568 return 0;
1569 }
1570
1571 template <typename S>
1572 static void write_auth_string(const S &str, Buffer &buf)
1573 {
1574 const size_t len = str.length();
1575 if (len)
1576 {
1577 write_uint16_length(len + 1, buf);
1578 buf.write((const unsigned char *)str.c_str(), len);
1579 buf.null_terminate();
1580 }
1581 else
1582 write_uint16_length(0, buf);
1583 }
1584
1585 template <typename S>
1587 {
1588 const size_t len = read_uint16_length(buf);
1589 if (len)
1590 {
1591 const char *data = (const char *)buf.read_alloc(len);
1592 if (len > 1)
1593 return S(data, len - 1);
1594 }
1595 return S();
1596 }
1597
1598 template <typename S>
1599 static void write_control_string(const S &str, Buffer &buf)
1600 {
1601 const size_t len = str.length();
1602 buf.write((const unsigned char *)str.c_str(), len);
1603 buf.null_terminate();
1604 }
1605
1606 static void write_empty_string(Buffer &buf)
1607 {
1608 write_uint16_length(0, buf);
1609 }
1610
1611 template <typename S>
1612 static S read_control_string(const Buffer &buf)
1613 {
1614 size_t size = buf.size();
1615 if (size)
1616 {
1617 /* Trim any trailing \n or \r or 0x00 characters. Scripts plugin sometimes accidentally include a \n or \r\n in AUTH_FAILED
1618 * or similar messages */
1619 while (size > 0 && (buf[size - 1] == 0 || buf[size - 1] == '\r' || buf[size - 1] == '\n'))
1620 {
1621 --size;
1622 }
1623
1624 if (size)
1625 {
1626 return S{reinterpret_cast<const char *>(buf.c_data()), size};
1627 }
1628 }
1629 return {};
1630 }
1631
1632 template <typename S>
1633 void write_control_string(const S &str)
1634 {
1635 const size_t len = str.length();
1636 auto bp = BufferAllocatedRc::Create(len + 1);
1637 write_control_string(str, *bp);
1638 control_send(std::move(bp));
1639 }
1640
1641 // Packet structure for managing network packets, passed as a template
1642 // parameter to ProtoStackBase
1644 {
1645 friend class ProtoContext;
1646
1647 public:
1649 {
1650 reset_non_buf();
1651 }
1652
1653 Packet(BufferPtr &&buf_arg, const unsigned int opcode_arg = CONTROL_V1)
1654 : opcode(opcode_arg), buf(std::move(buf_arg))
1655 {
1656 }
1657
1658 // clone packet, including buffer content
1660 {
1661 Packet pkt;
1662 pkt.opcode = opcode;
1664 return pkt;
1665 }
1666
1667 void reset()
1668 {
1669 reset_non_buf();
1670 buf.reset();
1671 }
1672
1673 void frame_prepare(const Frame &frame, const unsigned int context)
1674 {
1675 if (!buf)
1677 frame.prepare(context, *buf);
1678 }
1679
1685 {
1686 return opcode == CONTROL_V1 || opcode == CONTROL_WKC_V1;
1687 }
1688 operator bool() const
1689 {
1690 return bool(buf);
1691 }
1693 {
1694 return buf;
1695 }
1696 const Buffer &buffer() const
1697 {
1698 return *buf;
1699 }
1700
1701 private:
1703 {
1705 }
1706
1707 unsigned int opcode;
1709 };
1710
1711 // ---- standalone control-channel wrapping -----------------------------------
1712 // The framing/protection of an outgoing control packet, factored out of
1713 // KeyContext so it can also wrap packets that belong to no established session
1714 // (e.g. an out-of-band SERVER_PROBE). These are pure functions of the crypto
1715 // context + the caller's session id / packet-id / key-id; KeyContext::gen_head_*
1716 // delegate here with their own state, so on-wire behaviour is unchanged.
1717
1724 static bool opcode_carries_wkc(const unsigned int opcode)
1725 {
1726 return opcode == CONTROL_HARD_RESET_CLIENT_V3 || opcode == CONTROL_WKC_V1;
1727 }
1728
1730 static void wrap_tls_auth(const unsigned int opcode,
1731 Buffer &buf,
1732 PacketIDControlSend &pid_send,
1733 const PacketIDControl::time_t now_secs,
1734 const size_t hmac_size,
1736 const unsigned int key_id,
1738 {
1739 pid_send.write_next(buf, true, now_secs);
1741 psid_self.prepend(buf);
1742 buf.push_front(op_compose(opcode, key_id));
1743 ta_hmac_send.ovpn_hmac_gen(buf.data(),
1744 buf.size(),
1746 hmac_size,
1748 }
1749
1756 static void wrap_tls_crypt(const unsigned int opcode,
1757 BufferAllocated &buf,
1759 Frame &frame,
1760 PacketIDControlSend &pid_send,
1761 const PacketIDControl::time_t now_secs,
1762 const size_t hmac_size,
1764 const unsigned int key_id,
1766 const Buffer *wkc)
1767 {
1768 // header fields that are not encrypted go into 'work'
1770 work.prepend_alloc(hmac_size);
1771 pid_send.write_next(work, true, now_secs);
1773 work.push_front(op_compose(opcode, key_id));
1774
1775 // HMAC over header fields (from 'work') and plaintext payload (from 'buf')
1776 tls_crypt_send.hmac_gen(work.data(), TLSCryptContext::hmac_offset, buf.c_data(), buf.size());
1777
1778 const size_t data_offset = TLSCryptContext::hmac_offset + hmac_size;
1779 const size_t encrypt_bytes = tls_crypt_send.encrypt(work.c_data() + TLSCryptContext::hmac_offset,
1780 work.data() + data_offset,
1781 work.max_size() - data_offset,
1782 buf.c_data(),
1783 buf.size());
1784 if (!encrypt_bytes)
1785 {
1786 buf.reset_size();
1787 return;
1788 }
1789 work.inc_size(encrypt_bytes);
1790
1791 // append the WKc: opcode_carries_wkc() covers the in-session handshake
1792 // packets, and an OOB probe carries one too (it has no session to key)
1793 if ((opcode_carries_wkc(opcode) || opcode == CONTROL_OOB_WKC_V1) && wkc)
1794 {
1795 if (!wkc->defined())
1796 throw proto_error("Client Key Wrapper undefined");
1797 work.append(*wkc);
1798 }
1799
1800 // 'work' now holds the complete packet; swap it into 'buf'
1801 buf.swap(work);
1802 }
1803
1805 static void wrap_tls_plain(const unsigned int opcode,
1806 Buffer &buf,
1808 const unsigned int key_id)
1809 {
1810 psid_self.prepend(buf);
1811 buf.push_front(op_compose(opcode, key_id));
1812 }
1813
1814 // Result of the crypto/framing half of decapsulating a control packet. The
1815 // caller maps the error cases to stats/invalidate and OK to further session
1816 // processing; DROP is a silent, non-error discard (malformed/too-short).
1817 enum class UnwrapStatus
1818 {
1819 OK,
1820 DROP,
1821 HMAC_ERROR,
1823 };
1824
1831 const size_t hmac_size,
1833 const PacketIDControlReceive &pid_recv,
1834 ProtoSessionID &src_psid,
1835 PacketIDControl &pid)
1836 {
1837 const unsigned char *orig_data = recv.data();
1838 const size_t orig_size = recv.size();
1839
1840 recv.advance(1); // past initial op byte
1841 src_psid.read(recv);
1842 recv.advance(hmac_size);
1843 if (!ta_hmac_recv.ovpn_hmac_cmp(orig_data,
1844 orig_size,
1846 hmac_size,
1849
1850 pid = pid_recv.read_next(recv);
1851 return UnwrapStatus::OK;
1852 }
1853
1861 Frame &frame,
1862 const size_t hmac_size,
1864 const PacketIDControlReceive &pid_recv,
1865 ProtoSessionID &src_psid,
1866 PacketIDControl &pid)
1867 {
1868 const unsigned char *orig_data = recv.data();
1869 const size_t orig_size = recv.size();
1870
1871 recv.advance(1); // past initial op byte
1872 src_psid.read(recv);
1873 pid = pid_recv.read_next(recv);
1874 recv.advance(hmac_size); // skip the hmac
1875
1876 const size_t data_offset = TLSCryptContext::hmac_offset + hmac_size;
1877 if (orig_size < data_offset)
1878 return UnwrapStatus::DROP;
1879
1881 const size_t decrypt_bytes = tls_crypt_recv.decrypt(orig_data + TLSCryptContext::hmac_offset,
1882 work.data(),
1883 work.max_size(),
1884 recv.c_data(),
1885 recv.size());
1886 if (!decrypt_bytes)
1888 work.inc_size(decrypt_bytes);
1889
1890 if (!tls_crypt_recv.hmac_cmp(orig_data, TLSCryptContext::hmac_offset, work.c_data(), work.size()))
1892
1893 // plaintext is now in 'work'; swap it into 'recv' for further processing
1894 recv.swap(work);
1895 return UnwrapStatus::OK;
1896 }
1897
1898 // ---- standalone construction of the control-channel protection contexts -----
1899 // The crypto instances a control packet is wrapped/unwrapped with, factored out
1900 // of reset()/reset_tls_crypt() so they can be built directly from a ProtoConfig
1901 // for a packet that belongs to no session (e.g. an out-of-band probe). Behaviour
1902 // is identical to the in-session setup; the session path delegates here.
1903
1908 static void build_tls_auth(const ProtoConfig &c,
1911 {
1912 send = c.tls_auth_context->new_obj();
1913 recv = c.tls_auth_context->new_obj();
1914 if (c.key_direction >= 0)
1915 {
1916 // key-direction is 0 or 1
1917 const unsigned int key_dir = c.key_direction ? OpenVPNStaticKey::INVERSE : OpenVPNStaticKey::NORMAL;
1920 }
1921 else
1922 {
1923 // key-direction bidirectional mode
1926 }
1927 }
1928
1933 static void build_tls_crypt(const ProtoConfig &c,
1934 const bool server,
1935 const OpenVPNStaticKey &key,
1938 {
1939 send = c.tls_crypt_context->new_obj_send();
1940 recv = c.tls_crypt_context->new_obj_recv();
1941
1942 // static direction assignment - not user configurable
1943 const unsigned int key_dir = server ? OpenVPNStaticKey::NORMAL : OpenVPNStaticKey::INVERSE;
1944
1945 send->init(c.ssl_factory->libctx(),
1948 recv->init(c.ssl_factory->libctx(),
1951 }
1952
1953 private:
1954 // TLS wrapping mode for the control channel
1962
1969
1973 {
1974 if (c.tls_crypt_v2_enabled() && !c.tls_auth_enabled())
1975 return {.mode = TLS_CRYPT_V2, .hmac_size = c.tls_crypt_context->digest_size()};
1976 if (c.tls_crypt_enabled() && !c.tls_auth_enabled())
1977 return {.mode = TLS_CRYPT, .hmac_size = c.tls_crypt_context->digest_size()};
1978 if (c.tls_auth_enabled())
1979 return {.mode = TLS_AUTH, .hmac_size = c.tls_auth_context->size()};
1980 return {.mode = TLS_PLAIN, .hmac_size = 0};
1981 }
1982
1983 public:
1996 {
1997 public:
2000 : config(config_arg)
2001 {
2002 const ProtoConfig &c = *config;
2003
2004 const TLSWrapSelection sel = select_tls_wrap(c);
2005 mode = sel.mode;
2006 hmac_size = sel.hmac_size;
2007
2008 switch (mode)
2009 {
2010 case TLS_AUTH:
2012 break;
2013 case TLS_CRYPT:
2014 case TLS_CRYPT_V2:
2015 // the probe is sent by the client, so build with the client role
2017 break;
2018 case TLS_PLAIN:
2019 break;
2020 }
2021
2022 ta_pid_send.init();
2023 ta_pid_recv.init("OOB-PROBE", 0, stats);
2024
2026 }
2027
2030 {
2031 return psid_self;
2032 }
2033
2041 {
2042 const PacketIDControl::time_t now_secs = config->now->seconds_since_epoch();
2043 switch (mode)
2044 {
2045 case TLS_AUTH:
2047 break;
2048 case TLS_CRYPT:
2050 break;
2051 case TLS_CRYPT_V2:
2053 break;
2054 case TLS_PLAIN:
2056 break;
2057 }
2058 }
2059
2071 ProtoSessionID &src_psid,
2072 PacketIDControl &pid)
2073 {
2074 // The unwrap helpers walk the fixed header -- opcode, psid, packet id and
2075 // hmac, whose order differs per mode but not its size --
2076 // with advance()/read(), which throw on a short buffer. In a session
2077 // that is caught upstream, but a probe reply is parsed inside the
2078 // prober's asio receive handler, where an exception has nowhere to go.
2079 // Drop anything too small to hold the header instead.
2080 const size_t header_size = OPCODE_SIZE + ProtoSessionID::SIZE + PacketIDControl::size() + hmac_size;
2081
2082 switch (mode)
2083 {
2084 case TLS_AUTH:
2085 if (recv.size() < header_size)
2086 return UnwrapStatus::DROP;
2087 return unwrap_tls_auth(recv, hmac_size, *ta_hmac_recv, ta_pid_recv, src_psid, pid);
2088 case TLS_CRYPT:
2089 case TLS_CRYPT_V2:
2090 if (recv.size() < header_size)
2091 return UnwrapStatus::DROP;
2092 return unwrap_tls_crypt(recv, work, *config->frame, hmac_size, *tls_crypt_recv, ta_pid_recv, src_psid, pid);
2093 case TLS_PLAIN:
2094 // plaintext control channel: [op][psid][payload]
2095 if (recv.size() < OPCODE_SIZE + ProtoSessionID::SIZE)
2096 return UnwrapStatus::DROP;
2097 recv.advance(OPCODE_SIZE);
2098 src_psid.read(recv);
2099 return UnwrapStatus::OK;
2100 }
2101 return UnwrapStatus::DROP;
2102 }
2103
2104 private:
2105 static constexpr unsigned int KEY_ID = 0;
2106
2109 size_t hmac_size = 0;
2110
2115
2119 };
2120
2121 // KeyContext encapsulates a single SSL/TLS session.
2122 // ProtoStackBase uses CRTP-based static polymorphism for method callbacks.
2123 class KeyContext : ProtoStackBase<Packet, KeyContext>, public RC<thread_unsafe_refcount>
2124 {
2126 friend Base;
2127#ifdef UNIT_TEST
2128 // test seam: lets ProtoContext::force_resend_wkc() set resend_wkc
2129 friend class ProtoContext;
2130#endif
2133
2134 // ProtoStackBase protected vars
2135 using Base::now;
2136 using Base::rel_recv;
2137 using Base::rel_send;
2138 using Base::xmit_acks;
2139
2140 // ProtoStackBase member functions
2141 using Base::raw_send;
2144
2145 // Helper for handling deferred data channel setup,
2146 // for example if cipher/digest are pushed.
2148 {
2150 std::optional<CryptoDCInstance::RekeyType> rekey_type;
2151 };
2152
2153 public:
2155
2156 // ProtoStackBase member functions
2158
2159 OPENVPN_SIMPLE_EXCEPTION(tls_crypt_unwrap_wkc_error);
2160
2161 // KeyContext events occur on two basic key types:
2162 // Primary Key -- the key we transmit/encrypt on.
2163 // Secondary Key -- new keys and retiring keys.
2164 //
2165 // The very first key created (key_id == 0) is a
2166 // primary key. Subsequently created keys are always,
2167 // at least initially, secondary keys. Secondary keys
2168 // promote to primary via the KEV_BECOME_PRIMARY event
2169 // (actually KEV_BECOME_PRIMARY swaps the primary and
2170 // secondary keys, so the old primary is demoted
2171 // to secondary and marked for expiration).
2172 //
2173 // Secondary keys are created by:
2174 // 1. locally-generated soft renegotiation requests, and
2175 // 2. peer-requested soft renegotiation requests.
2176 // In each case, any previous secondary key will be
2177 // wiped (including a secondary key that exists due to
2178 // demotion of a previous primary key that has been marked
2179 // for expiration).
2181 {
2183
2184 // KeyContext has reached the ACTIVE state, occurs on both
2185 // primary and secondary.
2187
2188 // SSL/TLS negotiation must complete by this time. If this
2189 // event is hit on the first primary (i.e. first KeyContext
2190 // with key_id == 0), it is fatal to the session and will
2191 // trigger a disconnect/reconnect. If it's hit on the
2192 // secondary, it will trigger a soft renegotiation.
2194
2195 // When a KeyContext (normally the secondary) is scheduled
2196 // to transition to the primary state.
2198
2199 // Waiting for condition on secondary (usually
2200 // dataflow-based) to trigger KEV_BECOME_PRIMARY.
2202
2203 // Start renegotiating a new KeyContext on secondary
2204 // (ignored unless originating on primary).
2206
2207 // Trigger a renegotiation originating from either
2208 // primary or secondary.
2210
2211 // Queue delayed renegotiation request from secondary
2212 // to take effect after KEV_BECOME_PRIMARY.
2214
2215 // Expiration of KeyContext.
2217 };
2218
2219 // for debugging
2220 static const char *event_type_string(const EventType et)
2221 {
2222 switch (et)
2223 {
2224 case KEV_NONE:
2225 return "KEV_NONE";
2226 case KEV_ACTIVE:
2227 return "KEV_ACTIVE";
2228 case KEV_NEGOTIATE:
2229 return "KEV_NEGOTIATE";
2230 case KEV_BECOME_PRIMARY:
2231 return "KEV_BECOME_PRIMARY";
2233 return "KEV_PRIMARY_PENDING";
2234 case KEV_RENEGOTIATE:
2235 return "KEV_RENEGOTIATE";
2237 return "KEV_RENEGOTIATE_FORCE";
2239 return "KEV_RENEGOTIATE_QUEUE";
2240 case KEV_EXPIRE:
2241 return "KEV_EXPIRE";
2242 default:
2243 return "KEV_?";
2244 }
2245 }
2246
2247 KeyContext(ProtoContext &p, const bool initiator, bool psid_cookie_mode = false)
2248 : Base(*p.config->ssl_factory,
2249 p.config->now,
2251 p.config->frame,
2252 p.stats,
2253 psid_cookie_mode),
2254 proto(p),
2256 crypto_flags(0),
2257 dirty(0),
2259 tlsprf(p.config->tlsprf_factory->new_obj(p.is_server()))
2260 {
2261 // reliable protocol?
2262 set_protocol(proto.config->protocol);
2263
2264 // get key_id from parent
2266
2267 // set initial state
2268 set_state((proto.is_server() ? S_INITIAL : C_INITIAL) + (initiator ? 0 : 1));
2269
2270 // cache stuff that we need to access in hot path
2271 cache_op32();
2272
2273 // remember when we were constructed
2275
2276 // set must-negotiate-by time
2278 }
2279
2280 void set_protocol(const Protocol &p)
2281 {
2282 is_reliable = p.is_reliable(); // cache is_reliable state locally
2283 }
2284
2285 uint32_t get_tls_warnings() const
2286 {
2287 return Base::get_tls_warnings();
2288 }
2289
2297 void start(const ProtoSessionID cookie_psid = ProtoSessionID())
2298 {
2299 if (cookie_psid.defined())
2300 {
2302 dirty = true;
2303 }
2304 if (state == C_INITIAL || state == S_INITIAL)
2305 {
2306 send_reset();
2307 set_state(state + 1);
2308 dirty = true;
2309 }
2310 }
2311
2312 // control channel flush
2313 void flush()
2314 {
2315 if (dirty)
2316 {
2318 Base::flush();
2320 dirty = false;
2321 }
2322 }
2323
2324 void invalidate(const Error::Type reason)
2325 {
2326 Base::invalidate(reason);
2327 }
2328
2329 // retransmit packets as part of reliability layer
2331 {
2332 // note that we don't set dirty here
2334 }
2335
2336 // when should we next call retransmit method
2338 {
2339 const Time t = Base::next_retransmit();
2340 if (t <= next_event_time)
2341 return t;
2342 return next_event_time;
2343 }
2344
2346 {
2347 if (bp->size() > APP_MSG_MAX)
2348 throw proto_error("app_send: sent control message is too large");
2349 Base::app_send(std::move(bp));
2350 }
2351
2352 // send app-level cleartext data to peer via SSL
2354 {
2355 if (state >= ACTIVE)
2356 {
2357 app_send_validate(std::move(bp));
2358 dirty = true;
2359 }
2360 else
2361 app_pre_write_queue.push_back(bp);
2362 }
2363
2364 // pass received ciphertext packets on network to SSL/reliability layers
2365 bool net_recv(Packet &&pkt)
2366 {
2367 const bool ret = Base::net_recv(std::move(pkt));
2368 dirty = true;
2369 return ret;
2370 }
2371
2372 // data channel encrypt
2374 {
2375 if (state >= ACTIVE
2377 && !invalidated())
2378 {
2379 // compress and encrypt packet and prepend op header
2380 const bool pid_wrap = do_encrypt(buf, true);
2381
2382 // Trigger a new SSL/TLS negotiation if packet ID (a 32-bit unsigned int)
2383 // is getting close to wrapping around. If it wraps back to 0 without
2384 // a renegotiation, it would cause the replay protection logic to wrongly
2385 // think that all further packets are replays.
2386 if (pid_wrap)
2388 }
2389 else
2390 buf.reset_size(); // no crypto context available
2391 }
2392
2393 // data channel decrypt
2395 {
2396 try
2397 {
2398 if (state >= ACTIVE
2400 && !invalidated())
2401 {
2402 // Knock off leading op from buffer, but pass the 32-bit version to
2403 // decrypt so it can be used as Additional Data for packet authentication.
2404 const size_t head_size = op_head_size(buf[0]);
2405 const unsigned char *op32 = (head_size == OP_SIZE_V2) ? buf.c_data() : nullptr;
2406 buf.advance(head_size);
2407
2408 // decrypt packet
2409 const Error::Type err = crypto->decrypt(buf, now->seconds_since_epoch(), op32);
2410 if (err)
2411 {
2412 proto.stats->error(err);
2413 if (proto.is_tcp() && (err == Error::DECRYPT_ERROR || err == Error::HMAC_ERROR))
2414 invalidate(err);
2415 }
2416
2417 // trigger renegotiation if we hit decrypt data limit
2418 if (data_limit)
2420 throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "Unable to add data limit");
2421
2422 // decompress packet
2423 if (compress)
2424 compress->decompress(buf);
2425
2426 // set MSS for segments server can receive
2427 if (proto.config->mss_fix > 0)
2428 MSSFix::mssfix(buf, numeric_cast<uint16_t>(proto.config->mss_fix));
2429 }
2430 else
2431 buf.reset_size(); // no crypto context available
2432 }
2433 catch (std::exception &)
2434 {
2436 buf.reset_size();
2437 if (proto.is_tcp())
2439 }
2440 }
2441
2442 // usually called by parent ProtoContext object when this KeyContext
2443 // has been retired.
2445 {
2446 set_event(current_ev,
2447 KEV_EXPIRE,
2449 }
2450
2451 // set a default next event, if unspecified
2453 {
2454 if (next_event == KEV_NONE && !invalidated())
2456 }
2457
2458 // set a key limit renegotiation event at time t
2459 void key_limit_reneg(const EventType ev, const Time &t)
2460 {
2461 if (t.defined())
2462 set_event(KEV_NONE, ev, t + Time::Duration::seconds(proto.is_server() ? 2 : 1));
2463 }
2464
2465 // return time of upcoming KEV_BECOME_PRIMARY event
2467 {
2469 return next_event_time;
2470 return Time();
2471 }
2472
2473 // is an KEV_x event pending?
2475 {
2478 return current_event != KEV_NONE;
2479 }
2480
2481 // get KEV_x event
2483 {
2484 return current_event;
2485 }
2486
2487 // clear KEV_x event
2489 {
2491 }
2492
2493 // was session invalidated by an exception?
2494 bool invalidated() const
2495 {
2496 return Base::invalidated();
2497 }
2498
2499 // Reason for invalidation
2501 {
2503 }
2504
2505 // our Key ID in the OpenVPN protocol
2506 unsigned int key_id() const
2507 {
2508 return key_id_;
2509 }
2510
2511 // indicates that data channel is keyed and ready to encrypt/decrypt packets
2513 {
2514 return state >= ACTIVE;
2515 }
2516
2517 bool is_dirty() const
2518 {
2519 return dirty;
2520 }
2521
2522 // notification from parent of rekey operation
2524 {
2525 if (crypto)
2526 crypto->rekey(type);
2527 else if (data_channel_key)
2528 {
2529 // save for deferred processing
2530 data_channel_key->rekey_type = type;
2531 }
2532 }
2533
2534 // time that our state transitioned to ACTIVE
2536 {
2537 return reached_active_time_;
2538 }
2539
2540 // transmit a keepalive message to peer
2542 {
2543 send_data_channel_message(proto_context_private::keepalive_message,
2544 sizeof(proto_context_private::keepalive_message));
2545 }
2546
2547 // send explicit-exit-notify message to peer
2549 {
2552 else
2553 send_data_channel_message(proto_context_private::explicit_exit_notify_message,
2554 sizeof(proto_context_private::explicit_exit_notify_message));
2555 }
2556
2557 // general purpose method for sending constant string messages
2558 // to peer via data channel
2559 void send_data_channel_message(const unsigned char *data, const size_t size)
2560 {
2561 if (state >= ACTIVE
2563 && !invalidated())
2564 {
2565 // allocate packet
2566 Packet pkt;
2568
2569 // write keepalive message
2570 pkt.buf->write(data, size);
2571
2572 // process packet for transmission
2573 do_encrypt(*pkt.buf, false); // set compress hint to "no"
2574
2575 // send it
2576 proto.net_send(key_id_, pkt);
2577 }
2578 }
2579
2587 static bool tls_crypt_v2_convertible(const ProtoContext &proto, const unsigned int opcode)
2588 {
2589 return proto.is_server()
2591 && !proto.psid_peer.defined()
2592 && proto.config->tls_crypt_v2_enabled()
2593 && opcode_carries_wkc(opcode);
2594 }
2595
2596 // validate the integrity of a packet
2597 static bool validate(const Buffer &net_buf, ProtoContext &proto, TimePtr now)
2598 {
2599 try
2600 {
2601 Buffer recv(net_buf);
2602
2603 switch (proto.tls_wrap_mode)
2604 {
2605 case TLS_AUTH:
2607 {
2608 // Still TLS_AUTH only because decapsulate() has not converted the
2609 // session yet; the tls-auth key would reject every genuine
2610 // tls-crypt-v2 client.
2611 OVPN_LOG_VERBOSE("SKIPPING VALIDATION OF WKc-BEARING PACKET");
2612 return true;
2613 }
2614 return validate_tls_auth(recv, proto, now);
2615 case TLS_CRYPT_V2:
2617 {
2618 // Nothing to judge it with: this packet keys the receive context.
2619 OVPN_LOG_VERBOSE("SKIPPING VALIDATION OF WKc-BEARING PACKET");
2620 return true;
2621 }
2622 /* no break */
2623 case TLS_CRYPT:
2624 return validate_tls_crypt(recv, proto, now);
2625 case TLS_PLAIN:
2626 return validate_tls_plain(recv, proto, now);
2627 }
2628 }
2629 catch ([[maybe_unused]] BufferException &e)
2630 {
2631 OVPN_LOG_VERBOSE("validate() exception: " << e.what());
2632 }
2633 return false;
2634 }
2635
2636 // Resets data_channel_key but also retains old
2637 // rekey_defined and rekey_type from previous instance.
2639 {
2640 std::unique_ptr<DataChannelKey> dck(new DataChannelKey());
2641
2642 if (proto.config->dc.key_derivation() == CryptoAlgs::KeyDerivation::TLS_EKM)
2643 {
2644 // USE RFC 5705 key material export
2645 export_key_material(dck->key, "EXPORTER-OpenVPN-datakeys");
2646 }
2647 else
2648 {
2649 // use the TLS PRF construction to exchange session keys for building
2650 // the data channel crypto context
2652 }
2653 tlsprf->erase();
2655 << " KEY " << CryptoAlgs::name(proto.config->dc.key_derivation())
2656 << " " << proto.mode().str() << ' ' << dck->key.render());
2657
2658 if (data_channel_key)
2659 {
2660 dck->rekey_type = data_channel_key->rekey_type;
2661 }
2662 dck.swap(data_channel_key);
2663 }
2664
2666 {
2667 if (c.mss_parms.fixed)
2668 {
2669 // substract IPv4 and TCP overhead, mssfix method will add extra 20 bytes for IPv6
2670 c.mss_fix = c.mss_parms.mssfix - (20 + 20);
2671 OPENVPN_LOG("fixed mssfix=" << c.mss_fix);
2672 return;
2673 }
2674
2675 /* If we are running default mssfix but have a different tun-mtu pushed
2676 * disable mssfix */
2677 if (c.tun_mtu != TUN_MTU_DEFAULT && c.tun_mtu != 0 && c.mss_parms.mssfix_default)
2678 {
2679 c.mss_fix = 0;
2680 OPENVPN_LOG("mssfix disabled since tun-mtu is non-default ("
2681 << c.tun_mtu << ")");
2682 return;
2683 }
2684
2685 auto payload_overhead = size_t(0);
2686
2687 // compv2 doesn't increase payload size
2688 switch (c.comp_ctx.type())
2689 {
2693 break;
2694 default:
2695 payload_overhead += 1;
2696 }
2697
2699 payload_overhead += PacketIDData::size(false);
2700
2701 // account for IPv4 and TCP headers of the payload, mssfix method
2702 // will add 20 extra bytes if payload is IPv6
2703 payload_overhead += 20 + 20;
2704
2705 auto overhead = c.protocol.extra_transport_bytes()
2706 + (enable_op32 ? OP_SIZE_V2 : 1)
2707 + c.dc.context().encap_overhead();
2708
2709 // in CBC mode, the packet id is part of the payload size / overhead
2711 overhead += PacketIDData::size(false);
2712
2713 if (c.mss_parms.mtu)
2714 {
2715 overhead += c.protocol.is_ipv6()
2716 ? sizeof(struct IPv6Header)
2717 : sizeof(struct IPv4Header);
2718 overhead += proto.is_tcp()
2719 ? sizeof(struct TCPHeader)
2720 : sizeof(struct UDPHeader);
2721 }
2722
2723 auto target = c.mss_parms.mssfix - overhead;
2724 if (CryptoAlgs::mode(c.dc.cipher()) == CryptoAlgs::CBC_HMAC)
2725 {
2726 // openvpn3 crypto includes blocksize in overhead, but we can
2727 // be a bit smarter here and instead make sure that resulting
2728 // ciphertext size (which is always multiple blocksize) is not
2729 // larger than target by running down target to the nearest
2730 // multiple of multiple and substracting 1.
2731
2732 auto block_size = CryptoAlgs::block_size(c.dc.cipher());
2733 target += block_size;
2734 target = (target / block_size) * block_size;
2735 target -= 1;
2736 }
2737
2738 if (!is_safe_conversion<decltype(c.mss_fix)>(target - payload_overhead))
2739 {
2740 OPENVPN_LOG("mssfix disabled since computed value is outside type bounds ("
2741 << c.mss_fix << ")");
2742 c.mss_fix = 0;
2743 return;
2744 }
2745
2746 c.mss_fix = static_cast<decltype(c.mss_fix)>(target - payload_overhead);
2747 OVPN_LOG_VERBOSE("mssfix=" << c.mss_fix
2748 << " (upper bound=" << c.mss_parms.mssfix
2749 << ", overhead=" << overhead
2750 << ", payload_overhead=" << payload_overhead
2751 << ", target=" << target << ")");
2752 }
2753
2754 // Initialize the components of the OpenVPN data channel protocol
2756 {
2757 // don't run until our prerequisites are satisfied
2758 if (!data_channel_key)
2759 return;
2761
2762 // set up crypto for data channel
2763 bool enable_compress = true;
2764 ProtoConfig &c = *proto.config;
2765 const unsigned int key_dir = proto.is_server() ? OpenVPNStaticKey::INVERSE : OpenVPNStaticKey::NORMAL;
2766 const OpenVPNStaticKey &key = data_channel_key->key;
2767
2768 // special data limits for 64-bit block-size ciphers (CVE-2016-6329)
2769 if (is_bs64_cipher(c.dc.cipher()))
2770 {
2774 OVPN_LOG_INFO("Per-Key Data Limit: "
2775 << dp.encrypt_red_limit << '/' << dp.decrypt_red_limit);
2776 data_limit.reset(new DataLimit(dp));
2777 }
2778
2779 // build crypto context for data channel encryption/decryption
2782
2787
2791
2792 crypto->init_pid("DATA",
2793 int(key_id_),
2794 proto.stats);
2795
2797
2798 enable_compress = crypto->consider_compression(proto.config->comp_ctx);
2799
2800 if (data_channel_key->rekey_type.has_value())
2801 crypto->rekey(data_channel_key->rekey_type.value());
2802 data_channel_key.reset();
2803
2804 // set up compression for data channel
2805 if (enable_compress)
2806 compress = proto.config->comp_ctx.new_compressor(proto.config->frame, proto.stats);
2807 else
2808 compress.reset();
2809
2810 // cache op32 for hot path in do_encrypt
2811 cache_op32();
2812
2814 }
2815
2817 const DataLimit::State cdl_status)
2818 {
2819 if (data_limit)
2820 data_limit_event(cdl_mode, data_limit->update_state(cdl_mode, cdl_status));
2821 }
2822
2823 int get_state() const
2824 {
2825 return state;
2826 }
2827
2834 static size_t tls_crypt_frame_size(const ProtoConfig &proto_config)
2835 {
2837 + proto_config.tls_crypt_context->digest_size()
2838 // the following is the tls-crypt payload
2839 + sizeof(char) // length of ACK array
2840 + sizeof(id_t); // reliable ID
2841 }
2842
2850 static size_t wkc_overhead(const ProtoConfig &proto_config)
2851 {
2852 return sizeof(uint16_t)
2853 + proto_config.tls_crypt_context->digest_size()
2854 + (proto_config.tls_crypt_v2_serverkey_id ? sizeof(uint32_t) : 0);
2855 }
2856
2871 static bool trailing_wkc_len(const Buffer &recv,
2872 const ProtoConfig &proto_config,
2873 const size_t min_wkc_len,
2874 uint16_t &wkc_len)
2875 {
2876 const size_t frame_size = tls_crypt_frame_size(proto_config);
2877 const size_t orig_size = recv.size();
2878
2879 if (orig_size < (frame_size + sizeof(wkc_len)))
2880 return false;
2881
2882 // avoid unaligned access
2883 std::memcpy(&wkc_len, recv.c_data() + orig_size - sizeof(wkc_len), sizeof(wkc_len));
2884 wkc_len = ntohs(wkc_len);
2885
2886 return wkc_len >= min_wkc_len && wkc_len <= (orig_size - frame_size);
2887 }
2888
2897 {
2899 int type = -1;
2901 };
2902
2916
2927 const ProtoConfig &proto_config,
2929 UnwrappedWkc &unwrapped)
2930 {
2931 // the ``WKc`` is located at the end of the packet, after the tls-crypt
2932 // payload.
2933 //
2934 // K_id is optional, and controlled by proto_config.tls_crypt_v2_serverkey_id.
2935 // If it is missing, we will use a single server key for all clients.
2936 //
2937 // Format is as follows:
2938 //
2939 // ``len = len(WKc)`` (16 bit, network byte order)
2940 // ``T = HMAC-SHA256(Ka, len || K_id || Kc || metadata)``
2941 // ``IV = 128 most significant bits of T``
2942 // ``WKc = T || AES-256-CTR(Ke, IV, Kc || metadata) || K_id || len``
2943
2944 const unsigned char *orig_data = recv.data();
2945 const size_t orig_size = recv.size();
2946 const size_t hmac_size = proto_config.tls_crypt_context->digest_size();
2947 const size_t tls_frame_size = tls_crypt_frame_size(proto_config);
2948
2949 uint32_t k_id = 0;
2950 const size_t serverkey_id_size = proto_config.tls_crypt_v2_serverkey_id ? sizeof(k_id) : 0;
2951
2952 // Establishes ``wkc_overhead() <= wkc_len <= orig_size - tls_frame_size``, so
2953 // the WKc holds its own length field, the authentication tag ``T`` and the
2954 // optional ``K_id``, and fits behind the tls-crypt frame. Both wkc_raw_size
2955 // expressions below then come to at least ``hmac_size + serverkey_id_size``,
2956 // which is what keeps the ``K_id`` read and the ciphertext length handed to
2957 // decrypt() from underflowing.
2958 uint16_t wkc_len;
2959 if (!trailing_wkc_len(recv, proto_config, wkc_overhead(proto_config), wkc_len))
2960 return Error::CC_ERROR;
2961
2962 // A CONTROL_HARD_RESET_CLIENT_V3 carries nothing but the ``WKc`` behind the
2963 // tls-crypt frame, so its extent follows from the sizes; a P_CONTROL_WKC_V1
2964 // carries a payload as well, and only ``wkc_len`` locates the ``WKc`` in it.
2965 const unsigned char *wkc_raw;
2966 size_t wkc_raw_size;
2967 if (opcode_extract(orig_data[0]) == CONTROL_HARD_RESET_CLIENT_V3)
2968 {
2969 wkc_raw = orig_data + tls_frame_size;
2970 wkc_raw_size = orig_size - tls_frame_size - sizeof(wkc_len);
2971 }
2972 else
2973 {
2974 wkc_raw = orig_data + orig_size - wkc_len;
2975 wkc_raw_size = wkc_len - sizeof(wkc_len);
2976 }
2977
2978 if (proto_config.tls_crypt_v2_serverkey_id)
2979 {
2980 std::memcpy(&k_id, wkc_raw + wkc_raw_size - serverkey_id_size, sizeof(k_id));
2981 k_id = ntohl(k_id);
2982 }
2983
2984 // length sanity check (the size of the ``len`` field is included in the value)
2985 if ((wkc_len - sizeof(uint16_t)) != wkc_raw_size)
2986 return Error::CC_ERROR;
2987
2989 // plaintext will be used to compute the Auth Tag, therefore start by prepending
2990 // the WKc length in network order
2991 const uint16_t net_wkc_len = htons(wkc_len);
2992 plaintext.write(&net_wkc_len, sizeof(net_wkc_len));
2993
2994 if (proto_config.tls_crypt_v2_serverkey_id)
2995 {
2996 const std::string serverkey_fn = render_hex_number(k_id, true) + ".key";
2997 const std::string serverkey_path = proto_config.tls_crypt_v2_serverkey_dir + "/"
2998 + serverkey_fn.substr(0, 2) + "/" + serverkey_fn;
2999
3000 // The K_id came off the wire, so a client whose key we never had -- or a
3001 // forgery -- names a file that is not there. That is a WKc we cannot unwrap
3002 // and nothing more, so nothing here may leave as an exception: decapsulate()
3003 // catches BufferException alone and open_file_error is not one.
3004 try
3005 {
3006 TLSCryptV2ServerKey tls_crypt_v2_key;
3007 tls_crypt_v2_key.parse(read_text(serverkey_path));
3008
3009 // Ka/Ke are of use only for the unwrap they key below, so they stay here
3010 // rather than on the config the cookie layer shares between sessions.
3011 OpenVPNStaticKey serverkey_material;
3012 tls_crypt_v2_key.extract_key(serverkey_material);
3013
3014 // the server key is composed by one key set only, therefore direction and
3015 // mode should not be specified when slicing
3016 tls_crypt_server.init(proto_config.ssl_factory->libctx(),
3017 serverkey_material.slice(OpenVPNStaticKey::HMAC),
3018 serverkey_material.slice(OpenVPNStaticKey::CIPHER));
3019 }
3020 catch (const std::exception &e)
3021 {
3022 OVPN_LOG_VERBOSE("DROPPING WKc NAMING TLS-crypt-V2 server key "
3023 << serverkey_path << ": " << e.what());
3024 return Error::DECRYPT_ERROR;
3025 }
3026
3027 OVPN_LOG_VERBOSE("Using TLS-crypt-V2 server key " << serverkey_path);
3028
3029 k_id = htonl(k_id);
3030 plaintext.write(&k_id, sizeof(k_id));
3031 }
3032 else
3033 {
3034 // Same key for every client, straight off the config. Keying the context is
3035 // this function's business in either mode: a caller that had to do it for one
3036 // mode and not the other could forget.
3037 if (!proto_config.tls_crypt_key.defined())
3038 {
3039 OVPN_LOG_VERBOSE("DROPPING WKc WITH NO TLS-crypt-V2 SERVER KEY TO UNWRAP IT");
3040 return Error::DECRYPT_ERROR;
3041 }
3042
3043 tls_crypt_server.init(proto_config.ssl_factory->libctx(),
3046 }
3047
3048 // the ``len || K_id`` prefix written above is part of the authenticated
3049 // plaintext, but the decrypted key material goes behind it
3050 const size_t plaintext_prefix_size = sizeof(wkc_len) + serverkey_id_size;
3051
3052 const size_t plaintext_max_size = plaintext.max_size();
3053 if (plaintext_max_size <= plaintext_prefix_size)
3054 return Error::DECRYPT_ERROR;
3055
3056 const size_t decrypt_bytes = tls_crypt_server.decrypt(wkc_raw,
3057 plaintext.data() + plaintext_prefix_size,
3058 plaintext_max_size - plaintext_prefix_size,
3059 wkc_raw + hmac_size,
3060 wkc_raw_size - hmac_size - serverkey_id_size);
3061 plaintext.inc_size(decrypt_bytes);
3062
3063 // The decrypted part must hold a full 2048-bit client key; metadata behind it is
3064 // optional. Measure decrypt_bytes, not plaintext.size(), which also counts the
3065 // length prefix and K_id written above.
3066 if (decrypt_bytes < OpenVPNStaticKey::KEY_SIZE)
3067 return Error::DECRYPT_ERROR;
3068
3069 if (!tls_crypt_server.hmac_cmp(wkc_raw, 0, plaintext.c_data(), plaintext.size()))
3070 return Error::HMAC_ERROR;
3071
3072 // we can now remove the WKc length (and the server key ID, if present)
3073 // from the plaintext, as they are not really part of the key material
3074 plaintext.advance(sizeof(wkc_len));
3075
3076 if (proto_config.tls_crypt_v2_serverkey_id)
3077 plaintext.advance(sizeof(k_id));
3078
3079 plaintext.read(unwrapped.client_key.raw_alloc(), OpenVPNStaticKey::KEY_SIZE);
3080
3081 // what is left of the plaintext is the metadata, its type byte in front
3082 if (!plaintext.empty())
3083 unwrapped.metadata.type = plaintext.pop_front();
3084 unwrapped.metadata.payload = std::move(plaintext);
3085
3086 // virtually remove the WKc from the packet
3087 recv.set_size(orig_size - wkc_len);
3088
3089 return Error::SUCCESS;
3090 }
3091
3108 static bool strip_resent_wkc(Buffer &recv, const ProtoConfig &proto_config)
3109 {
3110 // nothing is unwrapped here, but a WKc that could not hold the client key is
3111 // malformed all the same
3112 uint16_t wkc_len;
3113 if (!trailing_wkc_len(recv,
3114 proto_config,
3116 wkc_len))
3117 return false;
3118
3119 recv.set_size(recv.size() - wkc_len);
3120
3121 return true;
3122 }
3123
3124 private:
3126 {
3127 const unsigned char *orig_data = recv.data();
3128 const size_t orig_size = recv.size();
3129
3130 // advance buffer past initial op byte
3131 recv.advance(1);
3132
3133 // get source PSID
3134 ProtoSessionID src_psid(recv);
3135
3136 // verify HMAC
3137 {
3138 recv.advance(proto.hmac_size);
3139 if (!proto.ta_hmac_recv->ovpn_hmac_cmp(orig_data,
3140 orig_size,
3144 {
3145 return false;
3146 }
3147 }
3148
3149 // verify source PSID; a session has none until accept_peer() pins one
3150 if (proto.psid_peer.defined() && !proto.psid_peer.match(src_psid))
3151 return false;
3152
3153 // read tls_auth packet ID
3154 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
3155
3156 // get current time_t
3158
3159 // verify tls_auth packet ID
3160 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
3161
3162 // make sure that our own PSID is contained in packet received from peer
3163 if (ReliableAck::ack_skip(recv))
3164 {
3165 ProtoSessionID dest_psid(recv);
3166 if (!proto.psid_self.match(dest_psid))
3167 return false;
3168 }
3169
3170 return pid_ok;
3171 }
3172
3174 {
3175 // in TLS_CRYPT_V2 mode the receive context stays unset until a WKc has been
3176 // unwrapped, so a packet reaching here before that has nothing to be judged
3177 // with -- whichever opcodes validate() lets past it
3178 if (!proto.tls_crypt_recv)
3179 return false;
3180
3181 const unsigned char *orig_data = recv.data();
3182 const size_t orig_size = recv.size();
3183
3184 // advance buffer past initial op byte
3185 recv.advance(1);
3186 // get source PSID
3187 ProtoSessionID src_psid(recv);
3188 // read tls_auth packet ID
3189 const PacketIDControl pid = proto.ta_pid_recv.read_next(recv);
3190
3191 recv.advance(proto.hmac_size);
3192
3193 const size_t head_size = OPCODE_SIZE + ProtoSessionID::SIZE + PacketIDControl::size();
3194 const size_t data_offset = head_size + proto.hmac_size;
3195 if (orig_size < data_offset)
3196 return false;
3197
3198 // we need a buffer to perform the payload decryption and being this a static
3199 // function we can't use the instance member like in decapsulate_tls_crypt()
3201 proto.config->frame->prepare(Frame::DECRYPT_WORK, work);
3202
3203 // decrypt payload from 'recv' into 'work'
3204 const size_t decrypt_bytes = proto.tls_crypt_recv->decrypt(orig_data + head_size,
3205 work.data(),
3206 work.max_size(),
3207 recv.c_data(),
3208 recv.size());
3209 if (!decrypt_bytes)
3210 return false;
3211
3212 work.inc_size(decrypt_bytes);
3213
3214 // verify HMAC
3215 if (!proto.tls_crypt_recv->hmac_cmp(orig_data,
3217 work.c_data(),
3218 work.size()))
3219 return false;
3220
3221 // verify source PSID, never pin it: only accept_peer() may name our peer
3222 if (proto.psid_peer.defined() && !proto.psid_peer.match(src_psid))
3223 return false;
3224
3225 // get current time_t
3227
3228 // verify tls_auth packet ID
3229 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
3230 // make sure that our own PSID is contained in packet received from peer
3232 {
3233 ProtoSessionID dest_psid(work);
3234 if (!proto.psid_self.match(dest_psid))
3235 return false;
3236 }
3237
3238 return pid_ok;
3239 }
3240
3242 {
3243 // advance buffer past initial op byte
3244 recv.advance(1);
3245
3246 ProtoSessionID src_psid(recv);
3247 // verify source PSID; a session has none until accept_peer() pins one
3248 if (proto.psid_peer.defined() && !proto.psid_peer.match(src_psid))
3249 return false;
3250
3251 // make sure that our own PSID is contained in packet received from peer
3252 if (ReliableAck::ack_skip(recv))
3253 {
3254 ProtoSessionID dest_psid(recv);
3255 if (!proto.psid_self.match(dest_psid))
3256 return false;
3257 }
3258 return true;
3259 }
3260
3261 bool do_encrypt(BufferAllocated &buf, const bool compress_hint)
3262 {
3263 if (!is_safe_conversion<uint16_t>(proto.config->mss_fix))
3264 return false;
3265
3266 // set MSS for segments client can receive
3267 if (proto.config->mss_fix > 0)
3268 MSSFix::mssfix(buf, static_cast<uint16_t>(proto.config->mss_fix));
3269
3270 // compress packet
3271 if (compress)
3272 compress->compress(buf, compress_hint);
3273
3274 // trigger renegotiation if we hit encrypt data limit
3275 if (data_limit)
3277 return false;
3278
3279 bool pid_wrap;
3280
3281 if (enable_op32)
3282 {
3283 const std::uint32_t op32 = htonl(op32_compose(DATA_V2, key_id_, remote_peer_id));
3284
3285 static_assert(sizeof(op32) == OP_SIZE_V2, "OP_SIZE_V2 inconsistency");
3286
3287 // encrypt packet
3288 pid_wrap = crypto->encrypt(buf, (const unsigned char *)&op32);
3289
3290 // prepend op
3291 buf.prepend((const unsigned char *)&op32, sizeof(op32));
3292 }
3293 else
3294 {
3295 // encrypt packet
3296 pid_wrap = crypto->encrypt(buf, nullptr);
3297
3298 // prepend op
3300 }
3301 return pid_wrap;
3302 }
3303
3304 // cache op32 and remote_peer_id
3306 {
3307 enable_op32 = proto.config->enable_op32;
3308 remote_peer_id = proto.config->remote_peer_id;
3309 }
3310
3311 void set_state(const int newstate)
3312 {
3314 << " KeyContext[" << key_id_ << "] "
3315 << state_string(state) << " -> " << state_string(newstate));
3316 state = newstate;
3317 }
3318
3319 void set_event(const EventType current)
3320 {
3322 << " KeyContext[" << key_id_ << "] "
3323 << event_type_string(current));
3324 current_event = current;
3325 }
3326
3327 void set_event(const EventType current, const EventType next, const Time &next_time)
3328 {
3330 << " KeyContext[" << key_id_ << "] "
3331 << event_type_string(current) << " -> " << event_type_string(next)
3332 << '(' << seconds_until(next_time) << ')');
3333 current_event = current;
3334 next_event = next;
3335 next_event_time = next_time;
3336 }
3337
3338 void invalidate_callback() // called by ProtoStackBase when session is invalidated
3339 {
3343 }
3344
3345 // Trigger a renegotiation based on data flow condition such
3346 // as per-key data limit or packet ID approaching wraparound.
3348 {
3350 {
3351 OVPN_LOG_VERBOSE(proto.debug_prefix() << " SCHEDULE KEY LIMIT RENEGOTIATION");
3352
3355
3356 // If primary, renegotiate now (within a second or two).
3357 // If secondary, queue the renegotiation request until
3358 // key reaches primary.
3359 if (next_event == KEV_BECOME_PRIMARY) // secondary key before transition to primary?
3360 {
3361 // reneg request crosses over to primary,
3362 // doesn't wipe next_event (KEV_BECOME_PRIMARY)
3364 }
3365 else
3366 {
3368 }
3369 }
3370 }
3371
3372 // Handle data-limited keys such as Blowfish and other 64-bit block-size ciphers.
3373 bool data_limit_add(const DataLimit::Mode mode, const size_t size)
3374 {
3375 if (is_safe_conversion<DataLimit::size_type>(size))
3376 return false;
3377 const DataLimit::State state = data_limit->add(mode, static_cast<DataLimit::size_type>(size));
3378 if (state > DataLimit::None)
3380 return true;
3381 }
3382
3383 // Handle a DataLimit event.
3385 {
3387 << " DATA LIMIT " << DataLimit::mode_str(mode)
3388 << ' ' << DataLimit::state_str(state)
3389 << " key_id=" << key_id_);
3390
3391 // State values:
3392 // DataLimit::Green -- first packet received and decrypted.
3393 // DataLimit::Red -- data limit has been exceeded, so trigger a renegotiation.
3394 if (state == DataLimit::Red)
3396
3397 // When we are in KEV_PRIMARY_PENDING state, we must receive at least
3398 // one packet from the peer on this key before we transition to
3399 // KEV_BECOME_PRIMARY so we can transmit on it.
3400 if (next_event == KEV_PRIMARY_PENDING && data_limit->is_decrypt_green())
3401 set_event(KEV_NONE, KEV_BECOME_PRIMARY, *now + Time::Duration::seconds(1));
3402 }
3403
3404 // Should we enter KEV_PRIMARY_PENDING state? Do it if:
3405 // 1. we are a client,
3406 // 2. data limit is enabled,
3407 // 3. this is a renegotiated key in secondary context, i.e. not the first key, and
3408 // 4. no data received yet from peer on this key.
3409 bool data_limit_defer() const
3410 {
3411 return !proto.is_server()
3412 && data_limit
3413 && key_id_
3414 && !data_limit->is_decrypt_green();
3415 }
3416
3417 // General expiration set when key hits data limit threshold.
3419 {
3420 return *now + (proto.config->handshake_window * 2);
3421 }
3422
3424 {
3427 reached_active() + proto.config->become_primary);
3428 }
3429
3431 {
3432 if (*now >= next_event_time)
3433 {
3434 switch (next_event)
3435 {
3436 case KEV_BECOME_PRIMARY:
3437 if (data_limit_defer())
3439 else
3442 construct_time + proto.config->renegotiate);
3443 break;
3444 case KEV_RENEGOTIATE:
3447 break;
3448 case KEV_NEGOTIATE:
3450 break;
3453 break;
3454 case KEV_EXPIRE:
3456 break;
3457 default:
3458 break;
3459 }
3460 }
3461 }
3462
3463 void kev_error(const EventType ev, const Error::Type reason)
3464 {
3465 proto.stats->error(reason);
3466 invalidate(reason);
3467 set_event(ev);
3468 }
3469
3470 unsigned int initial_op(const bool sender, const bool tls_crypt_v2) const
3471 {
3472 if (key_id_)
3473 {
3474 return CONTROL_SOFT_RESET_V1;
3475 }
3476
3477 if (proto.is_server() == sender)
3479
3480 if (!tls_crypt_v2)
3483 }
3484
3486 {
3487 Packet pkt;
3490 raw_send(std::move(pkt));
3491 }
3492
3494 {
3495 /* The data in the early negotiation packet is structured as
3496 * TLV (type, length, value) */
3497
3498 Buffer buf = pkt.buffer();
3499 while (!buf.empty())
3500 {
3501 if (buf.size() < 4)
3502 {
3503 /* Buffer does not have enough bytes for type (uint16) and length (uint16) */
3504 return false;
3505 }
3506
3507 uint16_t type = read_uint16_length(buf);
3508 uint16_t len = read_uint16_length(buf);
3509
3510 /* TLV defines a length that is larger than the remainder in the buffer. */
3511 if (buf.size() < len)
3512 return false;
3513
3514 if (type == EARLY_NEG_FLAGS)
3515 {
3516 if (len != 2)
3517 return false;
3518 uint16_t flags = read_uint16_length(buf);
3519
3520 if (flags & EARLY_NEG_FLAG_RESEND_WKC)
3521 {
3522 resend_wkc = true;
3523 }
3524 }
3525 else
3526 {
3527 /* skip over unknown types. We rather ignore undefined TLV to
3528 * not needing to add bits initial reset message (where space
3529 * is really tight) for optional features. */
3530 buf.advance(len);
3531 }
3532 }
3533 return true;
3534 }
3535
3536
3537 void raw_recv(Packet &&raw_pkt) // called by ProtoStackBase
3538 {
3539 if (raw_pkt.opcode == initial_op(false, proto.tls_wrap_mode == TLS_CRYPT_V2))
3540 {
3541 switch (state)
3542 {
3543 case C_WAIT_RESET:
3545 if (!parse_early_negotiation(raw_pkt))
3546 {
3548 }
3549 break;
3550 case S_WAIT_RESET:
3551 send_reset();
3553 break;
3554 }
3555 }
3556 }
3557
3558 void app_recv(BufferPtr &&to_app_buf) // called by ProtoStackBase
3559 {
3560 app_recv_buf.put(std::move(to_app_buf));
3562 throw proto_error("app_recv: received control message is too large");
3564 switch (state)
3565 {
3566 case C_WAIT_AUTH:
3567 if (recv_auth_complete(bcc))
3568 {
3569 recv_auth(bcc.get());
3571 }
3572 break;
3573 case S_WAIT_AUTH:
3574 if (recv_auth_complete(bcc))
3575 {
3576 recv_auth(bcc.get());
3577 send_auth();
3579 }
3580 break;
3581 case S_WAIT_AUTH_ACK:
3582 // rare case where client receives auth, goes ACTIVE,
3583 // but the ACK response is dropped
3584 case ACTIVE:
3585 if (bcc.advance_to_null()) // does composed buffer contain terminating null char?
3586 proto.app_recv(key_id_, bcc.get());
3587 break;
3588 }
3589 }
3590
3591 void net_send(const Packet &net_pkt, const Base::NetSendType nstype) // called by ProtoStackBase
3592 {
3593 if (!is_reliable || nstype != Base::NET_SEND_RETRANSMIT) // retransmit packets on UDP only, not TCP
3594 proto.net_send(key_id_, net_pkt);
3595 }
3596
3598 {
3600 {
3601 switch (state)
3602 {
3603 case C_WAIT_RESET_ACK:
3605 send_auth();
3607 break;
3608 case S_WAIT_RESET_ACK:
3611 break;
3612 case C_WAIT_AUTH_ACK:
3613 active();
3615 break;
3616 case S_WAIT_AUTH_ACK:
3617 active();
3619 break;
3620 }
3621 }
3622 }
3623
3625 {
3626 auto buf = BufferAllocatedRc::Create();
3627 proto.config->frame->prepare(Frame::WRITE_SSL_CLEARTEXT, *buf);
3628 buf->write(proto_context_private::auth_prefix, sizeof(proto_context_private::auth_prefix));
3630 tlsprf->self_write(*buf);
3631 const std::string options = proto.config->options_string();
3632 write_auth_string(options, *buf);
3633 if (!proto.is_server())
3634 {
3635 OVPN_LOG_INFO("Tunnel Options:" << options);
3636 buf->add_flags(BufAllocFlags::DESTRUCT_ZERO);
3637 if (proto.config->xmit_creds)
3638 proto.client_auth(*buf);
3639 else
3640 {
3641 write_empty_string(*buf); // username
3642 write_empty_string(*buf); // password
3643 }
3644 const std::string peer_info = proto.config->peer_info_string(proto.proto_callback->supports_epoch_data());
3645 write_auth_string(peer_info, *buf);
3646 }
3647 app_send_validate(std::move(buf));
3648 dirty = true;
3649 }
3650
3652 {
3653 const unsigned char *buf_pre = buf->read_alloc(sizeof(proto_context_private::auth_prefix));
3654 if (std::memcmp(buf_pre, proto_context_private::auth_prefix, sizeof(proto_context_private::auth_prefix)))
3655 throw proto_error("bad_auth_prefix");
3656 tlsprf->peer_read(*buf);
3657 const std::string options = read_auth_string<std::string>(*buf);
3658 if (proto.is_server())
3659 {
3660 const std::string username = read_auth_string<std::string>(*buf);
3661 const SafeString password = read_auth_string<SafeString>(*buf);
3662 const std::string peer_info = read_auth_string<std::string>(*buf);
3663 proto.proto_callback->server_auth(username, password, peer_info, Base::auth_cert());
3664 }
3665 }
3666
3667 // return true if complete recv_auth message is contained in buffer
3669 {
3670 if (!bc.advance(sizeof(proto_context_private::auth_prefix)))
3671 return false;
3672 if (!tlsprf->peer_read_complete(bc))
3673 return false;
3674 if (!bc.advance_string()) // options
3675 return false;
3676 if (proto.is_server())
3677 {
3678 if (!bc.advance_string()) // username
3679 return false;
3680 if (!bc.advance_string()) // password
3681 return false;
3682 if (!bc.advance_string()) // peer_info
3683 return false;
3684 }
3685 return true;
3686 }
3687
3688 void active()
3689 {
3690 OVPN_LOG_INFO("TLS Handshake: " << Base::ssl_handshake_details());
3691
3692 /* Our internal state machine only decides after push request what protocol
3693 * options we want to use. Therefore we also have to postpone data key
3694 * generation until this happens, create a empty DataChannelKey as
3695 * placeholder */
3696 data_channel_key.reset(new DataChannelKey());
3697 if (!proto.dc_deferred)
3699
3700 while (!app_pre_write_queue.empty())
3701 {
3702 app_send_validate(std::move(app_pre_write_queue.front()));
3703 app_pre_write_queue.pop_front();
3704 dirty = true;
3705 }
3708 active_event();
3709 }
3710
3711 void prepend_dest_psid_and_acks(Buffer &buf, unsigned int opcode)
3712 {
3713 // if sending ACKs, prepend dest PSID
3714 if (xmit_acks.acks_ready())
3715 {
3716 if (proto.psid_peer.defined())
3717 proto.psid_peer.prepend(buf);
3718 else
3719 {
3721 throw proto_error("peer_psid_undef");
3722 }
3723 }
3724
3725 // prepend ACKs for messages received from peer
3726 xmit_acks.prepend(buf, opcode == ACK_V1);
3727 }
3728
3729 bool verify_src_psid(const ProtoSessionID &src_psid)
3730 {
3731 if (proto.psid_peer.defined() && !proto.psid_peer.match(src_psid))
3732 {
3734 if (proto.is_tcp())
3736 return false;
3737 }
3738 return true;
3739 }
3740
3749 void accept_peer(const ProtoSessionID &src_psid)
3750 {
3751 pkt_from_peer = true;
3752 if (!proto.psid_peer.defined())
3753 proto.psid_peer = src_psid;
3754 }
3755
3757 {
3758 ProtoSessionID dest_psid(buf);
3759 if (!proto.psid_self.match(dest_psid))
3760 {
3762 if (proto.is_tcp())
3764 return false;
3765 }
3766 return true;
3767 }
3768
3769 void gen_head_tls_auth(const unsigned int opcode, Buffer &buf)
3770 {
3772 }
3773
3774 void gen_head_tls_crypt(const unsigned int opcode, BufferAllocated &buf)
3775 {
3776 // The send context stays unset until a WKc has been unwrapped, and decapsulate()
3777 // can put a session into TLS_CRYPT_V2 mode before that ever happens. Giving up
3778 // this session is caught per session, where the dereference below would not be.
3779 if (!proto.tls_crypt_send)
3780 throw proto_error("gen_head_tls_crypt: no tls-crypt send context");
3781
3783 }
3784
3785 void gen_head_tls_plain(const unsigned int opcode, Buffer &buf)
3786 {
3787 wrap_tls_plain(opcode, buf, proto.psid_self, key_id_);
3788 }
3789
3790 void gen_head(const unsigned int opcode, BufferAllocated &buf)
3791 {
3792 switch (proto.tls_wrap_mode)
3793 {
3794 case TLS_AUTH:
3795 gen_head_tls_auth(opcode, buf);
3796 break;
3797 case TLS_CRYPT:
3798 case TLS_CRYPT_V2:
3799 gen_head_tls_crypt(opcode, buf);
3800 break;
3801 case TLS_PLAIN:
3802 gen_head_tls_plain(opcode, buf);
3803 break;
3804 }
3805 }
3806
3807 // True if the control packet with the given reliable-layer id will
3808 // carry the tls-crypt-v2 wrapped client key (WKc), appended after the
3809 // payload during encapsulation. Used both to select the CONTROL_WKC_V1
3810 // opcode and to reserve room for the WKc when filling the packet with
3811 // ciphertext.
3813 {
3814 return id == 1 && resend_wkc && proto.tls_wrap_mode == TLS_CRYPT_V2;
3815 }
3816
3817 // Worst-case number of bytes this control packet will carry around
3818 // the SSL ciphertext once encapsulated and wrapped: the tls wrap
3819 // header (opcode, session id, packet id, hmac) plus the reliable
3820 // layer message id and the largest possible piggybacked ACK block.
3821 // ACKs must be accounted for at their maximum, since retransmits
3822 // re-run encapsulate() with whatever ACKs are pending at that time.
3824 {
3825 size_t overhead = OPCODE_SIZE + ProtoSessionID::SIZE + proto.hmac_size;
3827 overhead += PacketIDControl::size();
3828 // reliable layer message id
3829 overhead += sizeof(id_t);
3830 // worst-case ACK block: count byte + ACK ids + dest session id
3831 overhead += 1 + sizeof(id_t) * ReliableAck::maximum_acks_control_v1
3833 return overhead;
3834 }
3835
3836 // Maximum amount of SSL ciphertext that may be placed into the control
3837 // packet with the given id, such that the fully wrapped packet does
3838 // not exceed the mssfix_ctrl limit. For the packet that also carries
3839 // the WKc, the WKc length is subtracted as well. Called by
3840 // ProtoStackBase.
3842 {
3843 size_t capacity = (*proto.config->frame)[Frame::READ_BIO_MEMQ_STREAM].payload();
3844
3845 // never let the fully wrapped packet exceed mssfix_ctrl
3846 size_t wire_budget = proto.config->mssfix_ctrl;
3847 wire_budget -= std::min(wire_budget, control_channel_wrap_overhead());
3848 capacity = std::min(capacity, wire_budget);
3849
3850 if (packet_carries_wkc(id) && proto.config->wkc.defined())
3851 {
3852 // clamp: a large WKc could exceed a small budget (mssfix-ctrl
3853 // can go as low as 256); never let the subtraction wrap. A
3854 // zero capacity yields a CONTROL_WKC_V1 packet carrying the
3855 // WKc alone, with all ciphertext deferred to the following
3856 // messages.
3857 capacity -= std::min(capacity, proto.config->wkc.size());
3858 }
3859 return capacity;
3860 }
3861
3862 void encapsulate(id_t id, Packet &pkt) // called by ProtoStackBase
3863 {
3864 BufferAllocated &buf = *pkt.buf;
3865
3866 // prepend message sequence number
3867 ReliableAck::prepend_id(buf, id);
3868
3869 // prepend dest PSID and ACKs to reply to peer
3871
3872 // generate message head
3873 int opcode = pkt.opcode;
3874 if (packet_carries_wkc(id))
3875 {
3876 opcode = CONTROL_WKC_V1;
3877 }
3878
3879 gen_head(opcode, buf);
3880 }
3881
3882 void generate_ack(Packet &pkt) // called by ProtoStackBase
3883 {
3884 BufferAllocated &buf = *pkt.buf;
3885
3886 // prepend dest PSID and ACKs to reply to peer
3888
3889 gen_head(ACK_V1, buf);
3890 }
3891
3893 {
3894 Buffer &recv = *pkt.buf;
3895
3896 // update our last-packet-received time
3898
3899 // verify source PSID
3900 if (!verify_src_psid(src_psid))
3901 return false;
3902
3903 // get current time_t
3905 // verify tls_auth/crypt packet ID
3906 const bool pid_ok = proto.ta_pid_recv.test_add(pid, t, false);
3907
3908 // process ACKs sent by peer (if packet ID check failed,
3909 // read the ACK IDs, but don't modify the rel_send object).
3910 if (ReliableAck::ack(rel_send, recv, pid_ok))
3911 {
3912 // make sure that our own PSID is contained in packet received from peer
3913 if (!verify_dest_psid(recv))
3914 return false;
3915 }
3916
3917 accept_peer(src_psid);
3918
3919 // for CONTROL packets only, not ACK
3920 if (pkt.opcode != ACK_V1)
3921 {
3922 // get message sequence number
3923 const id_t id = ReliableAck::read_id(recv);
3924
3925 if (pid_ok)
3926 {
3927 // try to push message into reliable receive object
3928 const unsigned int rflags = rel_recv.receive(pkt, id);
3929
3930 // should we ACK packet back to sender?
3931 if (rflags & ReliableRecv::ACK_TO_SENDER)
3932 xmit_acks.push_back(id); // ACK packet to sender
3933
3934 // was packet accepted by reliable receive object?
3935 if (rflags & ReliableRecv::IN_WINDOW)
3936 {
3937 // remember tls_auth packet ID so that it can't be replayed
3938 proto.ta_pid_recv.test_add(pid, t, true);
3939 return true;
3940 }
3941 }
3942 else // treat as replay
3943 {
3945 if (pid.is_valid())
3946 // even replayed packets must be ACKed or protocol could deadlock
3947 xmit_acks.push_back(id);
3948 }
3949 }
3950 else
3951 {
3952 if (pid_ok)
3953 // remember tls_auth packet ID of ACK packet to prevent replay
3954 proto.ta_pid_recv.test_add(pid, t, true);
3955 else
3957 }
3958 return false;
3959 }
3960
3962 {
3963 ProtoSessionID src_psid;
3964 PacketIDControl pid;
3965 switch (unwrap_tls_auth(*pkt.buf, proto.hmac_size, *proto.ta_hmac_recv, proto.ta_pid_recv, src_psid, pid))
3966 {
3967 case UnwrapStatus::OK:
3968 return decapsulate_post_process(pkt, src_psid, pid);
3969
3972 if (proto.is_tcp())
3974 return false;
3975
3976 default:
3977 return false;
3978 }
3979 }
3980
3982 {
3983 // in TLS_CRYPT_V2 mode the receive context stays unset until a WKc has been
3984 // unwrapped, so any other opcode reaching us before that has no key to be
3985 // decrypted with
3986 if (!proto.tls_crypt_recv)
3987 {
3989 if (proto.is_tcp())
3991 return false;
3992 }
3993
3994 ProtoSessionID src_psid;
3995 PacketIDControl pid;
3996 switch (unwrap_tls_crypt(*pkt.buf, work, *proto.config->frame, proto.hmac_size, *proto.tls_crypt_recv, proto.ta_pid_recv, src_psid, pid))
3997 {
3998 case UnwrapStatus::OK:
3999 return decapsulate_post_process(pkt, src_psid, pid);
4000
4003 if (proto.is_tcp())
4005 return false;
4006
4009 if (proto.is_tcp())
4011 return false;
4012
4013 default: // DROP: malformed / too short
4014 return false;
4015 }
4016 }
4017
4019 {
4020 Buffer &recv = *pkt.buf;
4021
4022 // update our last-packet-received time
4024
4025 // advance buffer past initial op byte
4026 recv.advance(1);
4027
4028 // verify source PSID
4029 ProtoSessionID src_psid(recv);
4030 if (!verify_src_psid(src_psid))
4031 return false;
4032
4033 // process ACKs sent by peer
4034 if (ReliableAck::ack(rel_send, recv, true))
4035 {
4036 // make sure that our own PSID is in packet received from peer
4037 if (!verify_dest_psid(recv))
4038 return false;
4039 }
4040
4041 accept_peer(src_psid);
4042
4043 // for CONTROL packets only, not ACK
4044 if (pkt.opcode != ACK_V1)
4045 {
4046 // get message sequence number
4047 const id_t id = ReliableAck::read_id(recv);
4048
4049 // try to push message into reliable receive object
4050 const unsigned int rflags = rel_recv.receive(pkt, id);
4051
4052 // should we ACK packet back to sender?
4053 if (rflags & ReliableRecv::ACK_TO_SENDER)
4054 xmit_acks.push_back(id); // ACK packet to sender
4055
4056 // was packet accepted by reliable receive object?
4057 if (rflags & ReliableRecv::IN_WINDOW)
4058 return true;
4059 }
4060 return false;
4061 }
4062
4070 bool tls_crypt_v2_wanted(const Packet &pkt) const
4071 {
4073 }
4074
4075 bool decapsulate(Packet &pkt) // called by ProtoStackBase
4076 {
4077 const bool detect_tls_crypt_v2 = tls_crypt_v2_wanted(pkt);
4078 const size_t tls_auth_hmac_size = proto.hmac_size;
4079 const bool had_client_key = bool(proto.tls_crypt_recv);
4080 bool authenticated = false;
4081
4082 pkt_from_peer = false;
4083
4084 try
4085 {
4086 if (detect_tls_crypt_v2)
4087 {
4088 // Create the server context the client's WKc is unwrapped with,
4089 // keyed only at unwrap time, when the WKc names its key. tls-crypt
4090 // session key setup is postponed to reception of the WKc too.
4092
4094 proto.hmac_size = proto.config->tls_crypt_context->digest_size();
4095
4096 // init tls_crypt packet ID; the send half waits until the packet has
4097 // earned it, below, since putting the previous id back is not possible
4098 proto.ta_pid_recv.init("SSL-CC", 0, proto.stats);
4099 }
4100
4101 authenticated = decapsulate_by_wrap_mode(pkt);
4102 }
4103 catch (const BufferException &)
4104 {
4106 if (proto.is_tcp())
4108 }
4109
4110 if (!pkt_from_peer && !had_client_key && proto.tls_crypt_recv)
4111 {
4112 // Drop a packet that's not ours.
4116 }
4117
4118 if (detect_tls_crypt_v2)
4119 {
4120 if (!pkt_from_peer)
4121 {
4122 // Not our peer's packet, so leave the session as tls-auth had it. The
4123 // receive packet id needs no undoing: reset() initialises it the same
4124 // way and nothing of our peer's has moved it.
4126 proto.hmac_size = tls_auth_hmac_size;
4127 }
4128 else
4129 {
4133 }
4134 }
4135
4136 return authenticated;
4137 }
4138
4148 {
4149 if (!proto.config->tls_crypt_metadata_factory)
4150 return true;
4151
4152 const TLSCryptMetadata::Ptr recorder = proto.config->tls_crypt_metadata_factory->new_obj();
4153
4154 if (recorder->verify(metadata.type, metadata.payload))
4155 return true;
4156
4158
4159 // Unconditional, unlike the drops above: this packet authenticated, so the
4160 // session ended is the one the record belongs to. The key stays -- the
4161 // decapsulation left an ACK to be wrapped.
4163 return false;
4164 }
4165
4179 {
4180 switch (proto.tls_wrap_mode)
4181 {
4182 case TLS_AUTH:
4183 return decapsulate_tls_auth(pkt);
4184 case TLS_CRYPT_V2:
4185 // The client key comes from this packet and nowhere else; later copies carry
4186 // the WKc too and only need it stripped.
4188 {
4189 if (!proto.tls_crypt_recv)
4190 {
4192 {
4194 << " DROPPING WKc WITH NO SERVER CONTEXT");
4195 return false;
4196 }
4197
4198 UnwrappedWkc unwrapped;
4199 const Error::Type unwrap_wkc_result = unwrap_tls_crypt_wkc(*pkt.buf,
4200 *proto.config,
4202 unwrapped);
4203 switch (unwrap_wkc_result)
4204 {
4206 case Error::HMAC_ERROR:
4207 proto.stats->error(unwrap_wkc_result);
4208 if (proto.is_tcp())
4209 invalidate(unwrap_wkc_result);
4210 return false;
4211 case Error::SUCCESS:
4212 break;
4213 default:
4214 return false;
4215 }
4216
4217 // The WKc holds up under the server key, so the client key inside it
4218 // is one this server issued. Key the session with it.
4219 proto.tls_crypt_client_key = std::move(unwrapped.client_key);
4221
4222 // That says the WKc is ours, not that the sender holds the Kc inside:
4223 // a replayed one unwraps just as well. Only the frame verifying under
4224 // that Kc says so, hence decapsulate before judging the record.
4225 const bool authenticated = decapsulate_tls_crypt(pkt);
4226
4227 if (pkt_from_peer && !verify_wkc_metadata(unwrapped.metadata))
4228 return false;
4229
4230 return authenticated;
4231 }
4232 else if (!strip_resent_wkc(*pkt.buf, *proto.config))
4233 {
4235 if (proto.is_tcp())
4237 return false;
4238 }
4239 }
4240 // now that the tls-crypt contexts have been initialized it is
4241 // possible to proceed with the standard tls-crypt decapsulation
4242 [[fallthrough]];
4243 case TLS_CRYPT:
4244 return decapsulate_tls_crypt(pkt);
4245 case TLS_PLAIN:
4246 return decapsulate_tls_plain(pkt);
4247 }
4248 return false;
4249 }
4250
4251 // for debugging
4252 static const char *state_string(const int s)
4253 {
4254 switch (s)
4255 {
4256 case C_WAIT_RESET_ACK:
4257 return "C_WAIT_RESET_ACK";
4258 case C_WAIT_AUTH_ACK:
4259 return "C_WAIT_AUTH_ACK";
4260 case S_WAIT_RESET_ACK:
4261 return "S_WAIT_RESET_ACK";
4262 case S_WAIT_AUTH_ACK:
4263 return "S_WAIT_AUTH_ACK";
4264 case C_INITIAL:
4265 return "C_INITIAL";
4266 case C_WAIT_RESET:
4267 return "C_WAIT_RESET";
4268 case C_WAIT_AUTH:
4269 return "C_WAIT_AUTH";
4270 case S_INITIAL:
4271 return "S_INITIAL";
4272 case S_WAIT_RESET:
4273 return "S_WAIT_RESET";
4274 case S_WAIT_AUTH:
4275 return "S_WAIT_AUTH";
4276 case ACTIVE:
4277 return "ACTIVE";
4278 default:
4279 return "STATE_UNDEF";
4280 }
4281 }
4282
4283 // for debugging
4284 int seconds_until(const Time &next_time)
4285 {
4286 Time::Duration d = next_time - *now;
4287 if (d.is_infinite())
4288 return -1;
4289 return numeric_cast<int>(d.to_seconds());
4290 }
4291
4292 // BEGIN KeyContext data members
4293
4296 unsigned int key_id_;
4297 unsigned int crypto_flags;
4298 int remote_peer_id; // -1 to disable
4300 /* early negotiation enabled resending of wrapped tls-crypt-v2 client key
4301 * with third packet of the three-way handshake
4302 */
4303 bool resend_wkc = false;
4305 bool pkt_from_peer = false;
4306 bool dirty;
4317 std::deque<BufferPtr> app_pre_write_queue;
4318 std::unique_ptr<DataChannelKey> data_channel_key;
4320 std::unique_ptr<DataLimit> data_limit;
4322
4323 // static member used by validate_tls_crypt()
4325 };
4326
4328 {
4329 public:
4330 PsidCookieHelper(unsigned int op_field)
4331 : op_code_(opcode_extract(op_field)), key_id_(key_id_extract(op_field))
4332 {
4333 }
4334
4336 {
4337 return key_id_ == 0 && (op_code_ == CONTROL_HARD_RESET_CLIENT_V2 || op_code_ == CONTROL_HARD_RESET_CLIENT_V3);
4338 }
4339
4341 bool is_tls_crypt_v2() const noexcept
4342 {
4343 return op_code_ == CONTROL_HARD_RESET_CLIENT_V3 || op_code_ == CONTROL_WKC_V1;
4344 }
4345
4347 bool supports_early_negotiation(const PacketIDControl &pidc) const noexcept
4348 {
4349 return (pidc.id & EARLY_NEG_MASK) == EARLY_NEG_START;
4350 }
4351
4354 {
4355 return key_id_ == 0 && (op_code_ == CONTROL_V1 || op_code_ == ACK_V1);
4356 }
4357
4360 {
4361 return key_id_ == 0 && op_code_ == CONTROL_WKC_V1;
4362 }
4363
4365 bool is_ack_v1() const
4366 {
4367 return op_code_ == ACK_V1;
4368 }
4369
4371 static void prepend_TLV(Buffer &payload)
4372 {
4373 // The only supported TLV payload for now.
4374 const uint16_t type = htons(EARLY_NEG_FLAGS);
4375 const uint16_t len = htons(sizeof(uint16_t));
4376 const uint16_t flags = htons(EARLY_NEG_FLAG_RESEND_WKC);
4377
4378 payload.prepend(&flags, sizeof(flags));
4379 payload.prepend(&len, sizeof(len));
4380 payload.prepend(&type, sizeof(type));
4381 }
4382
4383 static unsigned char get_server_hard_reset_opfield()
4384 {
4385 return op_compose(CONTROL_HARD_RESET_SERVER_V2, 0);
4386 }
4387
4388 private:
4389 const unsigned int op_code_;
4390 const unsigned int key_id_;
4391 };
4392
4394 {
4395 public:
4396 IvProtoHelper(const OptionList &peer_info)
4397 : proto_field_(peer_info.get_num<unsigned int>("IV_PROTO", 1, 0))
4398 {
4399 }
4400
4402 {
4403 return proto_field_ & iv_proto_flag::IV_PROTO_TLS_KEY_EXPORT;
4404 }
4405
4407 {
4408 return proto_field_ & iv_proto_flag::IV_PROTO_AUTH_FAIL_TEMP;
4409 }
4410
4412 {
4413 return proto_field_ & iv_proto_flag::IV_PROTO_DATA_V2;
4414 }
4415
4417 {
4418 return proto_field_ & iv_proto_flag::IV_PROTO_AUTH_PENDING_KW;
4419 }
4420
4422 {
4423 return proto_field_ & iv_proto_flag::IV_PROTO_PUSH_UPDATE;
4424 }
4425
4427 {
4428 return proto_field_ & iv_proto_flag::IV_PROTO_REQUEST_PUSH;
4429 }
4430
4433 {
4434 return proto_field_ & iv_proto_flag::IV_PROTO_CC_EXIT_NOTIFY;
4435 }
4436
4439 {
4440 return proto_field_ & iv_proto_flag::IV_PROTO_DYN_TLS_CRYPT;
4441 }
4442
4445 {
4446 return proto_field_ & iv_proto_flag::IV_PROTO_DNS_OPTION_V2;
4447 }
4448
4449 private:
4450 unsigned int proto_field_;
4451 };
4452
4453 class TLSWrapPreValidate : public RC<thread_unsafe_refcount>
4454 {
4455 public:
4457
4458 virtual bool validate(const BufferAllocated &net_buf) = 0;
4459 };
4460
4461 // Validate the integrity of a packet, only considering tls-auth HMAC.
4463 {
4464 public:
4465 OPENVPN_SIMPLE_EXCEPTION(tls_auth_pre_validate);
4466
4467 TLSAuthPreValidate(const ProtoConfig &c, const bool server)
4468 {
4469 if (!c.tls_auth_enabled())
4470 throw tls_auth_pre_validate();
4471
4472 // save hard reset op we expect to receive from peer
4473 reset_op = server ? CONTROL_HARD_RESET_CLIENT_V2 : CONTROL_HARD_RESET_SERVER_V2;
4474
4475 // init OvpnHMACInstance
4476 ta_hmac_recv = c.tls_auth_context->new_obj();
4477
4478 // init tls_auth hmac
4479 if (c.key_direction >= 0)
4480 {
4481 // key-direction is 0 or 1
4482 const unsigned int key_dir = c.key_direction
4483 ? OpenVPNStaticKey::INVERSE
4484 : OpenVPNStaticKey::NORMAL;
4485 ta_hmac_recv->init(c.tls_auth_key.slice(OpenVPNStaticKey::HMAC | OpenVPNStaticKey::DECRYPT | key_dir));
4486 }
4487 else
4488 {
4489 // key-direction bidirectional mode
4490 ta_hmac_recv->init(c.tls_auth_key.slice(OpenVPNStaticKey::HMAC));
4491 }
4492 }
4493
4494 bool validate(const BufferAllocated &net_buf)
4495 {
4496 try
4497 {
4498 if (net_buf.empty())
4499 return false;
4500
4501 const unsigned int op = net_buf[0];
4502 if (opcode_extract(op) != reset_op || key_id_extract(op) != 0)
4503 return false;
4504
4505 return ta_hmac_recv->ovpn_hmac_cmp(net_buf.c_data(),
4506 net_buf.size(),
4507 OPCODE_SIZE + ProtoSessionID::SIZE,
4508 ta_hmac_recv->output_size(),
4509 PacketIDControl::size());
4510 }
4511 catch (const BufferException &)
4512 {
4513 }
4514
4515 return false;
4516 }
4517
4518 private:
4520 unsigned int reset_op;
4521 };
4522
4524 {
4525 public:
4526 OPENVPN_SIMPLE_EXCEPTION(tls_crypt_pre_validate);
4527
4528 TLSCryptPreValidate(const ProtoConfig &c, const bool server)
4529 {
4530 const bool tls_crypt_v2_enabled = c.tls_crypt_v2_enabled();
4531
4532 if (!c.tls_crypt_enabled() && !tls_crypt_v2_enabled)
4533 throw tls_crypt_pre_validate();
4534
4535 // save hard reset op we expect to receive from peer
4536 reset_op = CONTROL_HARD_RESET_SERVER_V2;
4537
4538 if (server)
4539 {
4540 // We can't pre-validate because we haven't extracted the server key from
4541 // the server key ID that's present in the client key yet.
4542 if (tls_crypt_v2_enabled && c.tls_crypt_v2_serverkey_id)
4543 {
4544 disabled = true;
4545 return;
4546 }
4547
4548 reset_op = tls_crypt_v2_enabled
4549 ? CONTROL_HARD_RESET_CLIENT_V3
4550 : CONTROL_HARD_RESET_CLIENT_V2;
4551 }
4552
4553 tls_crypt_recv = c.tls_crypt_context->new_obj_recv();
4554
4555 // static direction assignment - not user configurable
4556 const unsigned int key_dir = server ? OpenVPNStaticKey::NORMAL : OpenVPNStaticKey::INVERSE;
4557 tls_crypt_recv->init(c.ssl_factory->libctx(),
4558 c.tls_crypt_key.slice(OpenVPNStaticKey::HMAC | OpenVPNStaticKey::DECRYPT | key_dir),
4559 c.tls_crypt_key.slice(OpenVPNStaticKey::CIPHER | OpenVPNStaticKey::DECRYPT | key_dir));
4560
4561 // needed to create the decrypt buffer during validation
4562 frame = c.frame;
4563 }
4564
4565 bool validate(const BufferAllocated &net_buf)
4566 {
4567 if (disabled)
4568 return true;
4569
4570 try
4571 {
4572 if (net_buf.empty())
4573 return false;
4574
4575 const unsigned int op = net_buf[0];
4576 if (opcode_extract(op) != reset_op || key_id_extract(op) != 0)
4577 return false;
4578
4579 const size_t data_offset = TLSCryptContext::hmac_offset + tls_crypt_recv->output_hmac_size();
4580 if (net_buf.size() < data_offset)
4581 return false;
4582
4583 frame->prepare(Frame::DECRYPT_WORK, work);
4584
4585 // decrypt payload from 'net_buf' into 'work'
4586 const size_t decrypt_bytes = tls_crypt_recv->decrypt(net_buf.c_data() + TLSCryptContext::hmac_offset,
4587 work.data(),
4588 work.max_size(),
4589 net_buf.c_data() + data_offset,
4590 net_buf.size() - data_offset);
4591 if (!decrypt_bytes)
4592 return false;
4593
4594 work.inc_size(decrypt_bytes);
4595
4596 // verify HMAC
4597 return tls_crypt_recv->hmac_cmp(net_buf.c_data(),
4598 TLSCryptContext::hmac_offset,
4599 work.data(),
4600 work.size());
4601 }
4602 catch (const BufferException &)
4603 {
4604 }
4605 return false;
4606 }
4607
4608 protected:
4609 unsigned int reset_op;
4610
4611 private:
4615 bool disabled = false;
4616 };
4617
4618 OPENVPN_SIMPLE_EXCEPTION(select_key_context_error);
4619
4621 const ProtoConfig::Ptr &config_arg, // configuration
4622 const SessionStats::Ptr &stats_arg) // error stats
4623 : proto_callback(cb_arg),
4624 config(config_arg),
4625 stats(stats_arg),
4626 mode_(config_arg->ssl_factory->mode()),
4627 n_key_ids(0),
4628 now_(config_arg->now)
4629 {
4631 }
4632
4634 {
4635 const TLSWrapSelection sel = select_tls_wrap(c);
4636 tls_wrap_mode = sel.mode;
4637 hmac_size = sel.hmac_size;
4638 }
4639
4640 uint32_t get_tls_warnings() const
4641 {
4642 if (primary)
4643 return primary->get_tls_warnings();
4644
4645 OPENVPN_LOG("TLS: primary key context uninitialized. Can't retrieve TLS warnings");
4646 return 0;
4647 }
4648
4649 bool uses_bs64_cipher() const
4650 {
4651 return is_bs64_cipher(conf().dc.cipher());
4652 }
4653
4655 {
4657 }
4658
4660 {
4661 // Both call sites fire on primary->key_id() == 0, which a duplicated -- or
4662 // corrupted, then retransmitted -- soft reset satisfies twice. The switch below
4663 // reads tls_wrap_mode, which this function ends by overwriting, so a second
4664 // pass would land on TLS_CRYPT and mix c.tls_crypt_key: the wrong key, and on
4665 // a tls_crypt_v2_serverkey_id server not a defined one. There is nothing new
4666 // to derive anyway -- same TLS session, same exported material.
4668 return;
4669
4670 OpenVPNStaticKey dyn_key;
4671 key_ctx->export_key_material(dyn_key, "EXPORTER-OpenVPN-dynamic-tls-crypt");
4672
4673 // The mode this session settled on, not what the config allows. A server holding
4674 // both a tls-auth key and tls-crypt-v2 starts every session as TLS_AUTH and only
4675 // decapsulate() converts it, so asking the config here would have such a server
4676 // mix tls_auth_key while its converted tls-crypt-v2 client mixes Kc.
4677 switch (tls_wrap_mode)
4678 {
4679 case TLS_AUTH:
4680 dyn_key.XOR(c.tls_auth_key);
4681 break;
4682 case TLS_CRYPT_V2:
4683 // Kc, this session's own: c.tls_crypt_key is the client's Kc on a client but the
4684 // server key on a server, and with tls_crypt_v2_serverkey_id not even defined, so
4685 // mixing it in would have the two ends derive different keys.
4687 throw proto_error("dynamic tls-crypt with no tls-crypt-v2 client key");
4688 dyn_key.XOR(tls_crypt_client_key);
4689 break;
4690 case TLS_CRYPT:
4691 dyn_key.XOR(c.tls_crypt_key);
4692 break;
4693 case TLS_PLAIN:
4694 break;
4695 }
4696
4698
4699 // get HMAC size from Digest object
4701
4702 ta_pid_send.init();
4703 ta_pid_recv.init("SSL-CC", 0, stats);
4704
4705 reset_tls_crypt(c, dyn_key);
4707 }
4708
4710 {
4711 // The session key is derived from the WKc riding on the first packet we
4712 // decapsulate, so there is nothing to install here -- see decapsulate(). Any key
4713 // this session already holds is left alone: decapsulate() can bring us back here
4714 // for a session already running, and dropping its contexts would leave the next
4715 // control packet it sends with nothing to authenticate itself with.
4716
4717 // Server context, used only to process incoming WKc's. Left unkeyed:
4718 // unwrap_tls_crypt_wkc() keys it, since only it knows which key the WKc needs.
4720 }
4721
4733 void reset(const ProtoSessionID cookie_psid = ProtoSessionID())
4734 {
4735 const ProtoConfig &c = *config;
4736
4737 // defer data channel initialization until after client options pull?
4739
4740 // clear key contexts
4741 reset_all();
4742
4743 // Drop the contexts a previous handshake set up: until the peer is known, no key may
4744 // be left that could authenticate its packets. reset_tls_crypt_server() cannot do it,
4745 // since decapsulate() also calls that for a session already running.
4751
4752 // start with key ID 0
4753 upcoming_key_id = 0;
4754
4755 // tls-auth initialization
4757 switch (tls_wrap_mode)
4758 {
4759 case TLS_CRYPT:
4761 // init tls_crypt packet ID
4762 ta_pid_send.init();
4763 ta_pid_recv.init("SSL-CC", 0, stats);
4764 break;
4765 case TLS_CRYPT_V2:
4766 if (is_server())
4767 // Create the server context the client's WKc is unwrapped with,
4768 // keyed only at unwrap time, when the WKc names its key. tls-crypt
4769 // session key setup is postponed to reception of the WKc too.
4771 else
4772 {
4773 // a client's own Kc, the one its WKc carries to the server
4776 }
4779 // init tls_crypt packet ID
4781 ta_pid_recv.init("SSL-CC", 0, stats);
4782 break;
4783 case TLS_AUTH:
4784 // init OvpnHMACInstance send + recv
4786
4796 ta_pid_send.init(cookie_psid.defined() ? 1 : 0);
4797 ta_pid_recv.init("SSL-CC", 0, stats);
4798 break;
4799 case TLS_PLAIN:
4800 break;
4801 }
4802
4803 // initialize proto session ID
4804 if (cookie_psid.defined())
4805 psid_self = cookie_psid;
4806 else
4808 psid_peer.reset();
4809
4810 // initialize key contexts
4811 primary.reset(new KeyContext(*this, is_client(), cookie_psid.defined()));
4812 OVPN_LOG_VERBOSE(debug_prefix() << " New KeyContext PRIMARY id=" << primary->key_id());
4813
4814 // initialize keepalive timers
4815 keepalive_expire = Time::infinite(); // initially disabled
4816 update_last_sent(); // set timer for initial keepalive send
4817 }
4818
4819 void set_protocol(const Protocol &p)
4820 {
4821 config->set_protocol(p);
4822 if (primary)
4823 primary->set_protocol(p);
4824 if (secondary)
4825 secondary->set_protocol(p);
4826 }
4827
4828 // Free up space when parent object has been halted but
4829 // object destruction is not immediately scheduled.
4831 {
4832 reset_all();
4833 }
4834
4835 // Is primary key defined
4837 {
4838 return bool(primary);
4839 }
4840
4841 virtual ~ProtoContext() = default;
4842
4843 // return the PacketType of an incoming network packet
4845 {
4846 return PacketType(buf, *this);
4847 }
4848
4857 void start(const ProtoSessionID cookie_psid = ProtoSessionID())
4858 {
4859 if (!primary)
4860 throw proto_error("start: no primary key");
4861 primary->start(cookie_psid);
4862 update_last_received(); // set an upper bound on when we expect a response
4863 }
4864
4865#ifdef UNIT_TEST
4866 // Test seam: pretend the server requested resending the tls-crypt-v2 WKc
4867 // (EARLY_NEG_FLAG_RESEND_WKC), so the first control packet carrying SSL
4868 // ciphertext is emitted as CONTROL_WKC_V1 with the WKc appended.
4869 void force_resend_wkc()
4870 {
4871 if (primary)
4872 primary->resend_wkc = true;
4873 }
4874#endif
4875
4876 // trigger a protocol renegotiation
4878 {
4879 // set up dynamic tls-crypt keys when the first rekeying happens
4880 // primary key_id 0 indicates that it is the first rekey
4881 if (conf().dynamic_tls_crypt_enabled() && primary && primary->key_id() == 0)
4883
4884 // initialize secondary key context
4885 new_secondary_key(true);
4886 secondary->start();
4887 }
4888
4889 // Should be called at the end of sequence of send/recv
4890 // operations on underlying protocol object.
4891 // If control_channel is true, do a full flush.
4892 // If control_channel is false, optimize flush for data
4893 // channel only.
4894 void flush(const bool control_channel)
4895 {
4896 if (control_channel || process_events())
4897 {
4898 do
4899 {
4900 if (primary)
4901 primary->flush();
4902 if (secondary)
4903 secondary->flush();
4904 } while (process_events());
4905 }
4906 }
4907
4908 // Perform various time-based housekeeping tasks such as retransmiting
4909 // unacknowleged packets as part of the reliability layer and testing
4910 // for keepalive timouts.
4911 // Should be called at the time returned by next_housekeeping.
4913 {
4914 // handle control channel retransmissions on primary
4915 if (primary)
4916 primary->retransmit();
4917
4918 // handle control channel retransmissions on secondary
4919 if (secondary)
4920 secondary->retransmit();
4921
4922 // handle possible events
4923 flush(false);
4924
4925 // handle keepalive/expiration
4927 }
4928
4929 // When should we next call housekeeping?
4930 // Will return a time value for immediate execution
4931 // if session has been invalidated.
4933 {
4934 if (!invalidated())
4935 {
4936 Time ret = Time::infinite();
4937 if (primary)
4938 ret.min(primary->next_retransmit());
4939 if (secondary)
4940 ret.min(secondary->next_retransmit());
4941 ret.min(keepalive_xmit);
4942 ret.min(keepalive_expire);
4943 return ret;
4944 }
4945 return Time();
4946 }
4947
4948 // send app-level cleartext to remote peer
4949
4951 {
4952 select_control_send_context().app_send(std::move(app_bp));
4953 }
4954
4956 {
4957 control_send(BufferAllocatedRc::Create(std::move(app_buf)));
4958 }
4959
4960 // validate a control channel network packet
4961 bool control_net_validate(const PacketType &type, const Buffer &net_buf)
4962 {
4963 return type.is_defined() && KeyContext::validate(net_buf, *this, now_);
4964 }
4965
4966 // pass received control channel network packets (ciphertext) into protocol object
4967 bool control_net_recv(const PacketType &type, BufferPtr &&net_bp)
4968 {
4969 Packet pkt(std::move(net_bp), type.opcode);
4970 if (type.is_soft_reset() && !renegotiate_request(pkt))
4971 return false;
4972 return select_key_context(type, true).net_recv(std::move(pkt));
4973 }
4974
4982 bool control_net_recv(const PacketType &type, BufferAllocated &&net_buf)
4983 {
4984 return control_net_recv(type, BufferAllocatedRc::Create(std::move(net_buf)));
4985 }
4986
4987 // encrypt a data channel packet using primary KeyContext
4989 {
4990 OVPN_LOG_DEBUG(debug_prefix() << " DATA ENCRYPT size=" << in_out.size());
4991 if (!primary)
4992 throw proto_error("data_encrypt: no primary key");
4993 primary->encrypt(in_out);
4994 }
4995
4996 // decrypt a data channel packet (automatically select primary
4997 // or secondary KeyContext based on packet content)
4998 bool data_decrypt(const PacketType &type, BufferAllocated &in_out)
4999 {
5000 bool ret = false;
5001
5002 OVPN_LOG_DEBUG(debug_prefix() << " DATA DECRYPT key_id=" << select_key_context(type, false).key_id() << " size=" << in_out.size());
5003
5004 select_key_context(type, false).decrypt(in_out);
5005
5006 // update time of most recent packet received
5007 if (!in_out.empty())
5008 {
5010 ret = true;
5011 }
5012
5013 // discard keepalive packets
5014 if (proto_context_private::is_keepalive(in_out))
5015 {
5016 in_out.reset_size();
5017 }
5018
5019 return ret;
5020 }
5021
5022 // enter disconnected state
5023 void disconnect(const Error::Type reason)
5024 {
5025 if (primary)
5026 primary->invalidate(reason);
5027 if (secondary)
5028 secondary->invalidate(reason);
5029 }
5030
5031 // normally used by UDP clients to tell the server that
5032 // they are disconnecting
5034 {
5035#ifndef OPENVPN_DISABLE_EXPLICIT_EXIT // explicit exit should always be enabled in production
5036 if (!is_client() || !is_udp() || !primary)
5037 {
5038 return;
5039 }
5040
5041 if (config->cc_exit_notify)
5042 {
5043 write_control_string(std::string("EXIT"));
5044 primary->flush();
5045 }
5046 else
5047 {
5048 primary->send_explicit_exit_notify();
5049 }
5050#endif // OPENVPN_DISABLE_EXPLICIT_EXIT
5051 }
5052
5053 // should be called after a successful network packet transmit
5055 {
5056 keepalive_xmit = *now_ + config->keepalive_ping;
5057 }
5058
5059 // Can we call data_encrypt or data_decrypt yet?
5060 // Returns true if primary data channel is in ACTIVE state.
5062 {
5063 return primary && primary->data_channel_ready();
5064 }
5065
5066 // total number of SSL/TLS negotiations during lifetime of ProtoContext object
5067 unsigned int negotiations() const
5068 {
5069 return n_key_ids;
5070 }
5071
5072 // worst-case handshake time
5073 const Time::Duration &slowest_handshake()
5074 {
5075 return slowest_handshake_;
5076 }
5077
5078 // was primary context invalidated by an exception?
5079 bool invalidated() const
5080 {
5081 return primary && primary->invalidated();
5082 }
5083
5084 // reason for invalidation if invalidated() above returns true
5086 {
5087 return primary->invalidation_reason();
5088 }
5089
5090 // Do late initialization of data channel, for example
5091 // on client after server push, or on server after client
5092 // capabilities are known.
5094 {
5095 dc_deferred = false;
5096
5097 // initialize data channel (crypto & compression)
5098 if (primary)
5099 primary->init_data_channel();
5100 if (secondary)
5101 secondary->init_data_channel();
5102 }
5103
5104 // Call on client with server-pushed options
5106 {
5107 // modify config with pushed options
5108 config->process_push(opt, pco);
5109
5110 // in case keepalive parms were modified by push
5112 }
5113
5114 // Return the current transport alignment adjustment
5115 size_t align_adjust_hint() const
5116 {
5117 return config->enable_op32 ? 0 : 1;
5118 }
5119
5120 // Return true if keepalive parameter(s) are enabled
5122 {
5123 return config->keepalive_ping.enabled()
5124 || config->keepalive_timeout.enabled();
5125 }
5126
5127 // Disable keepalive for rest of session,
5128 // but return the previous keepalive parameters.
5129 void disable_keepalive(unsigned int &keepalive_ping,
5130 unsigned int &keepalive_timeout)
5131 {
5132 keepalive_ping = config->keepalive_ping.enabled()
5133 ? clamp_to_typerange<std::remove_reference_t<decltype(keepalive_ping)>>(config->keepalive_ping.to_seconds())
5134 : 0;
5135 keepalive_timeout = config->keepalive_timeout.enabled()
5136 ? clamp_to_typerange<std::remove_reference_t<decltype(keepalive_timeout)>>(config->keepalive_timeout.to_seconds())
5137 : 0;
5138 config->keepalive_ping = Time::Duration::infinite();
5139 config->keepalive_timeout = Time::Duration::infinite();
5140 config->keepalive_timeout_early = Time::Duration::infinite();
5142 }
5143
5144 // Notify our component KeyContext when per-key Data Limits have been reached
5145 void data_limit_notify(const unsigned int key_id,
5146 const DataLimit::Mode cdl_mode,
5147 const DataLimit::State cdl_status)
5148 {
5149 if (primary && key_id == primary->key_id())
5150 primary->data_limit_notify(cdl_mode, cdl_status);
5151 else if (secondary && key_id == secondary->key_id())
5152 secondary->data_limit_notify(cdl_mode, cdl_status);
5153 }
5154
5155 // access the data channel settings
5157 {
5158 return config->dc;
5159 }
5160
5161 // reset the data channel factory
5163 {
5164 config->dc.reset();
5165 }
5166
5167 // set the local peer ID (or -1 to disable)
5168 void set_local_peer_id(const int local_peer_id)
5169 {
5170 config->local_peer_id = local_peer_id;
5171 }
5172
5173 // current time
5174 const Time &now() const
5175 {
5176 return *now_;
5177 }
5179 {
5180 now_->update();
5181 }
5182
5183 // frame
5184 const Frame &frame() const
5185 {
5186 return *config->frame;
5187 }
5188 const Frame::Ptr &frameptr() const
5189 {
5190 return config->frame;
5191 }
5192
5193 // client or server?
5194 const Mode &mode() const
5195 {
5196 return mode_;
5197 }
5198 bool is_server() const
5199 {
5200 return mode_.is_server();
5201 }
5202 bool is_client() const
5203 {
5204 return mode_.is_client();
5205 }
5206
5207 // tcp/udp mode
5208 bool is_tcp()
5209 {
5210 return config->protocol.is_tcp();
5211 }
5212 bool is_udp()
5213 {
5214 return config->protocol.is_udp();
5215 }
5216
5217 // configuration
5218 const ProtoConfig &conf() const
5219 {
5220 return *config;
5221 }
5223 {
5224 return *config;
5225 }
5227 {
5228 return config;
5229 }
5230
5231 // stats
5233 {
5234 return *stats;
5235 }
5236
5237 // debugging
5239 {
5240 return primary_state() == C_WAIT_RESET_ACK;
5241 }
5242
5243 protected:
5244 int primary_state() const
5245 {
5246 if (primary)
5247 return primary->get_state();
5248 return STATE_UNDEF;
5249 }
5250
5251 private:
5253 {
5254 if (primary)
5256 primary.reset();
5257 secondary.reset();
5258 }
5259
5260 // Called on client to request username/password credentials.
5261 // delegated to the callback/parent
5263 {
5265 }
5266
5268 {
5269 keepalive_expire = *now_ + (data_channel_ready() ? config->keepalive_timeout : config->keepalive_timeout_early);
5270 }
5271
5272 void net_send(const unsigned int key_id, const Packet &net_pkt)
5273 {
5275 }
5276
5277 void app_recv(const unsigned int key_id, BufferPtr &&to_app_buf)
5278 {
5280 }
5281
5282 // we're getting a request from peer to renegotiate.
5284 {
5285 // set up dynamic tls-crypt keys when the first rekeying happens
5286 // primary key_id 0 indicates that it is the first rekey
5287 if (conf().dynamic_tls_crypt_enabled() && primary && primary->key_id() == 0)
5289
5290 if (KeyContext::validate(pkt.buffer(), *this, now_))
5291 {
5292 new_secondary_key(false);
5293 return true;
5294 }
5295 return false;
5296 }
5297
5298 // select a KeyContext (primary or secondary) for received network packets
5299 KeyContext &select_key_context(const PacketType &type, const bool control)
5300 {
5301 const unsigned int flags = type.flags & (PacketType::DEFINED | PacketType::SECONDARY | PacketType::CONTROL);
5302 if (!control)
5303 {
5304 if (flags == (PacketType::DEFINED) && primary)
5305 return *primary;
5307 return *secondary;
5308 }
5309 else
5310 {
5312 {
5313 return *primary;
5314 }
5316 && secondary)
5317 {
5318 return *secondary;
5319 }
5320 }
5321 throw select_key_context_error();
5322 }
5323
5324 // Select a KeyContext (primary or secondary) for control channel sends.
5325 // Even after new key context goes active, we still wait for
5326 // KEV_BECOME_PRIMARY event (controlled by the become_primary duration
5327 // in Config) before we use it for app-level control-channel
5328 // transmissions. Simulations have found this method to be more reliable
5329 // than the immediate rollover practiced by OpenVPN 2.x.
5331 {
5332 OVPN_LOG_VERBOSE(debug_prefix() << " CONTROL SEND");
5333 if (!primary)
5334 throw proto_error("select_control_send_context: no primary key");
5335 return *primary;
5336 }
5337
5338 // Possibly send a keepalive message, and check for expiration
5339 // of session due to lack of received packets from peer.
5341 {
5342 const Time now = *now_;
5343
5344 // check for keepalive timeouts
5345 if (now >= keepalive_xmit && primary)
5346 {
5347 primary->send_keepalive();
5349 }
5350 if (now >= keepalive_expire)
5351 {
5352 // no contact with peer, disconnect
5355 }
5356 }
5357
5358 // Process KEV_x events
5359 // Return true if any events were processed.
5361 {
5362 bool did_work = false;
5363
5364 // primary
5365 if (primary && primary->event_pending())
5366 {
5368 did_work = true;
5369 }
5370
5371 // secondary
5372 if (secondary && secondary->event_pending())
5373 {
5375 did_work = true;
5376 }
5377
5378 return did_work;
5379 }
5380
5381 // Create a new secondary key.
5382 // initiator --
5383 // false : remote renegotiation request
5384 // true : local renegotiation request
5385 void new_secondary_key(const bool initiator)
5386 {
5387 // Create the secondary
5388 secondary.reset(new KeyContext(*this, initiator));
5390 << " New KeyContext SECONDARY id=" << secondary->key_id()
5391 << (initiator ? " local-triggered" : " remote-triggered"));
5392 }
5393
5394 // Promote a newly renegotiated KeyContext to primary status.
5395 // This is usually triggered by become_primary variable (Time::Duration)
5396 // in Config.
5398 {
5400 if (primary)
5402 if (secondary)
5403 secondary->prepare_expire();
5404 OVPN_LOG_VERBOSE(debug_prefix() << " PRIMARY_SECONDARY_SWAP");
5405 }
5406
5408 {
5409 const KeyContext::EventType ev = primary->get_event();
5410 if (ev != KeyContext::KEV_NONE)
5411 {
5412 primary->reset_event();
5413 switch (ev)
5414 {
5416 OVPN_LOG_VERBOSE(debug_prefix() << " SESSION_ACTIVE");
5418 proto_callback->active(true);
5419 break;
5422 renegotiate();
5423 break;
5425 if (secondary && !secondary->invalidated())
5427 else
5428 {
5430 // primary context expired and no secondary context available
5432 }
5433 break;
5436 // primary negotiation failed
5438 break;
5439 default:
5440 break;
5441 }
5442 }
5443 primary->set_next_event_if_unspecified();
5444 }
5445
5447 {
5448 const KeyContext::EventType ev = secondary->get_event();
5449 if (ev != KeyContext::KEV_NONE)
5450 {
5451 secondary->reset_event();
5452 switch (ev)
5453 {
5456 if (primary)
5457 primary->prepare_expire();
5458 proto_callback->active(false);
5459 break;
5461 if (!secondary->invalidated())
5463 break;
5466 secondary.reset();
5467 break;
5469 if (primary)
5471 secondary->become_primary_time());
5472 break;
5475 [[fallthrough]];
5478 renegotiate();
5479 break;
5480 default:
5481 break;
5482 }
5483 }
5484 if (secondary)
5485 secondary->set_next_event_if_unspecified();
5486 }
5487
5488 std::string debug_prefix()
5489 {
5490 std::string ret = openvpn::to_string(now_->raw());
5491 ret += is_server() ? " SERVER[" : " CLIENT[";
5492 if (primary)
5493 ret += openvpn::to_string(primary->key_id());
5494 if (secondary)
5495 {
5496 ret += '/';
5497 ret += openvpn::to_string(secondary->key_id());
5498 }
5499 ret += ']';
5500 return ret;
5501 }
5502
5503 // key_id starts at 0, increments to KEY_ID_MASK, then recycles back to 1.
5504 // Therefore, if key_id is 0, it is the first key.
5505 unsigned int next_key_id()
5506 {
5507 ++n_key_ids;
5508 unsigned int ret = upcoming_key_id;
5509 if ((upcoming_key_id = (upcoming_key_id + 1) & KEY_ID_MASK) == 0)
5510 upcoming_key_id = 1;
5511 return ret;
5512 }
5513
5514 // call whenever keepalive parms are modified,
5515 // to reset timers
5517 {
5519
5520 // For keepalive_xmit timer, don't reschedule current cycle
5521 // unless it would fire earlier. Subsequent cycles will
5522 // time according to new keepalive_ping value.
5523 const Time kx = *now_ + config->keepalive_ping;
5524 if (kx < keepalive_xmit)
5525 keepalive_xmit = kx;
5526 }
5527
5528 // BEGIN ProtoContext data members
5529
5536
5539
5542 Mode mode_; // client or server
5543 unsigned int upcoming_key_id = 0;
5544 unsigned int n_key_ids;
5545
5546 TimePtr now_; // pointer to current time (a clone of config->now)
5547 Time keepalive_xmit; // time in future when we will transmit a keepalive (subject to continuous change)
5548 Time keepalive_expire; // time in future when we must have received a packet from peer or we will timeout session
5549
5550 Time::Duration slowest_handshake_; // longest time to reach a successful handshake
5551
5554
5557
5559
5570
5579
5582
5585
5588 bool dc_deferred = false;
5589
5590 // END ProtoContext data members
5591};
5592
5593} // namespace openvpn
5594
5595#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
bool defined() const
Returns true if the buffer is not empty.
Definition buffer.hpp:1223
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 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 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:4444
bool client_supports_auth_pending_kwargs() const
Definition proto.hpp:4416
IvProtoHelper(const OptionList &peer_info)
Definition proto.hpp:4396
bool client_supports_temp_auth_failed() const
Definition proto.hpp:4406
bool client_supports_exit_notify() const
Checks if the client is able to send an explicit EXIT message before exiting.
Definition proto.hpp:4432
bool client_supports_dynamic_tls_crypt() const
Checks if the client can handle dynamic TLS-crypt.
Definition proto.hpp:4438
void encapsulate(id_t id, Packet &pkt)
Definition proto.hpp:3862
static const char * event_type_string(const EventType et)
Definition proto.hpp:2220
bool decapsulate_post_process(Packet &pkt, ProtoSessionID &src_psid, const PacketIDControl pid)
Definition proto.hpp:3892
void kev_error(const EventType ev, const Error::Type reason)
Definition proto.hpp:3463
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:2587
static BufferAllocated static_work
Definition proto.hpp:4324
static bool validate(const Buffer &net_buf, ProtoContext &proto, TimePtr now)
Definition proto.hpp:2597
void set_protocol(const Protocol &p)
Definition proto.hpp:2280
void prepend_dest_psid_and_acks(Buffer &buf, unsigned int opcode)
Definition proto.hpp:3711
TLSPRFInstance::Ptr tlsprf
Definition proto.hpp:4311
bool net_recv(Packet &&pkt)
Definition proto.hpp:2365
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:3108
void set_state(const int newstate)
Definition proto.hpp:3311
std::deque< BufferPtr > app_pre_write_queue
Definition proto.hpp:4317
void recv_auth(BufferPtr buf)
Definition proto.hpp:3651
bool decapsulate_tls_plain(Packet &pkt)
Definition proto.hpp:4018
static bool validate_tls_plain(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:3241
void app_recv(BufferPtr &&to_app_buf)
Definition proto.hpp:3558
bool pkt_from_peer
Set per packet by accept_peer(), read by decapsulate()
Definition proto.hpp:4305
void net_send(const Packet &net_pkt, const Base::NetSendType nstype)
Definition proto.hpp:3591
size_t control_channel_wrap_overhead() const
Definition proto.hpp:3823
void app_send(BufferPtr &&bp)
Definition proto.hpp:2353
static size_t tls_crypt_frame_size(const ProtoConfig &proto_config)
Smallest tls-crypt frame a WKc can be appended to.
Definition proto.hpp:2834
void set_event(const EventType current)
Definition proto.hpp:3319
void raw_recv(Packet &&raw_pkt)
Definition proto.hpp:3537
void gen_head(const unsigned int opcode, BufferAllocated &buf)
Definition proto.hpp:3790
size_t control_ciphertext_capacity(id_t id) const
Definition proto.hpp:3841
std::unique_ptr< DataLimit > data_limit
Definition proto.hpp:4320
void prepare_expire(const EventType current_ev=KeyContext::KEV_NONE)
Definition proto.hpp:2444
void decrypt(BufferAllocated &buf)
Definition proto.hpp:2394
void send_data_channel_message(const unsigned char *data, const size_t size)
Definition proto.hpp:2559
void gen_head_tls_crypt(const unsigned int opcode, BufferAllocated &buf)
Definition proto.hpp:3774
void gen_head_tls_plain(const unsigned int opcode, Buffer &buf)
Definition proto.hpp:3785
void encrypt(BufferAllocated &buf)
Definition proto.hpp:2373
void accept_peer(const ProtoSessionID &src_psid)
Adopt src_psid as our peer, and mark this packet as ours.
Definition proto.hpp:3749
bool recv_auth_complete(BufferComplete &bc) const
Definition proto.hpp:3668
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:2926
bool verify_src_psid(const ProtoSessionID &src_psid)
Definition proto.hpp:3729
void generate_ack(Packet &pkt)
Definition proto.hpp:3882
bool verify_dest_psid(Buffer &buf)
Definition proto.hpp:3756
Error::Type invalidation_reason() const
Definition proto.hpp:2500
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:4070
bool packet_carries_wkc(id_t id) const
Definition proto.hpp:3812
bool parse_early_negotiation(const Packet &pkt)
Definition proto.hpp:3493
void calculate_mssfix(ProtoConfig &c)
Definition proto.hpp:2665
bool decapsulate_tls_crypt(Packet &pkt)
Definition proto.hpp:3981
static bool validate_tls_crypt(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:3173
void start(const ProtoSessionID cookie_psid=ProtoSessionID())
Initialize the state machine and start protocol negotiation.
Definition proto.hpp:2297
void invalidate(const Error::Type reason)
Definition proto.hpp:2324
static size_t wkc_overhead(const ProtoConfig &proto_config)
What a WKc holds besides the client key and the metadata.
Definition proto.hpp:2850
uint32_t get_tls_warnings() const
Definition proto.hpp:2285
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:2871
void gen_head_tls_auth(const unsigned int opcode, Buffer &buf)
Definition proto.hpp:3769
void app_send_validate(BufferPtr &&bp)
Definition proto.hpp:2345
bool decapsulate_by_wrap_mode(Packet &pkt)
Decapsulate pkt with the wrap mode this session is in.
Definition proto.hpp:4178
OPENVPN_SIMPLE_EXCEPTION(tls_crypt_unwrap_wkc_error)
void data_limit_event(const DataLimit::Mode mode, const DataLimit::State state)
Definition proto.hpp:3384
CryptoDCInstance::Ptr crypto
Definition proto.hpp:4310
KeyContext(ProtoContext &p, const bool initiator, bool psid_cookie_mode=false)
Definition proto.hpp:2247
unsigned int key_id() const
Definition proto.hpp:2506
static bool validate_tls_auth(Buffer &recv, ProtoContext &proto, TimePtr now)
Definition proto.hpp:3125
unsigned int initial_op(const bool sender, const bool tls_crypt_v2) const
Definition proto.hpp:3470
int seconds_until(const Time &next_time)
Definition proto.hpp:4284
static const char * state_string(const int s)
Definition proto.hpp:4252
void data_limit_notify(const DataLimit::Mode cdl_mode, const DataLimit::State cdl_status)
Definition proto.hpp:2816
bool verify_wkc_metadata(WkcMetadata &metadata)
Put the record a WKc carried to the embedder's hook, if it installed one.
Definition proto.hpp:4147
bool do_encrypt(BufferAllocated &buf, const bool compress_hint)
Definition proto.hpp:3261
std::unique_ptr< DataChannelKey > data_channel_key
Definition proto.hpp:4318
bool data_limit_add(const DataLimit::Mode mode, const size_t size)
Definition proto.hpp:3373
void set_event(const EventType current, const EventType next, const Time &next_time)
Definition proto.hpp:3327
void rekey(const CryptoDCInstance::RekeyType type)
Definition proto.hpp:2523
bool decapsulate(Packet &pkt)
Definition proto.hpp:4075
void key_limit_reneg(const EventType ev, const Time &t)
Definition proto.hpp:2459
bool decapsulate_tls_auth(Packet &pkt)
Definition proto.hpp:3961
PacketType(const Buffer &buf, class ProtoContext &proto)
Definition proto.hpp:1350
bool contains_tls_ciphertext() const
Definition proto.hpp:1684
Packet(BufferPtr &&buf_arg, const unsigned int opcode_arg=CONTROL_V1)
Definition proto.hpp:1653
void frame_prepare(const Frame &frame, const unsigned int context)
Definition proto.hpp:1673
const Buffer & buffer() const
Definition proto.hpp:1696
const BufferPtr & buffer_ptr()
Definition proto.hpp:1692
Wrap an out-of-band SERVER_PROBE / unwrap the matching PROBE_REPLY.
Definition proto.hpp:1996
TLSCryptInstance::Ptr tls_crypt_recv
Definition proto.hpp:2114
PacketIDControlSend ta_pid_send
Definition proto.hpp:2116
OvpnHMACInstance::Ptr ta_hmac_send
Definition proto.hpp:2111
UnwrapStatus unwrap(BufferAllocated &recv, BufferAllocated &work, ProtoSessionID &src_psid, PacketIDControl &pid)
Unwrap a received PROBE_REPLY in place.
Definition proto.hpp:2069
TLSCryptInstance::Ptr tls_crypt_send
Definition proto.hpp:2113
static constexpr unsigned int KEY_ID
Definition proto.hpp:2105
const ProtoSessionID & self_psid() const
the client session id carried in the probe (echoed back in the reply)
Definition proto.hpp:2029
void wrap(BufferAllocated &buf, BufferAllocated &work)
Wrap an already-encoded SERVER_PROBE payload in place.
Definition proto.hpp:2040
ProbeWrap(const ProtoConfig::Ptr &config_arg, const SessionStats::Ptr &stats)
Pick the wrap mode from config_arg and build the crypto contexts for it.
Definition proto.hpp:1999
OvpnHMACInstance::Ptr ta_hmac_recv
Definition proto.hpp:2112
PacketIDControlReceive ta_pid_recv
Definition proto.hpp:2117
void parse_pushed_peer_id(const OptionList &opt)
Definition proto.hpp:828
PeerInfo::Set::Ptr extra_peer_info
extra peer info key/value pairs generated by client app
Definition proto.hpp:464
std::string peer_info_string(bool supports_epoch_data) const
Definition proto.hpp:1146
void build_connect_time_peer_info_string(TransportClient::Ptr transport)
Definition proto.hpp:1128
std::string relay_prefix(const char *optname) const
Definition proto.hpp:1303
void load_common(const OptionList &opt, const ProtoContextCompressionOptions &pco, const LoadCommonType type)
Definition proto.hpp:1253
SSLFactoryAPI::Ptr ssl_factory
Definition proto.hpp:368
void set_protocol(const Protocol &p)
Definition proto.hpp:1019
TLSCryptContext::Ptr tls_crypt_context
Definition proto.hpp:447
TLSCryptFactory::Ptr tls_crypt_factory
Definition proto.hpp:446
TLSCryptMetadataFactory::Ptr tls_crypt_metadata_factory
Definition proto.hpp:449
bool tls_crypt_v2_serverkey_id
do we expect keys to contain a server key ID?
Definition proto.hpp:434
std::string tls_crypt_v2_serverkey_dir
server keys location, if tls_crypt_v2_serverkey_id is true
Definition proto.hpp:437
void show_cc_enc_option(std::ostringstream &os) const
Definition proto.hpp:980
BufferAllocated wkc
leave this undefined to disable tls-crypt-v2 on client
Definition proto.hpp:440
void set_tls_auth_digest(const CryptoAlgs::Type digest)
Definition proto.hpp:1025
void parse_pushed_data_channel_options(const OptionList &opt)
Definition proto.hpp:791
AppControlMessageReceiver app_control_recv
Definition proto.hpp:468
void get_data_channel_options(std::ostringstream &os) const
Definition proto.hpp:965
void set_xmit_creds(const bool xmit_creds_arg)
Definition proto.hpp:1047
void process_push(const OptionList &opt, const ProtoContextCompressionOptions &pco)
Definition proto.hpp:732
AppControlMessageConfig app_control_config
Definition proto.hpp:467
OpenVPNStaticKey tls_crypt_key
leave this undefined to disable tls-crypt/tls-crypt-v2
Definition proto.hpp:428
void load(const OptionList &opt, const ProtoContextCompressionOptions &pco, const int default_key_direction, const bool server)
Definition proto.hpp:499
void parse_pushed_protocol_flags(const OptionList &opt)
Definition proto.hpp:851
OpenVPNStaticKey tls_auth_key
leave this undefined to disable tls_auth
Definition proto.hpp:425
PeerInfo::Set::Ptr extra_peer_info_transport
Definition proto.hpp:471
std::string show_options() const
Definition proto.hpp:1000
Time::Duration keepalive_timeout_early
Definition proto.hpp:461
unsigned tls_crypt_
needed to distinguish between tls-crypt and tls-crypt-v2 server mode
Definition proto.hpp:431
void parse_custom_app_control(const OptionList &opt)
Definition proto.hpp:763
void parse_pushed_compression(const OptionList &opt, const ProtoContextCompressionOptions &pco)
Definition proto.hpp:913
OvpnHMACContext::Ptr tls_auth_context
Definition proto.hpp:443
TLSPRFFactory::Ptr tlsprf_factory
Definition proto.hpp:374
StrongRandomAPI::Ptr rng
Definition proto.hpp:385
OvpnHMACFactory::Ptr tls_auth_factory
Definition proto.hpp:442
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:4353
static unsigned char get_server_hard_reset_opfield()
Definition proto.hpp:4383
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:4359
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:4347
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:4365
PsidCookieHelper(unsigned int op_field)
Definition proto.hpp:4330
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:4371
bool is_tls_crypt_v2() const noexcept
Returns true if this is a TLS crypt V2 protocol packet.
Definition proto.hpp:4341
TLSAuthPreValidate(const ProtoConfig &c, const bool server)
Definition proto.hpp:4467
OPENVPN_SIMPLE_EXCEPTION(tls_auth_pre_validate)
bool validate(const BufferAllocated &net_buf)
Definition proto.hpp:4494
OPENVPN_SIMPLE_EXCEPTION(tls_crypt_pre_validate)
TLSCryptPreValidate(const ProtoConfig &c, const bool server)
Definition proto.hpp:4528
bool validate(const BufferAllocated &net_buf)
Definition proto.hpp:4565
virtual bool validate(const BufferAllocated &net_buf)=0
static void wrap_tls_plain(const unsigned int opcode, Buffer &buf, const ProtoSessionID &psid_self, const unsigned int key_id)
plaintext control channel: [op][psid][payload]
Definition proto.hpp:1805
void data_limit_notify(const unsigned int key_id, const DataLimit::Mode cdl_mode, const DataLimit::State cdl_status)
Definition proto.hpp:5145
bool control_net_recv(const PacketType &type, BufferPtr &&net_bp)
Definition proto.hpp:4967
void set_local_peer_id(const int local_peer_id)
Definition proto.hpp:5168
uint32_t get_tls_warnings() const
Definition proto.hpp:4640
void send_explicit_exit_notify()
Definition proto.hpp:5033
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, process_server_push_error)
bool is_client() const
Definition proto.hpp:5202
void net_send(const unsigned int key_id, const Packet &net_pkt)
Definition proto.hpp:5272
const Time::Duration & slowest_handshake()
Definition proto.hpp:5073
const Time & now() const
Definition proto.hpp:5174
CryptoDCSettings & dc_settings()
Definition proto.hpp:5156
void flush(const bool control_channel)
Definition proto.hpp:4894
void set_dynamic_tls_crypt(const ProtoConfig &c, const KeyContext::Ptr &key_ctx)
Definition proto.hpp:4659
OPENVPN_SIMPLE_EXCEPTION(select_key_context_error)
void control_send(BufferPtr &&app_bp)
Definition proto.hpp:4950
KeyContext & select_control_send_context()
Definition proto.hpp:5330
bool uses_bs64_cipher() const
Definition proto.hpp:4649
void process_secondary_event()
Definition proto.hpp:5446
void reset_tls_crypt(const ProtoConfig &c, const OpenVPNStaticKey &key)
Definition proto.hpp:4654
OpenVPNStaticKey tls_crypt_client_key
Kc, the tls-crypt-v2 client key this session's control channel is keyed with.
Definition proto.hpp:5569
PacketType packet_type(const Buffer &buf)
Definition proto.hpp:4844
void data_encrypt(BufferAllocated &in_out)
Definition proto.hpp:4988
void reset_tls_crypt_server(const ProtoConfig &c)
Definition proto.hpp:4709
bool dynamic_tls_crypt_keyed
Whether set_dynamic_tls_crypt() has keyed this session already.
Definition proto.hpp:5578
TLSCryptInstance::Ptr tls_crypt_recv
Definition proto.hpp:5556
bool is_keepalive_enabled() const
Definition proto.hpp:5121
KeyContext::Ptr primary
Definition proto.hpp:5586
TLSCryptInstance::Ptr tls_crypt_server
Definition proto.hpp:5558
static UnwrapStatus unwrap_tls_auth(Buffer &recv, const size_t hmac_size, OvpnHMACInstance &ta_hmac_recv, const PacketIDControlReceive &pid_recv, ProtoSessionID &src_psid, PacketIDControl &pid)
Definition proto.hpp:1830
static void build_tls_auth(const ProtoConfig &c, OvpnHMACInstance::Ptr &send, OvpnHMACInstance::Ptr &recv)
Definition proto.hpp:1908
const Frame & frame() const
Definition proto.hpp:5184
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:326
static S read_auth_string(Buffer &buf)
Definition proto.hpp:1586
ProtoConfig::Ptr conf_ptr() const
Definition proto.hpp:5226
static void wrap_tls_auth(const unsigned int opcode, Buffer &buf, PacketIDControlSend &pid_send, const PacketIDControl::time_t now_secs, const size_t hmac_size, const ProtoSessionID &psid_self, const unsigned int key_id, OvpnHMACInstance &ta_hmac_send)
tls-auth: [op][psid][hmac][pid][payload]
Definition proto.hpp:1730
ProtoSessionID psid_peer
Definition proto.hpp:5584
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_option_error)
void process_primary_event()
Definition proto.hpp:5407
const Mode & mode() const
Definition proto.hpp:5194
TLSCryptInstance::Ptr tls_crypt_send
Definition proto.hpp:5555
void process_push(const OptionList &opt, const ProtoContextCompressionOptions &pco)
Definition proto.hpp:5105
static void write_auth_string(const S &str, Buffer &buf)
Definition proto.hpp:1572
void client_auth(Buffer &buf)
Definition proto.hpp:5262
ProtoConfig & conf()
Definition proto.hpp:5222
static const char * opcode_name(const unsigned int opcode)
Definition proto.hpp:1431
static unsigned int opcode_extract(const unsigned int op)
Definition proto.hpp:311
void set_protocol(const Protocol &p)
Definition proto.hpp:4819
static unsigned int key_id_extract(const unsigned int op)
Definition proto.hpp:316
ProtoSessionID psid_self
Definition proto.hpp:5583
static S read_control_string(const Buffer &buf)
Definition proto.hpp:1612
void write_control_string(const S &str)
Definition proto.hpp:1633
bool data_channel_ready() const
Definition proto.hpp:5061
void keepalive_housekeeping()
Definition proto.hpp:5340
Time::Duration slowest_handshake_
Definition proto.hpp:5550
unsigned int upcoming_key_id
Definition proto.hpp:5543
static bool opcode_carries_wkc(const unsigned int opcode)
Does a packet with this opcode carry a WKc?
Definition proto.hpp:1724
static void wrap_tls_crypt(const unsigned int opcode, BufferAllocated &buf, BufferAllocated &work, Frame &frame, PacketIDControlSend &pid_send, const PacketIDControl::time_t now_secs, const size_t hmac_size, const ProtoSessionID &psid_self, const unsigned int key_id, TLSCryptInstance &tls_crypt_send, const Buffer *wkc)
Definition proto.hpp:1756
static unsigned int op32_compose(const unsigned int opcode, const unsigned int key_id, const int op_peer_id)
Definition proto.hpp:333
size_t align_adjust_hint() const
Definition proto.hpp:5115
PacketIDControlReceive ta_pid_recv
Definition proto.hpp:5581
ProtoContextCallbackInterface * proto_callback
Definition proto.hpp:5535
void reset_tls_wrap_mode(const ProtoConfig &c)
Definition proto.hpp:4633
SessionStats & stat() const
Definition proto.hpp:5232
bool is_server() const
Definition proto.hpp:5198
OvpnHMACInstance::Ptr ta_hmac_recv
Definition proto.hpp:5553
std::string dump_packet(const Buffer &buf)
Definition proto.hpp:1457
void disconnect(const Error::Type reason)
Definition proto.hpp:5023
static uint16_t read_uint16_length(Buffer &buf)
Definition proto.hpp:1560
bool control_net_validate(const PacketType &type, const Buffer &net_buf)
Definition proto.hpp:4961
KeyContext & select_key_context(const PacketType &type, const bool control)
Definition proto.hpp:5299
static void write_empty_string(Buffer &buf)
Definition proto.hpp:1606
static TLSWrapSelection select_tls_wrap(const ProtoConfig &c)
Definition proto.hpp:1972
TLSWrapMode tls_wrap_mode
Definition proto.hpp:5541
void app_recv(const unsigned int key_id, BufferPtr &&to_app_buf)
Definition proto.hpp:5277
void keepalive_parms_modified()
Definition proto.hpp:5516
int primary_state() const
Definition proto.hpp:5244
static void write_control_string(const S &str, Buffer &buf)
Definition proto.hpp:1599
void control_send(BufferAllocated &&app_buf)
Definition proto.hpp:4955
bool data_decrypt(const PacketType &type, BufferAllocated &in_out)
Definition proto.hpp:4998
void disable_keepalive(unsigned int &keepalive_ping, unsigned int &keepalive_timeout)
Definition proto.hpp:5129
static constexpr PacketIDControl::id_t EARLY_NEG_MASK
Definition proto.hpp:309
static constexpr PacketIDControl::id_t EARLY_NEG_START
Definition proto.hpp:308
Error::Type invalidation_reason() const
Definition proto.hpp:5085
static size_t op_head_size(const unsigned int op)
Definition proto.hpp:321
static UnwrapStatus unwrap_tls_crypt(BufferAllocated &recv, BufferAllocated &work, Frame &frame, const size_t hmac_size, TLSCryptInstance &tls_crypt_recv, const PacketIDControlReceive &pid_recv, ProtoSessionID &src_psid, PacketIDControl &pid)
Definition proto.hpp:1859
void new_secondary_key(const bool initiator)
Definition proto.hpp:5385
void update_last_received()
Definition proto.hpp:5267
void promote_secondary_to_primary()
Definition proto.hpp:5397
bool is_state_client_wait_reset_ack() const
Definition proto.hpp:5238
unsigned int negotiations() const
Definition proto.hpp:5067
PacketIDControlSend ta_pid_send
Definition proto.hpp:5580
Time next_housekeeping() const
Definition proto.hpp:4932
ProtoContext(ProtoContextCallbackInterface *cb_arg, const ProtoConfig::Ptr &config_arg, const SessionStats::Ptr &stats_arg)
Definition proto.hpp:4620
static void write_uint16_length(const size_t size, Buffer &buf)
Definition proto.hpp:1552
SessionStats::Ptr stats
Definition proto.hpp:5538
static constexpr size_t OPCODE_SIZE
Definition proto.hpp:216
unsigned int n_key_ids
Definition proto.hpp:5544
ProtoConfig::Ptr config
Definition proto.hpp:5537
bool control_net_recv(const PacketType &type, BufferAllocated &&net_buf)
pass received control channel network packets (ciphertext) into protocol object
Definition proto.hpp:4982
virtual ~ProtoContext()=default
std::string debug_prefix()
Definition proto.hpp:5488
static constexpr size_t APP_MSG_MAX
Definition proto.hpp:214
const Frame::Ptr & frameptr() const
Definition proto.hpp:5188
bool invalidated() const
Definition proto.hpp:5079
void reset(const ProtoSessionID cookie_psid=ProtoSessionID())
Resets ProtoContext *this to it's initial state.
Definition proto.hpp:4733
void start(const ProtoSessionID cookie_psid=ProtoSessionID())
Initialize the state machine and start protocol negotiation.
Definition proto.hpp:4857
static void build_tls_crypt(const ProtoConfig &c, const bool server, const OpenVPNStaticKey &key, TLSCryptInstance::Ptr &send, TLSCryptInstance::Ptr &recv)
Definition proto.hpp:1933
bool renegotiate_request(Packet &pkt)
Definition proto.hpp:5283
static constexpr size_t MAX_CONTROL_WRAP_OVERHEAD
Definition proto.hpp:352
KeyContext::Ptr secondary
Definition proto.hpp:5587
unsigned int next_key_id()
Definition proto.hpp:5505
OvpnHMACInstance::Ptr ta_hmac_send
Definition proto.hpp:5552
const ProtoConfig & conf() const
Definition proto.hpp:5218
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 read(BufType &buf)
Definition psid.hpp:59
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 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 parse(const std::string &key_text)
void extract_key(OpenVPNStaticKey &tls_key) const
virtual void self_write(Buffer &buf)=0
virtual void peer_read(Buffer &buf)=0
virtual void self_randomize(StrongRandomAPI &rng)=0
virtual void erase()=0
virtual void generate_key_expansion(OpenVPNStaticKey &dest, const ProtoSessionID &psid_self, const ProtoSessionID &psid_peer) const =0
virtual bool peer_read_complete(BufferComplete &bc)=0
T raw() const
Definition time.hpp:404
static TimeType infinite()
Definition time.hpp:254
void min(const TimeType &t)
Definition time.hpp:337
base_type seconds_since_epoch() const
Definition time.hpp:289
bool defined() const
Definition time.hpp:280
#define OPENVPN_THROW_ARG1(exc, arg, stuff)
#define OPENVPN_THROW(exc, stuff)
#define likely(x)
Definition likely.hpp:21
#define unlikely(x)
Definition likely.hpp:22
#define OPENVPN_LOG(args)
#define OVPN_LOG_DEBUG(args)
Definition logger.hpp:226
#define OVPN_LOG_INFO(args)
Definition logger.hpp:224
#define OVPN_LOG_VERBOSE(args)
Definition logger.hpp:225
void work(openvpn_io::io_context &io_context, ThreadCommon &tc, MyRunContext &runctx, const unsigned int unit)
constexpr BufferFlags DESTRUCT_ZERO(1U<< 1)
if enabled, destructor will zero data before deletion
constexpr BufferFlags CONSTRUCT_ZERO(1U<< 0)
if enabled, constructors/init will zero allocated space
Mode mode(const Type type)
Type lookup(const std::string &name)
size_t key_length(const Type type)
const char * name(const KeyDerivation kd)
size_t size(const Type type)
std::size_t for_each(std::function< bool(Type, const Alg &)> fn)
@ KEV_NEGOTIATE_ERROR
Definition error.hpp:99
@ KEEPALIVE_TIMEOUT
Definition error.hpp:61
@ N_KEY_LIMIT_RENEG
Definition error.hpp:88
@ HANDSHAKE_TIMEOUT
Definition error.hpp:60
@ TLS_CRYPT_META_FAIL
Definition error.hpp:78
@ EARLY_NEG_INVALID
Definition error.hpp:92
bool is_safe_conversion(InT inVal)
Returns true if the given value can be contained by the out type.
OutT clamp_to_typerange(InT inVal)
Clamps the input value to the legal range for the output type.
std::uint32_t id_t
Definition relcommon.hpp:22
std::vector< T > split(const T &str, const typename T::value_type sep, const int maxsplit=-1)
Definition string.hpp:452
std::string trim_crlf_copy(std::string str)
Definition string.hpp:180
const Option * load_duration_parm(Time::Duration &dur, const std::string &name, const OptionList &opt, const unsigned int min_value, const bool x2, const bool allow_ms)
Definition durhelper.hpp:41
void set_duration_parm(Time::Duration &dur, const std::string &name, const std::string &valstr, const unsigned int min_value, const bool x2, const bool ms)
Definition durhelper.hpp:20
std::string read_text(const std::string &filename, const std::uint64_t max_size=0)
Definition file.hpp:127
std::string to_string(const T &t)
Convert a value to a string.
Definition to_string.hpp:45
const char * platform_name()
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
@ TUN_MTU_DEFAULT
Definition tunmtu.hpp:20
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:2150
What a WKc yields, owned by whoever asked for the unwrap.
Definition proto.hpp:2911
OpenVPNStaticKey client_key
Kc, the client key the WKc wrapped.
Definition proto.hpp:2913
The metadata record a WKc carried, for TLSCryptMetadata::verify()
Definition proto.hpp:2897
int type
-1 when the WKc carried no metadata at all
Definition proto.hpp:2899
A control-channel wrap mode paired with its hmac size.
Definition proto.hpp:1965
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