-
Notifications
You must be signed in to change notification settings - Fork 403
/
proto.hpp
4751 lines (4130 loc) · 166 KB
/
proto.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012- OpenVPN Inc.
//
// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
//
// ProtoContext, the fundamental OpenVPN protocol implementation.
// It can be used by OpenVPN clients, servers, or unit tests.
#ifndef OPENVPN_SSL_PROTO_H
#define OPENVPN_SSL_PROTO_H
#include <cstring>
#include <string>
#include <sstream>
#include <algorithm> // for std::min
#include <cstdint> // for std::uint32_t, etc.
#include <memory>
#include <optional>
#include <openvpn/common/clamp_typerange.hpp>
#include <openvpn/common/exception.hpp>
#include <openvpn/common/size.hpp>
#include <openvpn/common/version.hpp>
#include <openvpn/common/platform_name.hpp>
#include <openvpn/common/rc.hpp>
#include <openvpn/common/hexstr.hpp>
#include <openvpn/common/options.hpp>
#include <openvpn/common/mode.hpp>
#include <openvpn/common/socktypes.hpp>
#include <openvpn/common/number.hpp>
#include <openvpn/common/likely.hpp>
#include <openvpn/common/string.hpp>
#include <openvpn/common/to_string.hpp>
#include <openvpn/common/numeric_cast.hpp>
#include <openvpn/buffer/buffer.hpp>
#include <openvpn/buffer/safestr.hpp>
#include <openvpn/buffer/bufcomposed.hpp>
#include <openvpn/ip/ip4.hpp>
#include <openvpn/ip/ip6.hpp>
#include <openvpn/ip/udp.hpp>
#include <openvpn/ip/tcp.hpp>
#include <openvpn/time/time.hpp>
#include <openvpn/time/durhelper.hpp>
#include <openvpn/frame/frame.hpp>
#include <openvpn/random/randapi.hpp>
#include <openvpn/crypto/cryptoalgs.hpp>
#include <openvpn/crypto/cryptodc.hpp>
#include <openvpn/crypto/cipher.hpp>
#include <openvpn/crypto/ovpnhmac.hpp>
#include <openvpn/crypto/tls_crypt.hpp>
#include <openvpn/crypto/tls_crypt_v2.hpp>
#include <openvpn/crypto/packet_id_control.hpp>
#include <openvpn/crypto/static_key.hpp>
#include <openvpn/crypto/bs64_data_limit.hpp>
#include <openvpn/log/sessionstats.hpp>
#include <openvpn/ssl/protostack.hpp>
#include <openvpn/ssl/psid.hpp>
#include <openvpn/ssl/tlsprf.hpp>
#include <openvpn/ssl/datalimit.hpp>
#include <openvpn/ssl/mssparms.hpp>
#include <openvpn/transport/mssfix.hpp>
#include <openvpn/transport/protocol.hpp>
#include <openvpn/transport/client/transbase.hpp>
#include <openvpn/tun/layer.hpp>
#include <openvpn/tun/tunmtu.hpp>
#include <openvpn/compress/compress.hpp>
#include <openvpn/ssl/proto_context_options.hpp>
#include <openvpn/ssl/peerinfo.hpp>
#include <openvpn/crypto/crypto_aead.hpp>
#include <openvpn/ssl/customcontrolchannel.hpp>
#include <openvpn/netconf/hwaddr.hpp>
#ifndef OPENVPN_DEBUG_PROTO
#define OPENVPN_DEBUG_PROTO 1
#endif
/*
ProtoContext -- OpenVPN protocol implementation
Protocol negotiation states:
Client:
1. send client reset to server
2. wait for server reset from server AND ack from 1 (C_WAIT_RESET, C_WAIT_RESET_ACK)
3. start SSL handshake
4. send auth message to server
5. wait for server auth message AND ack from 4 (C_WAIT_AUTH, C_WAIT_AUTH_ACK)
6. go active (ACTIVE)
Server:
1. wait for client reset (S_WAIT_RESET)
2. send server reset to client
3. wait for ACK from 2 (S_WAIT_RESET_ACK)
4. start SSL handshake
5. wait for auth message from client (S_WAIT_AUTH)
6. send auth message to client
7. wait for ACK from 6 (S_WAIT_AUTH_ACK)
8. go active (ACTIVE)
*/
namespace openvpn {
// utility namespace for ProtoContext
namespace proto_context_private {
namespace {
// clang-format off
const unsigned char auth_prefix[] = { 0, 0, 0, 0, 2 }; // CONST GLOBAL
const unsigned char keepalive_message[] = { // CONST GLOBAL
0x2a, 0x18, 0x7b, 0xf3, 0x64, 0x1e, 0xb4, 0xcb,
0x07, 0xed, 0x2d, 0x0a, 0x98, 0x1f, 0xc7, 0x48
};
enum
{
KEEPALIVE_FIRST_BYTE = 0x2a // first byte of keepalive message
};
inline bool is_keepalive(const Buffer &buf)
{
return buf.size() >= sizeof(keepalive_message)
&& buf[0] == KEEPALIVE_FIRST_BYTE
&& !std::memcmp(keepalive_message, buf.c_data(), sizeof(keepalive_message));
}
const unsigned char explicit_exit_notify_message[] = { // CONST GLOBAL
0x28, 0x7f, 0x34, 0x6b, 0xd4, 0xef, 0x7a, 0x81,
0x2d, 0x56, 0xb8, 0xd3, 0xaf, 0xc5, 0x45, 0x9c,
6 // OCC_EXIT
};
// clang-format on
enum
{
EXPLICIT_EXIT_NOTIFY_FIRST_BYTE = 0x28 // first byte of exit message
};
} // namespace
} // namespace proto_context_private
class ProtoContextCallbackInterface
{
public:
virtual ~ProtoContextCallbackInterface() = default;
/**
* Sends out bytes to the network.
*/
virtual void control_net_send(const Buffer &net_buf) = 0;
/*
* Receive as packet from the network
* \note app may take ownership of app_bp via std::move
*/
virtual void control_recv(BufferPtr &&app_bp) = 0;
/** Called on client to request username/password credentials.
* Should be overridden by derived class if credentials are required.
* username and password should be written into buf with write_auth_string().
*/
virtual void client_auth(Buffer &buf)
{
write_empty_string(buf); // username
write_empty_string(buf); // password
}
/** Called on server with credentials and peer info provided by client.
*Should be overriden by derived class if credentials are required. */
virtual void server_auth(const std::string &username,
const SafeString &password,
const std::string &peer_info,
const AuthCert::Ptr &auth_cert)
{
}
/**
* Writes an empty user or password string for the key-method 2 packet in the OpenVPN protocol
* @param buf buffer to write to
*/
static void write_empty_string(Buffer &buf)
{
uint8_t empty[]{0x00, 0x00}; // empty length field without content
buf.write(&empty, 2);
}
/** the protocol context needs to know if the parent and its tun/transport layer are able to
* support 64bit and AEAD tag at the end in order to properly handshake this protocol feature
*/
virtual bool supports_proto_v3() = 0;
//! Called when KeyContext transitions to ACTIVE state
virtual void active(bool primary) = 0;
};
class ProtoContext : public logging::LoggingMixin<OPENVPN_DEBUG_PROTO,
logging::LOG_LEVEL_VERB,
ProtoContext>
{
#ifdef UNIT_TEST
public:
#else
protected:
#endif
static constexpr size_t APP_MSG_MAX = 65536;
enum
{
// packet opcode (high 5 bits) and key-id (low 3 bits) are combined in one byte
KEY_ID_MASK = 0x07,
OPCODE_SHIFT = 3,
// packet opcodes -- the V1 is intended to allow protocol changes in the future
// CONTROL_HARD_RESET_CLIENT_V1 = 1, // (obsolete) initial key from client, forget previous state
// CONTROL_HARD_RESET_SERVER_V1 = 2, // (obsolete) initial key from server, forget previous state
CONTROL_SOFT_RESET_V1 = 3, // new key, graceful transition from old to new key
CONTROL_V1 = 4, // control channel packet (usually TLS ciphertext)
CONTROL_WKC_V1 = 11, // control channel packet with wrapped client key appended
ACK_V1 = 5, // acknowledgement for packets received
DATA_V1 = 6, // data channel packet with 1-byte header
DATA_V2 = 9, // data channel packet with 4-byte header
// indicates key_method >= 2
CONTROL_HARD_RESET_CLIENT_V2 = 7, // initial key from client, forget previous state
CONTROL_HARD_RESET_CLIENT_V3 = 10, // initial key from client, forget previous state
CONTROL_HARD_RESET_SERVER_V2 = 8, // initial key from server, forget previous state
INVALID_OPCODE = 0,
// DATA_V2 constants
OP_SIZE_V2 = 4, // size of initial packet opcode
OP_PEER_ID_UNDEF = 0x00FFFFFF, // indicates that Peer ID is undefined
// states
// C_x : client states
// S_x : server states
// ACK states -- must be first before other states
STATE_UNDEF = -1,
C_WAIT_RESET_ACK = 0,
C_WAIT_AUTH_ACK = 1,
S_WAIT_RESET_ACK = 2,
S_WAIT_AUTH_ACK = 3,
LAST_ACK_STATE = 3, // all ACK states must be <= this value
// key negotiation states (client)
C_INITIAL = 4,
C_WAIT_RESET = 5, // must be C_INITIAL+1
C_WAIT_AUTH = 6,
// key negotiation states (server)
S_INITIAL = 7,
S_WAIT_RESET = 8, // must be S_INITIAL+1
S_WAIT_AUTH = 9,
// key negotiation states (client and server)
ACTIVE = 10,
};
enum iv_proto_flag : unsigned int
{
// See ssl.h in openvpn2 for detailed documentation of IV_PROTO
//
// NOTE: Bit field (1 << 0) is reserved for historic reasons
// and not expected to be set. Do not use this field.
//
IV_PROTO_DATA_V2 = (1 << 1),
IV_PROTO_REQUEST_PUSH = (1 << 2),
IV_PROTO_TLS_KEY_EXPORT = (1 << 3),
IV_PROTO_AUTH_PENDING_KW = (1 << 4),
IV_PROTO_NCP_P2P = (1 << 5), // not implemented
IV_PROTO_DNS_OPTION = (1 << 6), // outdated, don't send
IV_PROTO_CC_EXIT_NOTIFY = (1 << 7),
IV_PROTO_AUTH_FAIL_TEMP = (1 << 8),
IV_PROTO_DYN_TLS_CRYPT = (1 << 9),
IV_PROTO_DATA_V3 = (1 << 10),
IV_PROTO_DNS_OPTION_V2 = (1 << 11),
IV_PROTO_PUSH_UPDATE = (1 << 12)
};
enum tlv_types : uint16_t
{
EARLY_NEG_FLAGS = 0x0001
};
enum early_neg_flags : uint16_t
{
EARLY_NEG_FLAG_RESEND_WKC = 0x0001
};
static unsigned int opcode_extract(const unsigned int op)
{
return op >> OPCODE_SHIFT;
}
static unsigned int key_id_extract(const unsigned int op)
{
return op & KEY_ID_MASK;
}
static size_t op_head_size(const unsigned int op)
{
return opcode_extract(op) == DATA_V2 ? OP_SIZE_V2 : 1;
}
static unsigned char op_compose(const unsigned int opcode, const unsigned int key_id)
{
// As long as 'opcode' stays within the range specified by the enum the cast should be safe.
// TODO: Use a more constrained type for opcode to ensure range violations can't happen.
return static_cast<unsigned char>((opcode << OPCODE_SHIFT) | key_id);
}
static unsigned int op32_compose(const unsigned int opcode,
const unsigned int key_id,
const int op_peer_id)
{
return (op_compose(opcode, key_id) << 24) | (op_peer_id & 0x00FFFFFF);
}
public:
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_error);
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, process_server_push_error);
OPENVPN_UNTAGGED_EXCEPTION_INHERIT(option_error, proto_option_error);
// configuration data passed to ProtoContext constructor
class ProtoConfig : public RCCopyable<thread_unsafe_refcount>
{
public:
typedef RCPtr<ProtoConfig> Ptr;
// master SSL context factory
SSLFactoryAPI::Ptr ssl_factory;
// data channel
CryptoDCSettings dc;
// TLSPRF factory
TLSPRFFactory::Ptr tlsprf_factory;
// master Frame object
Frame::Ptr frame;
// (non-smart) pointer to current time
TimePtr now;
// Random number generator.
// Use-cases demand highest cryptographic strength
// such as key generation.
StrongRandomAPI::Ptr rng;
// Pseudo-random number generator.
// Use-cases demand cryptographic strength
// combined with high performance. Used for
// IV and ProtoSessionID generation.
RandomAPI::Ptr prng;
// If relay mode is enabled, connect to a special OpenVPN
// server that acts as a relay/proxy to a second server.
bool relay_mode = false;
// defer data channel initialization until after client options pull
bool dc_deferred = false;
// transmit username/password creds to server (client-only)
bool xmit_creds = true;
// send client exit notifications via control channel
bool cc_exit_notify = false;
// Transport protocol, i.e. UDPv4, etc.
Protocol protocol; // set with set_protocol()
// OSI layer
Layer layer;
// compressor
CompressContext comp_ctx;
// tls_auth/crypt parms
enum TLSCrypt
{
None = 0,
V1 = (1 << 0),
V2 = (1 << 1),
Dynamic = (1 << 2)
};
OpenVPNStaticKey tls_key; // leave this undefined to disable tls_auth/crypt
unsigned tls_crypt_ = TLSCrypt::None; // needed to distinguish between tls-crypt and tls-crypt-v2 server mode
BufferAllocated wkc; // leave this undefined to disable tls-crypt-v2 on client
OvpnHMACFactory::Ptr tls_auth_factory;
OvpnHMACContext::Ptr tls_auth_context;
int key_direction = -1; // 0, 1, or -1 for bidirectional
TLSCryptFactory::Ptr tls_crypt_factory;
TLSCryptContext::Ptr tls_crypt_context;
TLSCryptMetadataFactory::Ptr tls_crypt_metadata_factory;
// timeout parameters, relative to construction of KeyContext object
Time::Duration handshake_window; // SSL/TLS negotiation must complete by this time
Time::Duration become_primary; // KeyContext (that is ACTIVE) becomes primary at this time
Time::Duration renegotiate; // start SSL/TLS renegotiation at this time
Time::Duration expire; // KeyContext expires at this time
Time::Duration tls_timeout; // Packet retransmit timeout on TLS control channel
// keepalive parameters
Time::Duration keepalive_ping; // ping xmit period
Time::Duration keepalive_timeout; // timeout period after primary KeyContext reaches ACTIVE state
Time::Duration keepalive_timeout_early; // timeout period before primary KeyContext reaches ACTIVE state
//! extra peer info key/value pairs generated by client app
PeerInfo::Set::Ptr extra_peer_info;
// App control config
AppControlMessageConfig app_control_config;
AppControlMessageReceiver app_control_recv;
/** extra peer information that depends on the state of the underlying transport and needs to be initialised
* after the transport is initialised but before the IV variables are sent */
PeerInfo::Set::Ptr extra_peer_info_transport;
/** When the extra_peer_info_transport is being built, we need to remember if it should include the more
* sensitive information that push-peer-info includes */
bool extra_peer_info_push_peerinfo = false;
// op header
bool enable_op32 = false;
int remote_peer_id = -1; // -1 to disable
int local_peer_id = -1; // -1 to disable
// MTU
unsigned int tun_mtu = TUN_MTU_DEFAULT;
unsigned int tun_mtu_max = TUN_MTU_DEFAULT + 100;
MSSParms mss_parms;
unsigned int mss_fix = 0;
// For compatibility with openvpn2 we send initial options on rekeying,
// instead of possible modifications caused by NCP
std::string initial_options;
bool auth_nocache = false;
void load(const OptionList &opt,
const ProtoContextCompressionOptions &pco,
const int default_key_direction,
const bool server)
{
// first set defaults
handshake_window = Time::Duration::seconds(60);
renegotiate = Time::Duration::seconds(3600);
tls_timeout = Time::Duration::seconds(1);
keepalive_ping = Time::Duration::seconds(8);
keepalive_timeout = Time::Duration::seconds(40);
keepalive_timeout_early = keepalive_timeout;
comp_ctx = CompressContext(CompressContext::NONE, false);
protocol = Protocol();
key_direction = default_key_direction;
// layer
{
const Option *dev = opt.get_ptr("dev-type");
if (!dev)
dev = opt.get_ptr("dev");
if (!dev)
throw proto_option_error(ERR_INVALID_CONFIG, "missing dev-type or dev option");
const std::string &dev_type = dev->get(1, 64);
if (string::starts_with(dev_type, "tun"))
layer = Layer(Layer::OSI_LAYER_3);
else if (string::starts_with(dev_type, "tap"))
throw proto_option_error(ERR_INVALID_CONFIG, "TAP mode is not supported");
else
throw proto_option_error(ERR_INVALID_OPTION_VAL, "bad dev-type");
}
// cipher/digest/tls-auth/tls-crypt
{
CryptoAlgs::Type cipher = CryptoAlgs::NONE;
CryptoAlgs::Type digest = CryptoAlgs::NONE;
// data channel cipher
{
const Option *o = opt.get_ptr("cipher");
if (o)
{
const std::string &cipher_name = o->get(1, 128);
if (cipher_name != "none")
cipher = CryptoAlgs::lookup(cipher_name);
}
else
cipher = CryptoAlgs::lookup("BF-CBC");
}
// data channel HMAC
{
const Option *o = opt.get_ptr("auth");
if (o)
{
const std::string &auth_name = o->get(1, 128);
if (auth_name != "none")
digest = CryptoAlgs::lookup(auth_name);
}
else
digest = CryptoAlgs::lookup("SHA1");
}
dc.set_cipher(cipher);
dc.set_digest(digest);
// tls-auth
{
const Option *o = opt.get_ptr(relay_prefix("tls-auth"));
if (o)
{
if (tls_crypt_context)
throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-auth and tls-crypt are mutually exclusive");
tls_key.parse(o->get(1, 0));
const Option *tad = opt.get_ptr(relay_prefix("tls-auth-digest"));
if (tad)
digest = CryptoAlgs::lookup(tad->get(1, 128));
if (digest != CryptoAlgs::NONE)
set_tls_auth_digest(digest);
}
}
// tls-crypt
{
const Option *o = opt.get_ptr(relay_prefix("tls-crypt"));
if (o)
{
if (tls_auth_context)
throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-auth and tls-crypt are mutually exclusive");
if (tls_crypt_context)
throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-crypt and tls-crypt-v2 are mutually exclusive");
tls_crypt_ = TLSCrypt::V1;
tls_key.parse(o->get(1, 0));
set_tls_crypt_algs();
}
}
// tls-crypt-v2
{
const Option *o = opt.get_ptr(relay_prefix("tls-crypt-v2"));
if (o)
{
if (tls_auth_context)
throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-auth and tls-crypt-v2 are mutually exclusive");
if (tls_crypt_context)
throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "tls-crypt and tls-crypt-v2 are mutually exclusive");
// initialize tls_crypt_context
set_tls_crypt_algs();
std::string keyfile = o->get(1, 0);
if (opt.exists("client"))
{
// in client mode expect the key to be a PEM encoded tls-crypt-v2 client key (key + WKc)
TLSCryptV2ClientKey tls_crypt_v2_key(tls_crypt_context);
tls_crypt_v2_key.parse(keyfile);
tls_crypt_v2_key.extract_key(tls_key);
tls_crypt_v2_key.extract_wkc(wkc);
}
else
{
// in server mode this is a PEM encoded tls-crypt-v2 server key
TLSCryptV2ServerKey tls_crypt_v2_key;
tls_crypt_v2_key.parse(keyfile);
tls_crypt_v2_key.extract_key(tls_key);
}
tls_crypt_ = TLSCrypt::V2;
}
}
}
// key-direction
{
if (key_direction >= -1 && key_direction <= 1)
{
const Option *o = opt.get_ptr(relay_prefix("key-direction"));
if (o)
{
const std::string &dir = o->get(1, 16);
if (dir == "0")
key_direction = 0;
else if (dir == "1")
key_direction = 1;
else if (dir == "bidirectional" || dir == "bi")
key_direction = -1;
else
throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "bad key-direction parameter");
}
}
else
throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "bad key-direction default");
}
// compression
{
const Option *o = opt.get_ptr("compress");
if (o)
{
if (o->size() >= 2)
{
const std::string meth_name = o->get(1, 128);
CompressContext::Type meth = CompressContext::parse_method(meth_name);
if (meth == CompressContext::NONE)
OPENVPN_THROW_ARG1(proto_option_error, ERR_INVALID_OPTION_VAL, "Unknown compressor: '" << meth_name << '\'');
comp_ctx = CompressContext(pco.is_comp() ? meth : CompressContext::stub(meth), pco.is_comp_asym());
}
else
comp_ctx = CompressContext(pco.is_comp() ? CompressContext::ANY : CompressContext::COMP_STUB, pco.is_comp_asym());
}
else
{
o = opt.get_ptr("comp-lzo");
if (o)
{
if (o->size() == 2 && o->ref(1) == "no")
{
// On the client, by using ANY instead of ANY_LZO, we are telling the server
// that it's okay to use any of our supported compression methods.
comp_ctx = CompressContext(pco.is_comp() ? CompressContext::ANY : CompressContext::LZO_STUB, pco.is_comp_asym());
}
else
{
comp_ctx = CompressContext(pco.is_comp() ? CompressContext::LZO : CompressContext::LZO_STUB, pco.is_comp_asym());
}
}
}
}
// tun-mtu
tun_mtu = parse_tun_mtu(opt, tun_mtu);
tun_mtu_max = parse_tun_mtu_max(opt, tun_mtu_max);
// mssfix
mss_parms.parse(opt, true);
if (mss_parms.mssfix_default)
{
if (tun_mtu == TUN_MTU_DEFAULT)
{
mss_parms.mssfix = MSSParms::MSSFIX_DEFAULT;
mss_parms.mtu = true;
}
else
{
mss_parms.mssfix = tun_mtu;
mss_parms.fixed = true;
}
}
// load parameters that can be present in both config file or pushed options
load_common(opt, pco, server ? LOAD_COMMON_SERVER : LOAD_COMMON_CLIENT);
}
/**
* Fire up the infrastructure needed in order to be able to process dynamic
* TLS-crypt renegotiation.
*/
void enable_dynamic_tls_crypt()
{
set_tls_crypt_algs();
tls_crypt_ |= TLSCrypt::Dynamic;
}
// load options string pushed by server
void process_push(const OptionList &opt, const ProtoContextCompressionOptions &pco)
{
// data channel
parse_pushed_data_channel_options(opt);
// protocol-flags
parse_pushed_protocol_flags(opt);
// compression
parse_pushed_compression(opt, pco);
// peer ID
parse_pushed_peer_id(opt);
// custom app control channel options
parse_custom_app_control(opt);
try
{
// load parameters that can be present in both config file or pushed options
load_common(opt, pco, LOAD_COMMON_CLIENT_PUSHED);
}
catch (const std::exception &e)
{
OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed parameter: " << e.what());
}
// show negotiated options
OVPN_LOG_INFO(show_options());
}
void parse_custom_app_control(const OptionList &opt)
{
try
{
const Option *o = opt.get_ptr("custom-control");
if (o)
{
app_control_config.max_msg_size = o->get_num(1, 1, std::numeric_limits<int>::max());
const auto &flags = o->get(2, 1024);
const auto &protocols = o->get(3, 1024);
app_control_config.parse_flags(flags);
app_control_config.supported_protocols = string::split(protocols, ':');
/* This implementation always wants to have at least both base64 and text encoding */
if (!app_control_config.encoding_text)
{
OPENVPN_LOG("Warning: custom app control requires base64 encoding to properly work");
}
}
}
catch (const std::exception &e)
{
OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed parameter: " << e.what());
app_control_config = {};
}
}
void parse_pushed_data_channel_options(const OptionList &opt)
{
// cipher
std::string new_cipher;
try
{
const Option *o = opt.get_ptr("cipher");
if (o)
{
new_cipher = o->get(1, 128);
if (new_cipher != "none")
dc.set_cipher(CryptoAlgs::lookup(new_cipher));
}
}
catch (const std::exception &e)
{
OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed cipher '" << new_cipher << "': " << e.what());
}
// digest
std::string new_digest;
try
{
const Option *o = opt.get_ptr("auth");
if (o)
{
new_digest = o->get(1, 128);
if (new_digest != "none")
dc.set_digest(CryptoAlgs::lookup(new_digest));
}
}
catch (const std::exception &e)
{
OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed digest '" << new_digest << "': " << e.what());
}
}
void parse_pushed_peer_id(const OptionList &opt)
{
try
{
const Option *o = opt.get_ptr("peer-id");
if (o)
{
bool status = parse_number_validate<int>(o->get(1, 16),
16,
-1,
0xFFFFFE,
&remote_peer_id);
if (!status)
throw Exception("parse/range issue");
enable_op32 = true;
}
}
catch (const std::exception &e)
{
OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed peer-id: " << e.what());
}
}
void parse_pushed_protocol_flags(const OptionList &opt)
{
// tls key-derivation method with old key-derivation option
std::string key_method;
try
{
const Option *o = opt.get_ptr("key-derivation");
if (o)
{
key_method = o->get(1, 128);
if (key_method == "tls-ekm")
dc.set_key_derivation(CryptoAlgs::KeyDerivation::TLS_EKM);
else
OPENVPN_THROW(process_server_push_error, "Problem accepting key-derivation method '" << key_method << "'");
}
else
dc.set_key_derivation(CryptoAlgs::KeyDerivation::OPENVPN_PRF);
}
catch (const std::exception &e)
{
OPENVPN_THROW(process_server_push_error, "Problem accepting key-derivation method '" << key_method << "': " << e.what());
}
try
{
const Option *o = opt.get_ptr("protocol-flags");
if (o)
{
o->min_args(2);
for (std::size_t i = 1; i < o->size(); i++)
{
std::string flag = o->get(i, 128);
if (flag == "cc-exit")
{
cc_exit_notify = true;
}
else if (flag == "dyn-tls-crypt")
{
enable_dynamic_tls_crypt();
}
else if (flag == "tls-ekm")
{
// Overrides "key-derivation" method set above
dc.set_key_derivation(CryptoAlgs::KeyDerivation::TLS_EKM);
}
else if (flag == "aead-tag-end")
{
dc.set_aead_tag_end(true);
}
else if (flag == "pkt-id-64-bit")
{
dc.set_64_bit_packet_id(true);
}
else
{
OPENVPN_THROW(process_server_push_error, "unknown flag '" << flag << "'");
}
}
}
}
catch (const std::exception &e)
{
OPENVPN_THROW(process_server_push_error, "Problem accepting protocol-flags: " << e.what());
}
}
void parse_pushed_compression(const OptionList &opt, const ProtoContextCompressionOptions &pco)
{
std::string new_comp;
try
{
const Option *o;
o = opt.get_ptr("compress");
if (o)
{
new_comp = o->get(1, 128);
CompressContext::Type meth = CompressContext::parse_method(new_comp);
if (meth != CompressContext::NONE)
{
// if compression is not availabe, CompressContext ctor throws an exception
if (pco.is_comp())
comp_ctx = CompressContext(meth, pco.is_comp_asym());
else
{
// server pushes compression but client has compression disabled
// degrade to asymmetric compression (downlink only)
comp_ctx = CompressContext(meth, true);
if (!comp_ctx.is_any_stub(meth))
{
OPENVPN_LOG("Server has pushed compressor "
<< comp_ctx.str()
<< ", but client has disabled compression, switching to asymmetric");
}
}
}
}
else
{
o = opt.get_ptr("comp-lzo");
if (o)
{
if (o->size() == 2 && o->ref(1) == "no")
{
comp_ctx = CompressContext(CompressContext::LZO_STUB, false);
}
else
{
comp_ctx = CompressContext(pco.is_comp() ? CompressContext::LZO : CompressContext::LZO_STUB, pco.is_comp_asym());
}
}
}
}
catch (const std::exception &e)
{
OPENVPN_THROW(process_server_push_error, "Problem accepting server-pushed compressor '" << new_comp << "': " << e.what());
}
}
void get_data_channel_options(std::ostringstream &os) const
{
os << " data channel:";
os << " cipher " << CryptoAlgs::name(dc.cipher());
if (CryptoAlgs::mode(dc.cipher()) != CryptoAlgs::Mode::AEAD)
os << ", digest " << CryptoAlgs::name(dc.digest());
os << ", peer-id " << remote_peer_id;
if (dc.aeadTagAtTheEnd())
os << ", aead-tag-end";
if (dc.use64bitPktCounter())
os << ", pkt-id-64-bit";
os << std::endl;
}
void show_cc_enc_option(std::ostringstream &os) const
{
if (tls_auth_enabled())
{
os << " control channel: tls-auth enabled" << std::endl;
}
if (tls_crypt_v2_enabled())
{
os << " control channel: tls-crypt v2 enabled" << std::endl;
}
else if (tls_crypt_enabled())
{
os << " control channel: tls-crypt enabled" << std::endl;
}
else if (dynamic_tls_crypt_enabled())
{
os << " control channel: dynamic tls-crypt enabled" << std::endl;
}
}
std::string show_options() const
{
std::ostringstream os;
os << "PROTOCOL OPTIONS:" << std::endl;
os << " key-derivation: " << CryptoAlgs::name(dc.key_derivation()) << std::endl;
if (comp_ctx.type() != CompressContext::NONE)
os << " compress: " << comp_ctx.str() << std::endl;
show_cc_enc_option(os);
get_data_channel_options(os);
if (!app_control_config.supported_protocols.empty())
{
os << " app custom control channel: " << app_control_config.str() << std::endl;
}
return os.str();
}
void set_protocol(const Protocol &p)
{
// adjust options for new transport protocol
protocol = p;
}
void set_tls_auth_digest(const CryptoAlgs::Type digest)
{
tls_auth_context = tls_auth_factory->new_obj(digest);
}
void set_tls_crypt_algs()
{
if (tls_crypt_context)
return;
auto digest = CryptoAlgs::lookup("SHA256");
auto cipher = CryptoAlgs::lookup("AES-256-CTR");
if ((digest == CryptoAlgs::NONE) || (cipher == CryptoAlgs::NONE))
throw proto_option_error(ERR_INVALID_OPTION_CRYPTO, "missing support for tls-crypt algorithms");
/* TODO: we currently use the default SSL library context here as the
* library context is not available this early. This should not matter
* for the algorithms used by tls_crypt */
tls_crypt_context = tls_crypt_factory->new_obj(nullptr, digest, cipher);
}