This repository has been archived by the owner on Nov 4, 2024. It is now read-only.
forked from OpenVPN/openvpn3
-
Notifications
You must be signed in to change notification settings - Fork 3
/
proto.hpp
3947 lines (3400 loc) · 112 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-2020 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
// 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 <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/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.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/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/ssl/ssllog.hpp>
#include <openvpn/crypto/crypto_aead.hpp>
#if OPENVPN_DEBUG_PROTO >= 1
#define OPENVPN_LOG_PROTO(x) OPENVPN_LOG(x)
#define OPENVPN_LOG_STRING_PROTO(x) OPENVPN_LOG_STRING(x)
#else
#define OPENVPN_LOG_PROTO(x)
#define OPENVPN_LOG_STRING_PROTO(x)
#endif
#if OPENVPN_DEBUG_PROTO >= 2
#define OPENVPN_LOG_PROTO_VERBOSE(x) OPENVPN_LOG(x)
#else
#define OPENVPN_LOG_PROTO_VERBOSE(x)
#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 {
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
};
enum {
EXPLICIT_EXIT_NOTIFY_FIRST_BYTE = 0x28 // first byte of exit message
};
}
}
class ProtoContext
{
protected:
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)
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
// define the range of legal opcodes
FIRST_OPCODE = 3,
LAST_OPCODE = 9,
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
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)
};
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 int op_compose(const unsigned int opcode, const unsigned int key_id)
{
return (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_EXCEPTION(proto_error);
OPENVPN_EXCEPTION(process_server_push_error);
OPENVPN_EXCEPTION_INHERIT(option_error, proto_option_error);
// configuration data passed to ProtoContext constructor
class Config : public RCCopyable<thread_unsafe_refcount>
{
public:
typedef RCPtr<Config> 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.
RandomAPI::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;
// Transport protocol, i.e. UDPv4, etc.
Protocol protocol; // set with set_protocol()
// OSI layer
Layer layer;
// compressor
CompressContext comp_ctx;
// tls_auth/crypt parms
OpenVPNStaticKey tls_key; // leave this undefined to disable tls_auth/crypt
bool tls_crypt_v2 = false; // 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;
// reliability layer parms
reliable::id_t reliable_window = 0;
size_t max_ack_list = 0;
// packet_id parms for both data and control channels
int pid_mode = 0; // PacketIDReceive::UDP_MODE or PacketIDReceive::TCP_MODE
// 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;
Time::Duration keepalive_timeout;
// extra peer info key/value pairs generated by client app
PeerInfo::Set::Ptr extra_peer_info;
// 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 = 1500;
MSSParms mss_parms;
unsigned int mss_inter = 0;
// Debugging
int debug_level = 1;
// For compatibility with openvpn2 we send initial options on rekeying,
// instead of possible modifications caused by NCP
std::string initial_options;
void load(const OptionList& opt, const ProtoContextOptions& pco,
const int default_key_direction, const bool server)
{
// first set defaults
reliable_window = 4;
max_ack_list = 4;
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);
comp_ctx = CompressContext(CompressContext::NONE, false);
protocol = Protocol();
pid_mode = PacketIDReceive::UDP_MODE;
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("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("TAP mode is not supported");
else
throw proto_option_error("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("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("tls-auth and tls-crypt are mutually exclusive");
if (tls_crypt_context)
throw proto_option_error("tls-crypt and tls-crypt-v2 are mutually exclusive");
tls_key.parse(o->get(1, 0));
digest = CryptoAlgs::lookup("SHA256");
cipher = CryptoAlgs::lookup("AES-256-CTR");
if ((digest == CryptoAlgs::NONE) || (cipher == CryptoAlgs::NONE))
throw proto_option_error("missing support for tls-crypt algorithms");
set_tls_crypt_algs(digest, cipher);
}
}
// tls-crypt-v2
{
const Option *o = opt.get_ptr(relay_prefix("tls-crypt-v2"));
if (o)
{
if (tls_auth_context)
throw proto_option_error("tls-auth and tls-crypt-v2 are mutually exclusive");
if (tls_crypt_context)
throw proto_option_error("tls-crypt and tls-crypt-v2 are mutually exclusive");
digest = CryptoAlgs::lookup("SHA256");
cipher = CryptoAlgs::lookup("AES-256-CTR");
if ((digest == CryptoAlgs::NONE) || (cipher == CryptoAlgs::NONE))
throw proto_option_error("missing support for tls-crypt-v2 algorithms");
// initialize tls_crypt_context
set_tls_crypt_algs(digest, cipher);
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_v2 = true;
}
}
}
// 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("bad key-direction parameter");
}
}
else
throw proto_option_error("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(proto_option_error, "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);
// mssfix
mss_parms.parse(opt, 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);
}
// load options string pushed by server
void process_push(const OptionList& opt, const ProtoContextOptions& pco)
{
// data channel
{
// 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());
}
// tls key-derivation method
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());
}
}
// compression
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());
}
// peer ID
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());
}
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
OPENVPN_LOG_STRING_PROTO(show_options());
}
std::string show_options() const
{
std::ostringstream os;
os << "PROTOCOL OPTIONS:" << std::endl;
os << " cipher: " << CryptoAlgs::name(dc.cipher()) << std::endl;
os << " digest: " << CryptoAlgs::name(dc.digest()) << std::endl;
os << " key-derivation: " << CryptoAlgs::name(dc.key_derivation()) << std::endl;
os << " compress: " << comp_ctx.str() << std::endl;
os << " peer ID: " << remote_peer_id << std::endl;
if (tls_auth_enabled())
{
os << " control channel: tls-auth enabled" << std::endl;
}
else 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;
}
return os.str();
}
void set_pid_mode(const bool tcp_linear)
{
if (protocol.is_udp() || !tcp_linear)
pid_mode = PacketIDReceive::UDP_MODE;
else if (protocol.is_tcp())
pid_mode = PacketIDReceive::TCP_MODE;
else
throw proto_option_error("transport protocol undefined");
}
void set_protocol(const Protocol& p)
{
// adjust options for new transport protocol
protocol = p;
set_pid_mode(false);
}
void set_tls_auth_digest(const CryptoAlgs::Type digest)
{
tls_auth_context = tls_auth_factory->new_obj(digest);
}
void set_tls_crypt_algs(const CryptoAlgs::Type digest,
const CryptoAlgs::Type cipher)
{
tls_crypt_context = tls_crypt_factory->new_obj(digest, cipher);
}
void set_xmit_creds(const bool xmit_creds_arg)
{
xmit_creds = xmit_creds_arg;
}
bool tls_auth_enabled() const
{
return tls_key.defined() && tls_auth_context;
}
bool tls_crypt_enabled() const
{
return tls_key.defined() && tls_crypt_context;
}
bool tls_crypt_v2_enabled() const
{
return tls_crypt_enabled() && tls_crypt_v2;
}
// generate a string summarizing options that will be
// transmitted to peer for options consistency check
std::string options_string()
{
if (!initial_options.empty())
return initial_options;
std::ostringstream out;
const bool server = ssl_factory->mode().is_server();
const unsigned int l2extra = (layer() == Layer::OSI_LAYER_2 ? 32 : 0);
out << "V4";
out << ",dev-type " << layer.dev_type();
out << ",link-mtu " << tun_mtu + link_mtu_adjust() + l2extra;
out << ",tun-mtu " << tun_mtu + l2extra;
out << ",proto " << protocol.str_client(true);
{
const char *compstr = comp_ctx.options_string();
if (compstr)
out << ',' << compstr;
}
if (tls_auth_context && (key_direction >= 0))
out << ",keydir " << key_direction;
out << ",cipher " << CryptoAlgs::name(dc.cipher(), "[null-cipher]");
out << ",auth " << CryptoAlgs::name(dc.digest(), "[null-digest]");
out << ",keysize " << (CryptoAlgs::key_length(dc.cipher()) * 8);
if (tls_auth_context)
out << ",tls-auth";
// sending tls-crypt does not make sense. If we got to this point it
// means that tls-crypt was already there and it worked fine.
// tls-auth has to be kept for backward compatibility as it is there
// since a bit.
out << ",key-method 2";
if (server)
out << ",tls-server";
else
out << ",tls-client";
initial_options = out.str();
return initial_options;
}
// generate a string summarizing information about the client
// including capabilities
std::string peer_info_string() const
{
std::ostringstream out;
const char *compstr = nullptr;
// supports op32 and P_DATA_V2 and expects a push reply
unsigned int iv_proto = IV_PROTO_DATA_V2
| IV_PROTO_REQUEST_PUSH
| IV_PROTO_AUTH_PENDING_KW;
if (SSLLib::SSLAPI::support_key_material_export())
{
iv_proto |= IV_PROTO_TLS_KEY_EXPORT;
}
out << "IV_VER=" << OPENVPN_VERSION << '\n';
out << "IV_PLAT=" << platform_name() << '\n';
out << "IV_NCP=2\n"; // negotiable crypto parameters V2
out << "IV_TCPNL=1\n"; // supports TCP non-linear packet ID
out << "IV_PROTO=" << std::to_string(iv_proto) << '\n';
/*
* OpenVPN3 allows to be pushed any cipher that it supports as it
* only implements secure ones and BF-CBC for backwards
* compatibility and generally adopts the concept of the server being
* responsible for sensible choices. Include the cipher here since
* OpenVPN 2.5 will otherwise ignore it and break on conrer cases
* like --cipher AES-128-CBC on client and --data-ciphers "AES-128-CBC"
* on server.
*
*/
out << "IV_CIPHERS=AES-256-GCM:AES-128-GCM";
if (openvpn::AEAD::is_algorithm_supported<SSLLib::CryptoAPI>(CryptoAlgs::CHACHA20_POLY1305))
{
out << ":CHACHA20-POLY1305";
}
if (openvpn::CryptoAlgs::defined(dc.cipher()) &&
dc.cipher() != CryptoAlgs::AES_128_GCM &&
dc.cipher() != CryptoAlgs::AES_256_GCM &&
dc.cipher() != CryptoAlgs::CHACHA20_POLY1305)
{
out << ":" << openvpn::CryptoAlgs::name(dc.cipher());
}
out << "\n";
compstr = comp_ctx.peer_info_string();
if (compstr)
out << compstr;
if (extra_peer_info)
out << extra_peer_info->to_string();
if (is_bs64_cipher(dc.cipher()))
out << "IV_BS64DL=1\n"; // indicate support for data limits when using 64-bit block-size ciphers, version 1 (CVE-2016-6329)
if (relay_mode)
out << "IV_RELAY=1\n";
const std::string ret = out.str();
OPENVPN_LOG_PROTO("Peer Info:" << std::endl << ret);
return ret;
}
// Used to generate link_mtu option sent to peer.
// Not const because dc.context() caches the DC context.
unsigned int link_mtu_adjust()
{
const size_t adj = protocol.extra_transport_bytes() + // extra 2 bytes for TCP-streamed packet length
(enable_op32 ? 4 : 1) + // leading op
comp_ctx.extra_payload_bytes() + // compression header
PacketID::size(PacketID::SHORT_FORM) + // sequence number
dc.context().encap_overhead(); // data channel crypto layer overhead
return (unsigned int)adj;
}
private:
enum LoadCommonType {
LOAD_COMMON_SERVER,
LOAD_COMMON_CLIENT,
LOAD_COMMON_CLIENT_PUSHED,
};
// load parameters that can be present in both config file or pushed options
void load_common(const OptionList& opt, const ProtoContextOptions& pco,
const LoadCommonType type)
{
// duration parms
load_duration_parm(renegotiate, "reneg-sec", opt, 10, false, false);
expire = renegotiate;
load_duration_parm(expire, "tran-window", opt, 10, false, false);
expire += renegotiate;
load_duration_parm(handshake_window, "hand-window", opt, 10, false, false);
if (is_bs64_cipher(dc.cipher())) // special data limits for 64-bit block-size ciphers (CVE-2016-6329)
{
become_primary = Time::Duration::seconds(5);
tls_timeout = Time::Duration::milliseconds(1000);
}
else
become_primary = Time::Duration::seconds(std::min(handshake_window.to_seconds(),
renegotiate.to_seconds() / 2));
load_duration_parm(become_primary, "become-primary", opt, 0, false, false);
load_duration_parm(tls_timeout, "tls-timeout", opt, 100, false, true);
if (type == LOAD_COMMON_SERVER)
renegotiate += handshake_window; // avoid renegotiation collision with client
// keepalive, ping, ping-restart
{
const Option *o = opt.get_ptr("keepalive");
if (o)
{
set_duration_parm(keepalive_ping, "keepalive ping", o->get(1, 16), 1, false, false);
set_duration_parm(keepalive_timeout, "keepalive timeout", o->get(2, 16), 1, type == LOAD_COMMON_SERVER, false);
}
else
{
load_duration_parm(keepalive_ping, "ping", opt, 1, false, false);
load_duration_parm(keepalive_timeout, "ping-restart", opt, 1, false, false);
}
}
}
std::string relay_prefix(const char *optname) const
{
std::string ret;
if (relay_mode)
ret = "relay-";
ret += optname;
return ret;
}
};
// Used to describe an incoming network packet
class PacketType
{
friend class ProtoContext;
enum {
DEFINED=1<<0, // packet is valid (otherwise invalid)
CONTROL=1<<1, // packet for control channel (otherwise for data channel)
SECONDARY=1<<2, // packet is associated with secondary KeyContext (otherwise primary)
SOFT_RESET=1<<3, // packet is a CONTROL_SOFT_RESET_V1 msg indicating a request for SSL/TLS renegotiate
};
public:
bool is_defined() const { return flags & DEFINED; }
bool is_control() const { return (flags & (CONTROL|DEFINED)) == (CONTROL|DEFINED); }
bool is_data() const { return (flags & (CONTROL|DEFINED)) == DEFINED; }
bool is_soft_reset() const { return (flags & (CONTROL|DEFINED|SECONDARY|SOFT_RESET))
== (CONTROL|DEFINED|SECONDARY|SOFT_RESET); }
int peer_id() const { return peer_id_; }
private:
PacketType(const Buffer& buf, class ProtoContext& proto)
: flags(0), opcode(INVALID_OPCODE), peer_id_(-1)
{
if (likely(buf.size()))
{
// get packet header byte
const unsigned int op = buf[0];