forked from zerotier/ZeroTierOne
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetwork.cpp
More file actions
1849 lines (1682 loc) · 60.6 KB
/
Copy pathNetwork.cpp
File metadata and controls
1849 lines (1682 loc) · 60.6 KB
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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* (c) ZeroTier, Inc.
* https://www.zerotier.com/
*/
#include "Network.hpp"
#include "../include/ZeroTierDebug.h"
#include "../version.h"
#include "Address.hpp"
#include "Buffer.hpp"
#include "Constants.hpp"
#include "ECC.hpp"
#include "InetAddress.hpp"
#include "MAC.hpp"
#include "Metrics.hpp"
#include "NetworkController.hpp"
#include "Node.hpp"
#include "Packet.hpp"
#include "Peer.hpp"
#include "RuntimeEnvironment.hpp"
#include "Switch.hpp"
#include "Trace.hpp"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
namespace ZeroTier {
namespace {
// Returns true if packet appears valid; pos and proto will be set
static inline bool _ipv6GetPayload(const uint8_t* frameData, unsigned int frameLen, unsigned int& pos, unsigned int& proto)
{
if (frameLen < 40) {
return false;
}
pos = 40;
proto = frameData[6];
while (pos <= frameLen) {
switch (proto) {
case 0: // hop-by-hop options
case 43: // routing
case 60: // destination options
case 135: // mobility options
if ((pos + 8) > frameLen) {
return false; // invalid!
}
proto = frameData[pos];
pos += ((unsigned int)frameData[pos + 1] * 8) + 8;
break;
// case 44: // fragment -- we currently can't parse these and they are deprecated in IPv6 anyway
// case 50:
// case 51: // IPSec ESP and AH -- we have to stop here since this is encrypted stuff
default:
return true;
}
}
return false; // overflow == invalid
}
enum _doZtFilterResult { DOZTFILTER_NO_MATCH, DOZTFILTER_DROP, DOZTFILTER_REDIRECT, DOZTFILTER_ACCEPT, DOZTFILTER_SUPER_ACCEPT };
static _doZtFilterResult _doZtFilter(
const RuntimeEnvironment* RR,
Trace::RuleResultLog& rrl,
const NetworkConfig& nconf,
const Membership* membership, // can be NULL
const bool inbound,
const Address& ztSource,
Address& ztDest, // MUTABLE -- is changed on REDIRECT actions
const MAC& macSource,
const MAC& macDest,
const uint8_t* const frameData,
const unsigned int frameLen,
const unsigned int etherType,
const unsigned int vlanId,
const ZT_VirtualNetworkRule* rules, // cannot be NULL
const unsigned int ruleCount,
Address& cc, // MUTABLE -- set to TEE destination if TEE action is taken or left alone otherwise
unsigned int& ccLength, // MUTABLE -- set to length of packet payload to TEE
bool& ccWatch, // MUTABLE -- set to true for WATCH target as opposed to normal TEE
uint8_t& qosBucket) // MUTABLE -- set to the value of the argument provided to PRIORITY
{
// Set to true if we are a TEE/REDIRECT/WATCH target
bool superAccept = false;
// The default match state for each set of entries starts as 'true' since an
// ACTION with no MATCH entries preceding it is always taken.
uint8_t thisSetMatches = 1;
uint8_t skipDrop = 0;
rrl.clear();
// uncomment for easier debugging fprintf
// if (!ztDest) { return DOZTFILTER_ACCEPT; }
#ifdef ZT_TRACE
// char buf[40], buf2[40];
// fprintf(stderr, "\nsrc %s dest %s inbound: %d ethertype %u", ztSource.toString(buf), ztDest.toString(buf2), inbound, etherType);
#endif
for (unsigned int rn = 0; rn < ruleCount; ++rn) {
const ZT_VirtualNetworkRuleType rt = (ZT_VirtualNetworkRuleType)(rules[rn].t & 0x3f);
#ifdef ZT_TRACE
// fprintf(stderr, "\n%02u %02d", rn, rt);
#endif
// First check if this is an ACTION
if ((unsigned int)rt <= (unsigned int)ZT_NETWORK_RULE_ACTION__MAX_ID) {
if (thisSetMatches) {
switch (rt) {
case ZT_NETWORK_RULE_ACTION_PRIORITY:
qosBucket = (rules[rn].v.qosBucket <= 8) ? rules[rn].v.qosBucket : 4; // 4 = default bucket (no priority)
return DOZTFILTER_ACCEPT;
case ZT_NETWORK_RULE_ACTION_DROP: {
if (! ! skipDrop) {
#ifdef ZT_TRACE
// fprintf(stderr, "\tskip Drop");
#endif
skipDrop = 0;
continue;
}
#ifdef ZT_TRACE
// fprintf(stderr, "\tDrop\n");
#endif
return DOZTFILTER_DROP;
}
case ZT_NETWORK_RULE_ACTION_ACCEPT: {
#ifdef ZT_TRACE
// fprintf(stderr, "\tAccept\n");
#endif
return (superAccept ? DOZTFILTER_SUPER_ACCEPT : DOZTFILTER_ACCEPT); // match, accept packet
}
// These are initially handled together since preliminary logic is common
case ZT_NETWORK_RULE_ACTION_TEE:
case ZT_NETWORK_RULE_ACTION_WATCH:
case ZT_NETWORK_RULE_ACTION_REDIRECT: {
const Address fwdAddr(rules[rn].v.fwd.address);
if (fwdAddr == ztSource) {
// Skip as no-op since source is target
}
else if (fwdAddr == RR->identity.address()) {
if (inbound) {
return DOZTFILTER_SUPER_ACCEPT;
}
else {
}
}
else if (fwdAddr == ztDest) {
}
else {
if (rt == ZT_NETWORK_RULE_ACTION_REDIRECT) {
ztDest = fwdAddr;
return DOZTFILTER_REDIRECT;
}
else {
cc = fwdAddr;
ccLength = (rules[rn].v.fwd.length != 0) ? ((frameLen < (unsigned int)rules[rn].v.fwd.length) ? frameLen : (unsigned int)rules[rn].v.fwd.length) : frameLen;
ccWatch = (rt == ZT_NETWORK_RULE_ACTION_WATCH);
}
}
}
continue;
case ZT_NETWORK_RULE_ACTION_BREAK:
return DOZTFILTER_NO_MATCH;
// Unrecognized ACTIONs are ignored as no-ops
default:
continue;
}
}
else {
// If this is an incoming packet and we are a TEE or REDIRECT target, we should
// super-accept if we accept at all. This will cause us to accept redirected or
// tee'd packets in spite of MAC and ZT addressing checks.
if (inbound) {
switch (rt) {
case ZT_NETWORK_RULE_ACTION_TEE:
case ZT_NETWORK_RULE_ACTION_WATCH:
case ZT_NETWORK_RULE_ACTION_REDIRECT:
if (RR->identity.address() == rules[rn].v.fwd.address) {
superAccept = true;
}
break;
default:
break;
}
}
thisSetMatches = 1; // reset to default true for next batch of entries
continue;
}
}
// Circuit breaker: no need to evaluate an AND if the set's match state
// is currently false since anything AND false is false.
if ((! thisSetMatches) && (! (rules[rn].t & 0x40))) {
rrl.logSkipped(rn, thisSetMatches);
continue;
}
// If this was not an ACTION evaluate next MATCH and update thisSetMatches with (AND [result])
uint8_t thisRuleMatches = 0;
uint64_t ownershipVerificationMask = 1; // this magic value means it hasn't been computed yet -- this is done lazily the first time it's needed
uint8_t hardYes = (rules[rn].t >> 7) ^ 1; // XOR with the NOT bit of the rule
uint8_t hardNo = (rules[rn].t >> 7) ^ 0;
switch (rt) {
case ZT_NETWORK_RULE_MATCH_SOURCE_ZEROTIER_ADDRESS:
thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztSource.toInt());
break;
case ZT_NETWORK_RULE_MATCH_DEST_ZEROTIER_ADDRESS:
thisRuleMatches = (uint8_t)(rules[rn].v.zt == ztDest.toInt());
break;
case ZT_NETWORK_RULE_MATCH_VLAN_ID:
thisRuleMatches = (uint8_t)(rules[rn].v.vlanId == (uint16_t)vlanId);
break;
case ZT_NETWORK_RULE_MATCH_VLAN_PCP:
// NOT SUPPORTED YET
thisRuleMatches = (uint8_t)(rules[rn].v.vlanPcp == 0);
break;
case ZT_NETWORK_RULE_MATCH_VLAN_DEI:
// NOT SUPPORTED YET
thisRuleMatches = (uint8_t)(rules[rn].v.vlanDei == 0);
break;
case ZT_NETWORK_RULE_MATCH_MAC_SOURCE:
thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac, 6) == macSource);
break;
case ZT_NETWORK_RULE_MATCH_MAC_DEST:
thisRuleMatches = (uint8_t)(MAC(rules[rn].v.mac, 6) == macDest);
break;
case ZT_NETWORK_RULE_MATCH_IPV4_SOURCE:
if ((etherType == ZT_ETHERTYPE_IPV4) && (frameLen >= 20)) {
thisRuleMatches = (uint8_t)(InetAddress((const void*)&(rules[rn].v.ipv4.ip), 4, rules[rn].v.ipv4.mask).containsAddress(InetAddress((const void*)(frameData + 12), 4, 0)));
}
else {
thisRuleMatches = hardNo;
}
break;
case ZT_NETWORK_RULE_MATCH_IPV4_DEST:
if ((etherType == ZT_ETHERTYPE_IPV4) && (frameLen >= 20)) {
thisRuleMatches = (uint8_t)(InetAddress((const void*)&(rules[rn].v.ipv4.ip), 4, rules[rn].v.ipv4.mask).containsAddress(InetAddress((const void*)(frameData + 16), 4, 0)));
}
else {
thisRuleMatches = hardNo;
}
break;
case ZT_NETWORK_RULE_MATCH_IPV6_SOURCE:
if ((etherType == ZT_ETHERTYPE_IPV6) && (frameLen >= 40)) {
thisRuleMatches = (uint8_t)(InetAddress((const void*)rules[rn].v.ipv6.ip, 16, rules[rn].v.ipv6.mask).containsAddress(InetAddress((const void*)(frameData + 8), 16, 0)));
}
else {
thisRuleMatches = hardNo;
}
break;
case ZT_NETWORK_RULE_MATCH_IPV6_DEST:
if ((etherType == ZT_ETHERTYPE_IPV6) && (frameLen >= 40)) {
thisRuleMatches = (uint8_t)(InetAddress((const void*)rules[rn].v.ipv6.ip, 16, rules[rn].v.ipv6.mask).containsAddress(InetAddress((const void*)(frameData + 24), 16, 0)));
}
else {
thisRuleMatches = hardNo;
}
break;
case ZT_NETWORK_RULE_MATCH_IP_TOS:
if ((etherType == ZT_ETHERTYPE_IPV4) && (frameLen >= 20)) {
const uint8_t tosMasked = frameData[1] & rules[rn].v.ipTos.mask;
thisRuleMatches = (uint8_t)((tosMasked >= rules[rn].v.ipTos.value[0]) && (tosMasked <= rules[rn].v.ipTos.value[1]));
}
else if ((etherType == ZT_ETHERTYPE_IPV6) && (frameLen >= 40)) {
const uint8_t tosMasked = (((frameData[0] << 4) & 0xf0) | ((frameData[1] >> 4) & 0x0f)) & rules[rn].v.ipTos.mask;
thisRuleMatches = (uint8_t)((tosMasked >= rules[rn].v.ipTos.value[0]) && (tosMasked <= rules[rn].v.ipTos.value[1]));
}
else {
thisRuleMatches = hardNo;
}
break;
case ZT_NETWORK_RULE_MATCH_IP_PROTOCOL:
if ((etherType == ZT_ETHERTYPE_IPV4) && (frameLen >= 20)) {
thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == frameData[9]);
}
else if (etherType == ZT_ETHERTYPE_IPV6) {
unsigned int pos = 0, proto = 0;
if (_ipv6GetPayload(frameData, frameLen, pos, proto)) {
thisRuleMatches = (uint8_t)(rules[rn].v.ipProtocol == (uint8_t)proto);
}
else {
thisRuleMatches = hardNo;
}
}
else {
thisRuleMatches = hardNo;
}
break;
case ZT_NETWORK_RULE_MATCH_ETHERTYPE:
thisRuleMatches = (uint8_t)(rules[rn].v.etherType == (uint16_t)etherType);
break;
case ZT_NETWORK_RULE_MATCH_ICMP:
if ((etherType == ZT_ETHERTYPE_IPV4) && (frameLen >= 20)) {
if (frameData[9] == 0x01) { // IP protocol == ICMP
const unsigned int ihl = (frameData[0] & 0xf) * 4;
if (frameLen >= (ihl + 2)) {
if (rules[rn].v.icmp.type == frameData[ihl]) {
if ((rules[rn].v.icmp.flags & 0x01) != 0) {
thisRuleMatches = (uint8_t)(frameData[ihl + 1] == rules[rn].v.icmp.code);
}
else {
thisRuleMatches = hardYes;
}
}
else {
thisRuleMatches = hardNo;
}
}
else {
thisRuleMatches = hardNo;
}
}
else {
thisRuleMatches = hardNo;
}
}
else if (etherType == ZT_ETHERTYPE_IPV6) {
unsigned int pos = 0, proto = 0;
if (_ipv6GetPayload(frameData, frameLen, pos, proto)) {
if ((proto == 0x3a) && (frameLen >= (pos + 2))) {
if (rules[rn].v.icmp.type == frameData[pos]) {
if ((rules[rn].v.icmp.flags & 0x01) != 0) {
thisRuleMatches = (uint8_t)(frameData[pos + 1] == rules[rn].v.icmp.code);
}
else {
thisRuleMatches = hardYes;
}
}
else {
thisRuleMatches = hardNo;
}
}
else {
thisRuleMatches = hardNo;
}
}
else {
thisRuleMatches = hardNo;
}
}
else {
thisRuleMatches = hardNo;
}
break;
case ZT_NETWORK_RULE_MATCH_IP_SOURCE_PORT_RANGE:
case ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE:
if ((etherType == ZT_ETHERTYPE_IPV4) && (frameLen >= 20)) {
const unsigned int headerLen = 4 * (frameData[0] & 0xf);
int p = -1;
switch (frameData[9]) { // IP protocol number
// All these start with 16-bit source and destination port in that order
case 0x06: // TCP
case 0x11: // UDP
case 0x84: // SCTP
case 0x88: // UDPLite
if (frameLen > (headerLen + 4)) {
unsigned int pos = headerLen + ((rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) ? 2 : 0);
p = (int)frameData[pos++] << 8;
p |= (int)frameData[pos];
}
break;
}
thisRuleMatches = (p >= 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0]) && (p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
}
else if (etherType == ZT_ETHERTYPE_IPV6) {
unsigned int pos = 0, proto = 0;
if (_ipv6GetPayload(frameData, frameLen, pos, proto)) {
int p = -1;
switch (proto) { // IP protocol number
// All these start with 16-bit source and destination port in that order
case 0x06: // TCP
case 0x11: // UDP
case 0x84: // SCTP
case 0x88: // UDPLite
if (frameLen > (pos + 4)) {
if (rt == ZT_NETWORK_RULE_MATCH_IP_DEST_PORT_RANGE) {
pos += 2;
}
p = (int)frameData[pos++] << 8;
p |= (int)frameData[pos];
}
break;
}
thisRuleMatches = (p > 0) ? (uint8_t)((p >= (int)rules[rn].v.port[0]) && (p <= (int)rules[rn].v.port[1])) : (uint8_t)0;
}
else {
thisRuleMatches = hardNo;
}
}
else {
thisRuleMatches = hardNo;
}
break;
case ZT_NETWORK_RULE_MATCH_CHARACTERISTICS: {
uint64_t cf = (inbound) ? ZT_RULE_PACKET_CHARACTERISTICS_INBOUND : 0ULL;
if (macDest.isMulticast()) {
cf |= ZT_RULE_PACKET_CHARACTERISTICS_MULTICAST;
}
if (macDest.isBroadcast()) {
cf |= ZT_RULE_PACKET_CHARACTERISTICS_BROADCAST;
}
if (ownershipVerificationMask == 1) {
ownershipVerificationMask = 0;
InetAddress src;
if ((etherType == ZT_ETHERTYPE_IPV4) && (frameLen >= 20)) {
src.set((const void*)(frameData + 12), 4, 0);
}
else if ((etherType == ZT_ETHERTYPE_IPV6) && (frameLen >= 40)) {
// IPv6 NDP requires special handling, since the src and dest IPs in the packet are empty or link-local.
if ((frameLen >= (40 + 8 + 16)) && (frameData[6] == 0x3a) && ((frameData[40] == 0x87) || (frameData[40] == 0x88))) {
if (frameData[40] == 0x87) {
// Neighbor solicitations contain no reliable source address, so we implement a small
// hack by considering them authenticated. Otherwise you would pretty much have to do
// this manually in the rule set for IPv6 to work at all.
ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_IP_AUTHENTICATED;
}
else {
// Neighbor advertisements on the other hand can absolutely be authenticated.
src.set((const void*)(frameData + 40 + 8), 16, 0);
}
}
else {
// Other IPv6 packets can be handled normally
src.set((const void*)(frameData + 8), 16, 0);
}
}
else if ((etherType == ZT_ETHERTYPE_ARP) && (frameLen >= 28)) {
src.set((const void*)(frameData + 14), 4, 0);
}
if (inbound) {
if (membership) {
if ((src) && (membership->hasCertificateOfOwnershipFor<InetAddress>(nconf, src))) {
ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_IP_AUTHENTICATED;
}
if (membership->hasCertificateOfOwnershipFor<MAC>(nconf, macSource)) {
ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_MAC_AUTHENTICATED;
}
}
}
else {
for (unsigned int i = 0; i < nconf.certificateOfOwnershipCount; ++i) {
if ((src) && (nconf.certificatesOfOwnership[i].owns(src))) {
ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_IP_AUTHENTICATED;
}
if (nconf.certificatesOfOwnership[i].owns(macSource)) {
ownershipVerificationMask |= ZT_RULE_PACKET_CHARACTERISTICS_SENDER_MAC_AUTHENTICATED;
}
}
}
}
cf |= ownershipVerificationMask;
if ((etherType == ZT_ETHERTYPE_IPV4) && (frameLen >= 20) && (frameData[9] == 0x06)) {
const unsigned int headerLen = 4 * (frameData[0] & 0xf);
cf |= (uint64_t)frameData[headerLen + 13];
cf |= (((uint64_t)(frameData[headerLen + 12] & 0x0f)) << 8);
}
else if (etherType == ZT_ETHERTYPE_IPV6) {
unsigned int pos = 0, proto = 0;
if (_ipv6GetPayload(frameData, frameLen, pos, proto)) {
if ((proto == 0x06) && (frameLen > (pos + 14))) {
cf |= (uint64_t)frameData[pos + 13];
cf |= (((uint64_t)(frameData[pos + 12] & 0x0f)) << 8);
}
}
}
thisRuleMatches = (uint8_t)((cf & rules[rn].v.characteristics) != 0);
} break;
case ZT_NETWORK_RULE_MATCH_FRAME_SIZE_RANGE:
thisRuleMatches = (uint8_t)((frameLen >= (unsigned int)rules[rn].v.frameSize[0]) && (frameLen <= (unsigned int)rules[rn].v.frameSize[1]));
break;
case ZT_NETWORK_RULE_MATCH_RANDOM:
thisRuleMatches = (uint8_t)((uint32_t)(RR->node->prng() & 0xffffffffULL) <= rules[rn].v.randomProbability);
break;
case ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE:
case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND:
case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR:
case ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR:
case ZT_NETWORK_RULE_MATCH_TAGS_EQUAL: {
const Tag* const localTag = std::lower_bound(&(nconf.tags[0]), &(nconf.tags[nconf.tagCount]), rules[rn].v.tag.id, Tag::IdComparePredicate());
if ((localTag != &(nconf.tags[nconf.tagCount])) && (localTag->id() == rules[rn].v.tag.id)) {
const Tag* const remoteTag = ((membership) ? membership->getTag(nconf, rules[rn].v.tag.id) : (const Tag*)0);
#ifdef ZT_TRACE
/*fprintf(stderr, "\tlocal tag [%u: %u] remote tag [%u: %u] match [%u]",
!!localTag ? localTag->id() : 0,
!!localTag ? localTag->value() : 0,
!!remoteTag ? remoteTag->id() : 0,
!!remoteTag ? remoteTag->value() : 0,
thisRuleMatches);*/
#endif
if (remoteTag) {
const uint32_t ltv = localTag->value();
const uint32_t rtv = remoteTag->value();
if (rt == ZT_NETWORK_RULE_MATCH_TAGS_DIFFERENCE) {
const uint32_t diff = (ltv > rtv) ? (ltv - rtv) : (rtv - ltv);
thisRuleMatches = (uint8_t)(diff <= rules[rn].v.tag.value);
}
else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_AND) {
thisRuleMatches = (uint8_t)((ltv & rtv) == rules[rn].v.tag.value);
}
else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_OR) {
thisRuleMatches = (uint8_t)((ltv | rtv) == rules[rn].v.tag.value);
}
else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_BITWISE_XOR) {
thisRuleMatches = (uint8_t)((ltv ^ rtv) == rules[rn].v.tag.value);
}
else if (rt == ZT_NETWORK_RULE_MATCH_TAGS_EQUAL) {
thisRuleMatches = (uint8_t)((ltv == rules[rn].v.tag.value) && (rtv == rules[rn].v.tag.value));
}
else { // sanity check, can't really happen
thisRuleMatches = hardNo;
}
}
else {
if ((inbound) && (! superAccept)) {
thisRuleMatches = hardNo;
#ifdef ZT_TRACE
// fprintf(stderr, "\tinbound ");
#endif
}
else {
// Outbound side is not strict since if we have to match both tags and
// we are sending a first packet to a recipient, we probably do not know
// about their tags yet. They will filter on inbound and we will filter
// once we get their tag. If we are a tee/redirect target we are also
// not strict since we likely do not have these tags.
skipDrop = 1;
thisRuleMatches = hardYes;
#ifdef ZT_TRACE
// fprintf(stderr, "\toutbound ");
#endif
}
}
}
else {
thisRuleMatches = hardNo;
}
} break;
case ZT_NETWORK_RULE_MATCH_TAG_SENDER:
case ZT_NETWORK_RULE_MATCH_TAG_RECEIVER: {
const Tag* const localTag = std::lower_bound(&(nconf.tags[0]), &(nconf.tags[nconf.tagCount]), rules[rn].v.tag.id, Tag::IdComparePredicate());
#ifdef ZT_TRACE
/*const Tag *const remoteTag = ((membership) ? membership->getTag(nconf,rules[rn].v.tag.id) : (const Tag *)0);
fprintf(stderr, "\tlocal tag [%u: %u] remote tag [%u: %u] match [%u]",
!!localTag ? localTag->id() : 0,
!!localTag ? localTag->value() : 0,
!!remoteTag ? remoteTag->id() : 0,
!!remoteTag ? remoteTag->value() : 0,
thisRuleMatches);*/
#endif
if (superAccept) {
skipDrop = 1;
thisRuleMatches = hardYes;
}
else if (((rt == ZT_NETWORK_RULE_MATCH_TAG_SENDER) && (inbound)) || ((rt == ZT_NETWORK_RULE_MATCH_TAG_RECEIVER) && (! inbound))) {
const Tag* const remoteTag = ((membership) ? membership->getTag(nconf, rules[rn].v.tag.id) : (const Tag*)0);
if (remoteTag) {
thisRuleMatches = (uint8_t)(remoteTag->value() == rules[rn].v.tag.value);
}
else {
if (rt == ZT_NETWORK_RULE_MATCH_TAG_RECEIVER) {
// If we are checking the receiver and this is an outbound packet, we
// can't be strict since we may not yet know the receiver's tag.
skipDrop = 1;
thisRuleMatches = hardYes;
}
else {
thisRuleMatches = hardNo;
}
}
}
else { // sender and outbound or receiver and inbound
if ((localTag != &(nconf.tags[nconf.tagCount])) && (localTag->id() == rules[rn].v.tag.id)) {
thisRuleMatches = (uint8_t)(localTag->value() == rules[rn].v.tag.value);
}
else {
thisRuleMatches = hardNo;
}
}
} break;
case ZT_NETWORK_RULE_MATCH_INTEGER_RANGE: {
uint64_t integer = 0;
const unsigned int bits = (rules[rn].v.intRange.format & 63) + 1;
const unsigned int bytes = ((bits + 8 - 1) / 8); // integer ceiling of division by 8
if ((rules[rn].v.intRange.format & 0x80) == 0) {
// Big-endian
unsigned int idx = rules[rn].v.intRange.idx + (8 - bytes);
const unsigned int eof = idx + bytes;
if (eof <= frameLen) {
while (idx < eof) {
integer <<= 8;
integer |= frameData[idx++];
}
}
integer &= 0xffffffffffffffffULL >> (64 - bits);
}
else {
// Little-endian
unsigned int idx = rules[rn].v.intRange.idx;
const unsigned int eof = idx + bytes;
if (eof <= frameLen) {
while (idx < eof) {
integer >>= 8;
integer |= ((uint64_t)frameData[idx++]) << 56;
}
}
integer >>= (64 - bits);
}
thisRuleMatches = (uint8_t)((integer >= rules[rn].v.intRange.start) && (integer <= (rules[rn].v.intRange.start + (uint64_t)rules[rn].v.intRange.end)));
} break;
// The result of an unsupported MATCH is configurable at the network
// level via a flag.
default:
thisRuleMatches = (uint8_t)((nconf.flags & ZT_NETWORKCONFIG_FLAG_RULES_RESULT_OF_UNSUPPORTED_MATCH) != 0);
break;
}
rrl.log(rn, thisRuleMatches, thisSetMatches);
if ((rules[rn].t & 0x40)) {
thisSetMatches |= (thisRuleMatches ^ ((rules[rn].t >> 7) & 1));
}
else {
thisSetMatches &= (thisRuleMatches ^ ((rules[rn].t >> 7) & 1));
}
}
return DOZTFILTER_NO_MATCH;
}
} // anonymous namespace
const ZeroTier::MulticastGroup Network::BROADCAST(ZeroTier::MAC(0xffffffffffffULL), 0);
Network::Network(const RuntimeEnvironment* renv, void* tPtr, uint64_t nwid, void* uptr, const NetworkConfig* nconf)
: RR(renv)
, _uPtr(uptr)
, _id(nwid)
, _nwidStr(OSUtils::networkIDStr(nwid))
, _lastAnnouncedMulticastGroupsUpstream(0)
, _mac(renv->identity.address(), nwid)
, _portInitialized(false)
, _lastConfigUpdate(0)
, _destroyed(false)
, _netconfFailure(NETCONF_FAILURE_NONE)
, _portError(0)
, _num_multicast_groups { Metrics::network_num_multicast_groups.Add({ { "network_id", _nwidStr } }) }
, _incoming_packets_accepted { Metrics::network_packets.Add({ { "direction", "rx" }, { "network_id", _nwidStr }, { "accepted", "yes" } }) }
, _incoming_packets_dropped { Metrics::network_packets.Add({ { "direction", "rx" }, { "network_id", _nwidStr }, { "accepted", "no" } }) }
, _outgoing_packets_accepted { Metrics::network_packets.Add({ { "direction", "tx" }, { "network_id", _nwidStr }, { "accepted", "yes" } }) }
, _outgoing_packets_dropped { Metrics::network_packets.Add({ { "direction", "tx" }, { "network_id", _nwidStr }, { "accepted", "no" } }) }
{
for (int i = 0; i < ZT_NETWORK_MAX_INCOMING_UPDATES; ++i) {
_incomingConfigChunks[i].ts = 0;
}
if (nconf) {
this->setConfiguration(tPtr, *nconf, false);
_lastConfigUpdate = 0; // still want to re-request since it's likely outdated
}
else {
uint64_t tmp[2];
tmp[0] = nwid;
tmp[1] = 0;
bool got = false;
Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>* dict = new Dictionary<ZT_NETWORKCONFIG_DICT_CAPACITY>();
try {
int n = RR->node->stateObjectGet(tPtr, ZT_STATE_OBJECT_NETWORK_CONFIG, tmp, dict->unsafeData(), ZT_NETWORKCONFIG_DICT_CAPACITY - 1);
if (n > 1) {
NetworkConfig* nconf = new NetworkConfig();
try {
if (nconf->fromDictionary(*dict)) {
this->setConfiguration(tPtr, *nconf, false);
_lastConfigUpdate = 0; // still want to re-request an update since it's likely outdated
got = true;
}
}
catch (...) {
}
delete nconf;
}
}
catch (...) {
}
delete dict;
if (! got) {
RR->node->stateObjectPut(tPtr, ZT_STATE_OBJECT_NETWORK_CONFIG, tmp, "\n", 1);
}
}
if (! _portInitialized) {
ZT_VirtualNetworkConfig ctmp;
memset(&ctmp, 0, sizeof(ZT_VirtualNetworkConfig));
_externalConfig(&ctmp);
_portError = RR->node->configureVirtualNetworkPort(tPtr, _id, &_uPtr, ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP, &ctmp);
_portInitialized = true;
}
Metrics::network_num_joined++;
}
Network::~Network()
{
ZT_VirtualNetworkConfig ctmp;
_externalConfig(&ctmp);
Metrics::network_num_joined--;
if (_destroyed) {
// This is done in Node::leave() so we can pass tPtr properly
// RR->node->configureVirtualNetworkPort((void *)0,_id,&_uPtr,ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DESTROY,&ctmp);
}
else {
RR->node->configureVirtualNetworkPort((void*)0, _id, &_uPtr, ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_DOWN, &ctmp);
}
}
bool Network::filterOutgoingPacket(
void* tPtr,
const bool noTee,
const Address& ztSource,
const Address& ztDest,
const MAC& macSource,
const MAC& macDest,
const uint8_t* frameData,
const unsigned int frameLen,
const unsigned int etherType,
const unsigned int vlanId,
uint8_t& qosBucket)
{
Address ztFinalDest(ztDest);
int localCapabilityIndex = -1;
int accept = 0;
Trace::RuleResultLog rrl, crrl;
Address cc;
unsigned int ccLength = 0;
bool ccWatch = false;
Mutex::Lock _l(_lock);
Membership* const membership = (ztDest) ? _memberships.get(ztDest) : (Membership*)0;
switch (_doZtFilter(RR, rrl, _config, membership, false, ztSource, ztFinalDest, macSource, macDest, frameData, frameLen, etherType, vlanId, _config.rules, _config.ruleCount, cc, ccLength, ccWatch, qosBucket)) {
case DOZTFILTER_NO_MATCH: {
for (unsigned int c = 0; c < _config.capabilityCount; ++c) {
ztFinalDest = ztDest; // sanity check, shouldn't be possible if there was no match
Address cc2;
unsigned int ccLength2 = 0;
bool ccWatch2 = false;
switch (_doZtFilter(
RR,
crrl,
_config,
membership,
false,
ztSource,
ztFinalDest,
macSource,
macDest,
frameData,
frameLen,
etherType,
vlanId,
_config.capabilities[c].rules(),
_config.capabilities[c].ruleCount(),
cc2,
ccLength2,
ccWatch2,
qosBucket)) {
case DOZTFILTER_NO_MATCH:
case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
break;
case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
case DOZTFILTER_ACCEPT:
case DOZTFILTER_SUPER_ACCEPT: // no difference in behavior on outbound side in capabilities
localCapabilityIndex = (int)c;
accept = 1;
if ((! noTee) && (cc2)) {
Packet outp(cc2, RR->identity.address(), Packet::VERB_EXT_FRAME);
outp.append(_id);
outp.append((uint8_t)(ccWatch2 ? 0x16 : 0x02));
macDest.appendTo(outp);
macSource.appendTo(outp);
outp.append((uint16_t)etherType);
outp.append(frameData, ccLength2);
RR->sw->send(tPtr, outp, true, _id, ZT_QOS_NO_FLOW);
}
break;
}
if (accept) {
break;
}
}
} break;
case DOZTFILTER_DROP:
if (_config.remoteTraceTarget) {
RR->t->networkFilter(tPtr, *this, rrl, (Trace::RuleResultLog*)0, (Capability*)0, ztSource, ztDest, macSource, macDest, frameData, frameLen, etherType, vlanId, noTee, false, 0);
}
return false;
case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
case DOZTFILTER_ACCEPT:
accept = 1;
break;
case DOZTFILTER_SUPER_ACCEPT:
accept = 2;
break;
}
if (accept) {
_outgoing_packets_accepted++;
if ((! noTee) && (cc)) {
Packet outp(cc, RR->identity.address(), Packet::VERB_EXT_FRAME);
outp.append(_id);
outp.append((uint8_t)(ccWatch ? 0x16 : 0x02));
macDest.appendTo(outp);
macSource.appendTo(outp);
outp.append((uint16_t)etherType);
outp.append(frameData, ccLength);
RR->sw->send(tPtr, outp, true, _id, ZT_QOS_NO_FLOW);
}
if ((ztDest != ztFinalDest) && (ztFinalDest)) {
Packet outp(ztFinalDest, RR->identity.address(), Packet::VERB_EXT_FRAME);
outp.append(_id);
outp.append((uint8_t)0x04);
macDest.appendTo(outp);
macSource.appendTo(outp);
outp.append((uint16_t)etherType);
outp.append(frameData, frameLen);
RR->sw->send(tPtr, outp, true, _id, ZT_QOS_NO_FLOW);
if (_config.remoteTraceTarget) {
RR->t->networkFilter(
tPtr,
*this,
rrl,
(localCapabilityIndex >= 0) ? &crrl : (Trace::RuleResultLog*)0,
(localCapabilityIndex >= 0) ? &(_config.capabilities[localCapabilityIndex]) : (Capability*)0,
ztSource,
ztDest,
macSource,
macDest,
frameData,
frameLen,
etherType,
vlanId,
noTee,
false,
0);
}
return false; // DROP locally, since we redirected
}
else {
if (_config.remoteTraceTarget) {
RR->t->networkFilter(
tPtr,
*this,
rrl,
(localCapabilityIndex >= 0) ? &crrl : (Trace::RuleResultLog*)0,
(localCapabilityIndex >= 0) ? &(_config.capabilities[localCapabilityIndex]) : (Capability*)0,
ztSource,
ztDest,
macSource,
macDest,
frameData,
frameLen,
etherType,
vlanId,
noTee,
false,
1);
}
return true;
}
}
else {
_outgoing_packets_dropped++;
if (_config.remoteTraceTarget) {
RR->t->networkFilter(
tPtr,
*this,
rrl,
(localCapabilityIndex >= 0) ? &crrl : (Trace::RuleResultLog*)0,
(localCapabilityIndex >= 0) ? &(_config.capabilities[localCapabilityIndex]) : (Capability*)0,
ztSource,
ztDest,
macSource,
macDest,
frameData,
frameLen,
etherType,
vlanId,
noTee,
false,
0);
}
return false;
}
}
int Network::filterIncomingPacket(
void* tPtr,
const SharedPtr<Peer>& sourcePeer,
const Address& ztDest,
const MAC& macSource,
const MAC& macDest,
const uint8_t* frameData,
const unsigned int frameLen,
const unsigned int etherType,
const unsigned int vlanId)
{
Address ztFinalDest(ztDest);
Trace::RuleResultLog rrl, crrl;
int accept = 0;
Address cc;
unsigned int ccLength = 0;
bool ccWatch = false;
const Capability* c = (Capability*)0;
uint8_t qosBucket = 255; // For incoming packets this is a dummy value
Mutex::Lock _l(_lock);
Membership& membership = _membership(sourcePeer->address());
switch (_doZtFilter(RR, rrl, _config, &membership, true, sourcePeer->address(), ztFinalDest, macSource, macDest, frameData, frameLen, etherType, vlanId, _config.rules, _config.ruleCount, cc, ccLength, ccWatch, qosBucket)) {
case DOZTFILTER_NO_MATCH: {
Membership::CapabilityIterator mci(membership, _config);
while ((c = mci.next())) {
ztFinalDest = ztDest; // sanity check, should be unmodified if there was no match
Address cc2;
unsigned int ccLength2 = 0;
bool ccWatch2 = false;
switch (_doZtFilter(RR, crrl, _config, &membership, true, sourcePeer->address(), ztFinalDest, macSource, macDest, frameData, frameLen, etherType, vlanId, c->rules(), c->ruleCount(), cc2, ccLength2, ccWatch2, qosBucket)) {
case DOZTFILTER_NO_MATCH:
case DOZTFILTER_DROP: // explicit DROP in a capability just terminates its evaluation and is an anti-pattern
break;
case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztDest will have been changed in _doZtFilter()
case DOZTFILTER_ACCEPT:
accept = 1; // ACCEPT
break;
case DOZTFILTER_SUPER_ACCEPT:
accept = 2; // super-ACCEPT
break;
}
if (accept) {
if (cc2) {
Packet outp(cc2, RR->identity.address(), Packet::VERB_EXT_FRAME);
outp.append(_id);
outp.append((uint8_t)(ccWatch2 ? 0x1c : 0x08));
macDest.appendTo(outp);
macSource.appendTo(outp);
outp.append((uint16_t)etherType);
outp.append(frameData, ccLength2);
RR->sw->send(tPtr, outp, true, _id, ZT_QOS_NO_FLOW);
}
break;
}
}
} break;
case DOZTFILTER_DROP:
if (_config.remoteTraceTarget) {
RR->t->networkFilter(tPtr, *this, rrl, (Trace::RuleResultLog*)0, (Capability*)0, sourcePeer->address(), ztDest, macSource, macDest, frameData, frameLen, etherType, vlanId, false, true, 0);
}
return 0; // DROP
case DOZTFILTER_REDIRECT: // interpreted as ACCEPT but ztFinalDest will have been changed in _doZtFilter()
case DOZTFILTER_ACCEPT:
accept = 1; // ACCEPT
break;
case DOZTFILTER_SUPER_ACCEPT:
accept = 2; // super-ACCEPT
break;
}
if (accept) {