forked from ligato/vpp-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnat_config.go
1141 lines (1014 loc) · 37.6 KB
/
nat_config.go
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
// Copyright (c) 2018 Cisco and/or its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ifplugin
import (
"net"
"strconv"
"strings"
govppapi "git.fd.io/govpp.git/api"
"github.com/go-errors/errors"
"github.com/gogo/protobuf/proto"
"github.com/ligato/cn-infra/logging"
"github.com/ligato/cn-infra/utils/safeclose"
"github.com/ligato/vpp-agent/idxvpp"
"github.com/ligato/vpp-agent/idxvpp/nametoidx"
"github.com/ligato/vpp-agent/plugins/govppmux"
"github.com/ligato/vpp-agent/plugins/vpp/ifplugin/ifaceidx"
"github.com/ligato/vpp-agent/plugins/vpp/ifplugin/vppcalls"
"github.com/ligato/vpp-agent/plugins/vpp/model/nat"
)
// Mapping labels
const (
dummyTag = "dummy-tag" // used for deletion where tag is not needed
)
// Default NAT virtual reassembly values
const (
maxReassembly = 1024
maxFragments = 5
timeout = 2
)
// NatConfigurator runs in the background in its own goroutine where it watches for any changes
// in the configuration of NAT address pools and static entries with or without a load ballance,
// as modelled by the proto file "../common/model/nat/nat.proto"
// and stored in ETCD under the keys:
// - "/vnf-agent/{agent-label}/vpp/config/v1/nat/{vrf}/addrpool/" for NAT address pool
// - "/vnf-agent/{agent-label}/vpp/config/v1/nat/{vrf}/static/" for NAT static mapping
// - "/vnf-agent/{agent-label}/vpp/config/v1/nat/{vrf}/staticlb/" for NAT static mapping with
// load balancer
// Updates received from the northbound API are compared with the VPP run-time configuration and differences
// are applied through the VPP binary API.
type NatConfigurator struct {
log logging.Logger
// Global config
globalNAT *nat.Nat44Global
// Mappings
ifIndexes ifaceidx.SwIfIndex
sNatIndexes idxvpp.NameToIdxRW // SNAT config indices
sNatMappingIndexes idxvpp.NameToIdxRW // SNAT indices for static mapping
dNatIndexes idxvpp.NameToIdxRW // DNAT indices
dNatStMappingIndexes idxvpp.NameToIdxRW // DNAT indices for static mapping
dNatIDMappingIndexes idxvpp.NameToIdxRW // DNAT indices for identity mapping
natIndexSeq uint32 // Nat name-to-idx mapping sequence
natMappingTagSeq uint32 // Static/identity mapping tag sequence
// a map of missing interfaces which should be enabled for NAT (format ifName/data)
notEnabledIfs map[string]*nat.Nat44Global_NatInterface
// a map of NAT-enabled interfaces which should be disabled (format ifName/data)
notDisabledIfs map[string]*nat.Nat44Global_NatInterface
// VPP channels
vppChan govppapi.Channel
vppDumpChan govppapi.Channel
// VPP API handler
natHandler vppcalls.NatVppAPI
}
// Init NAT configurator
func (c *NatConfigurator) Init(logger logging.PluginLogger, goVppMux govppmux.API, ifIndexes ifaceidx.SwIfIndex) (err error) {
// Logger
c.log = logger.NewLogger("nat-conf")
// Mappings
c.ifIndexes = ifIndexes
c.sNatIndexes = nametoidx.NewNameToIdx(c.log, "snat-indices", nil)
c.sNatMappingIndexes = nametoidx.NewNameToIdx(c.log, "snat-mapping-indices", nil)
c.dNatIndexes = nametoidx.NewNameToIdx(c.log, "dnat-indices", nil)
c.dNatStMappingIndexes = nametoidx.NewNameToIdx(c.log, "dnat-st-mapping-indices", nil)
c.dNatIDMappingIndexes = nametoidx.NewNameToIdx(c.log, "dnat-id-mapping-indices", nil)
c.notEnabledIfs = make(map[string]*nat.Nat44Global_NatInterface)
c.notDisabledIfs = make(map[string]*nat.Nat44Global_NatInterface)
c.natIndexSeq, c.natMappingTagSeq = 1, 1
// Init VPP API channel
if c.vppChan, err = goVppMux.NewAPIChannel(); err != nil {
return errors.Errorf("failed to create API channel: %v", err)
}
if c.vppDumpChan, err = goVppMux.NewAPIChannel(); err != nil {
return errors.Errorf("failed to create dump API channel: %v", err)
}
// VPP API handler
c.natHandler = vppcalls.NewNatVppHandler(c.vppChan, c.vppDumpChan, c.ifIndexes, c.log)
c.log.Info("NAT configurator initialized")
return nil
}
// Close used resources
func (c *NatConfigurator) Close() error {
if err := safeclose.Close(c.vppChan, c.vppDumpChan); err != nil {
return c.LogError(errors.Errorf("failed to safeclose NAT configurator: %v", err))
}
return nil
}
// clearMapping prepares all in-memory-mappings and other cache fields. All previous cached entries are removed.
func (c *NatConfigurator) clearMapping() {
c.sNatIndexes.Clear()
c.sNatMappingIndexes.Clear()
c.dNatIndexes.Clear()
c.dNatStMappingIndexes.Clear()
c.dNatIDMappingIndexes.Clear()
c.notEnabledIfs = make(map[string]*nat.Nat44Global_NatInterface)
c.notDisabledIfs = make(map[string]*nat.Nat44Global_NatInterface)
c.log.Debugf("NAT configurator mapping cleared")
}
// GetGlobalNat makes current global nat accessible
func (c *NatConfigurator) GetGlobalNat() *nat.Nat44Global {
return c.globalNAT
}
// IsInNotEnabledIfCache checks if interface is present in 'notEnabledIfs' cache
func (c *NatConfigurator) IsInNotEnabledIfCache(ifName string) bool {
_, ok := c.notEnabledIfs[ifName]
return ok
}
// IsInNotDisabledIfCache checks if interface is present in 'notDisabledIfs' cache
func (c *NatConfigurator) IsInNotDisabledIfCache(ifName string) bool {
_, ok := c.notDisabledIfs[ifName]
return ok
}
// IsDNatLabelRegistered checks if interface is present in 'notDisabledIfs' cache
func (c *NatConfigurator) IsDNatLabelRegistered(label string) bool {
_, _, found := c.dNatIndexes.LookupIdx(label)
return found
}
// IsDNatLabelStMappingRegistered checks if DNAT static mapping with provided id is registered
func (c *NatConfigurator) IsDNatLabelStMappingRegistered(id string) bool {
_, _, found := c.dNatStMappingIndexes.LookupIdx(id)
return found
}
// IsDNatLabelIDMappingRegistered checks if DNAT identity mapping with provided id is registered
func (c *NatConfigurator) IsDNatLabelIDMappingRegistered(id string) bool {
_, _, found := c.dNatIDMappingIndexes.LookupIdx(id)
return found
}
// SetNatGlobalConfig configures common setup for all NAT use cases
func (c *NatConfigurator) SetNatGlobalConfig(config *nat.Nat44Global) error {
// Store global NAT configuration (serves as cache)
c.globalNAT = config
// Forwarding
if err := c.natHandler.SetNat44Forwarding(config.Forwarding); err != nil {
return errors.Errorf("failed to set NAT44 forwarding to %t: %d", config.Forwarding, err)
}
// Inside/outside interfaces
if len(config.NatInterfaces) > 0 {
if err := c.enableNatInterfaces(config.NatInterfaces); err != nil {
return err
}
}
if err := c.addAddressPool(config.AddressPools); err != nil {
return err
}
// Virtual reassembly IPv4
if config.VirtualReassemblyIpv4 != nil {
if err := c.natHandler.SetVirtualReassemblyIPv4(config.VirtualReassemblyIpv4); err != nil {
return errors.Errorf("failed to set NAT virtual reassembly for IPv4: %v", err)
}
}
// Virtual reassembly IPv6
if config.VirtualReassemblyIpv6 != nil {
if err := c.natHandler.SetVirtualReassemblyIPv6(config.VirtualReassemblyIpv6); err != nil {
return errors.Errorf("failed to set NAT virtual reassembly for IPv6: %v", err)
}
}
c.log.Info("Setting up NAT global config done")
return nil
}
// ModifyNatGlobalConfig modifies common setup for all NAT use cases
func (c *NatConfigurator) ModifyNatGlobalConfig(oldConfig, newConfig *nat.Nat44Global) (err error) {
// Replace global NAT config
c.globalNAT = newConfig
// Forwarding
if oldConfig.Forwarding != newConfig.Forwarding {
if err := c.natHandler.SetNat44Forwarding(newConfig.Forwarding); err != nil {
return errors.Errorf("failed to set NAT44 forwarding to %t: %d", newConfig.Forwarding, err)
}
}
// Inside/outside interfaces
toSetIn, toSetOut, toUnsetIn, toUnsetOut := diffInterfaces(oldConfig.NatInterfaces, newConfig.NatInterfaces)
if err := c.disableNatInterfaces(toUnsetIn); err != nil {
return err
}
if err := c.disableNatInterfaces(toUnsetOut); err != nil {
return err
}
if err := c.enableNatInterfaces(toSetIn); err != nil {
return err
}
if err := c.enableNatInterfaces(toSetOut); err != nil {
return err
}
// Address pool
toAdd, toRemove := diffAddressPools(oldConfig.AddressPools, newConfig.AddressPools)
if err := c.delAddressPool(toRemove); err != nil {
return err
}
if err := c.addAddressPool(toAdd); err != nil {
return err
}
// Virtual reassembly IPv4
if toConfigure := isVirtualReassModified(oldConfig.VirtualReassemblyIpv4, newConfig.VirtualReassemblyIpv4); toConfigure != nil {
if err := c.natHandler.SetVirtualReassemblyIPv4(toConfigure); err != nil {
return errors.Errorf("failed to set NAT virtual reassembly for IPv4: %v", err)
}
}
// Virtual reassembly IPv6
if toConfigure := isVirtualReassModified(oldConfig.VirtualReassemblyIpv6, newConfig.VirtualReassemblyIpv6); toConfigure != nil {
if err := c.natHandler.SetVirtualReassemblyIPv6(toConfigure); err != nil {
return errors.Errorf("failed to set NAT virtual reassembly for IPv6: %v", err)
}
}
c.log.Info("NAT global config modified")
return nil
}
// DeleteNatGlobalConfig removes common setup for all NAT use cases
func (c *NatConfigurator) DeleteNatGlobalConfig(config *nat.Nat44Global) (err error) {
// Remove global NAT config
c.globalNAT = nil
// Inside/outside interfaces
if len(config.NatInterfaces) > 0 {
if err := c.disableNatInterfaces(config.NatInterfaces); err != nil {
return err
}
}
// Address pools
if len(config.AddressPools) > 0 {
if err := c.delAddressPool(config.AddressPools); err != nil {
return err
}
}
// Reset virtual reassembly to default
if err := c.natHandler.SetVirtualReassemblyIPv4(getDefaultVr()); err != nil {
return errors.Errorf("failed to reset NAT virtual reassembly for IPv4 to default: %v", err)
}
if err := c.natHandler.SetVirtualReassemblyIPv6(getDefaultVr()); err != nil {
return errors.Errorf("failed to reset NAT virtual reassembly for IPv4 to default: %v", err)
}
c.log.Info("NAT global config removed")
return nil
}
// ConfigureSNat configures new SNAT setup
func (c *NatConfigurator) ConfigureSNat(sNat *nat.Nat44SNat_SNatConfig) error {
c.log.Warn("SNAT CREATE not implemented")
return nil
}
// ModifySNat modifies existing SNAT setup
func (c *NatConfigurator) ModifySNat(oldSNat, newSNat *nat.Nat44SNat_SNatConfig) error {
c.log.Warn("SNAT MODIFY not implemented")
return nil
}
// DeleteSNat removes existing SNAT setup
func (c *NatConfigurator) DeleteSNat(sNat *nat.Nat44SNat_SNatConfig) error {
c.log.Warn("SNAT DELETE not implemented")
return nil
}
// ConfigureDNat configures new DNAT setup
func (c *NatConfigurator) ConfigureDNat(dNat *nat.Nat44DNat_DNatConfig) error {
// Resolve static mapping
if err := c.configureStaticMappings(dNat.Label, dNat.StMappings); err != nil {
return err
}
// Resolve identity mapping
if err := c.configureIdentityMappings(dNat.Label, dNat.IdMappings); err != nil {
return err
}
// Register DNAT configuration
c.dNatIndexes.RegisterName(dNat.Label, c.natIndexSeq, nil)
c.natIndexSeq++
c.log.Debugf("DNAT configuration registered (label: %v)", dNat.Label)
c.log.Infof("DNAT %s configured", dNat.Label)
return nil
}
// ModifyDNat modifies existing DNAT setup
func (c *NatConfigurator) ModifyDNat(oldDNat, newDNat *nat.Nat44DNat_DNatConfig) error {
// Static mappings
stmToAdd, stmToRemove := c.diffStatic(oldDNat.StMappings, newDNat.StMappings)
if err := c.unconfigureStaticMappings(stmToRemove); err != nil {
return err
}
if err := c.configureStaticMappings(newDNat.Label, stmToAdd); err != nil {
return err
}
// Identity mappings
idToAdd, idToRemove := c.diffIdentity(oldDNat.IdMappings, newDNat.IdMappings)
if err := c.unconfigureIdentityMappings(idToRemove); err != nil {
return err
}
if err := c.configureIdentityMappings(newDNat.Label, idToAdd); err != nil {
return err
}
c.log.Infof("DNAT %s modification done", newDNat.Label)
return nil
}
// DeleteDNat removes existing DNAT setup
func (c *NatConfigurator) DeleteDNat(dNat *nat.Nat44DNat_DNatConfig) error {
// In delete case, vpp-agent attempts to reconstruct every static mapping entry and remove it from the VPP
if err := c.unconfigureStaticMappings(dNat.StMappings); err != nil {
return err
}
// Do the same also for identity apping
if err := c.unconfigureIdentityMappings(dNat.IdMappings); err != nil {
return err
}
// Unregister DNAT configuration
c.dNatIndexes.UnregisterName(dNat.Label)
c.log.Debugf("DNAT configuration unregistered (label: %v)", dNat.Label)
c.log.Infof("DNAT %v removed", dNat.Label)
return nil
}
// ResolveCreatedInterface looks for cache of interfaces which should be enabled or disabled
// for NAT
func (c *NatConfigurator) ResolveCreatedInterface(ifName string, ifIdx uint32) error {
// Check for interfaces which should be enabled
var enabledIf []*nat.Nat44Global_NatInterface
for cachedName, data := range c.notEnabledIfs {
if cachedName == ifName {
delete(c.notEnabledIfs, cachedName)
c.log.Debugf("interface %s removed from not-enabled-for-NAT cache", ifName)
if err := c.enableNatInterfaces(append(enabledIf, data)); err != nil {
return errors.Errorf("failed to enable cached interface %s for NAT: %v", ifName, err)
}
}
}
// Check for interfaces which could be disabled
var disabledIf []*nat.Nat44Global_NatInterface
for cachedName, data := range c.notDisabledIfs {
if cachedName == ifName {
delete(c.notDisabledIfs, cachedName)
c.log.Debugf("interface %s removed from not-disabled-for-NAT cache", ifName)
if err := c.disableNatInterfaces(append(disabledIf, data)); err != nil {
return errors.Errorf("failed to disable cached interface %s for NAT: %v", ifName, err)
}
}
}
return nil
}
// ResolveDeletedInterface handles removed interface from NAT perspective
func (c *NatConfigurator) ResolveDeletedInterface(ifName string, ifIdx uint32) error {
// Check global NAT for interfaces
if c.globalNAT != nil {
for _, natIf := range c.globalNAT.NatInterfaces {
if natIf.Name == ifName {
// This interface was removed and it is not possible to determine its state, so agent handles it as
// not enabled
c.notEnabledIfs[natIf.Name] = natIf
c.log.Debugf("unregistered interface %s added to not-enabled-for-NAT cache", ifName)
return nil
}
}
}
return nil
}
// DumpNatGlobal returns the current NAT44 global config
func (c *NatConfigurator) DumpNatGlobal() (*nat.Nat44Global, error) {
return c.natHandler.Nat44GlobalConfigDump()
}
// DumpNatDNat returns the current NAT44 DNAT config
func (c *NatConfigurator) DumpNatDNat() (*nat.Nat44DNat, error) {
return c.natHandler.Nat44DNatDump()
}
// enables set of interfaces as inside/outside in NAT
func (c *NatConfigurator) enableNatInterfaces(natInterfaces []*nat.Nat44Global_NatInterface) error {
for _, natInterface := range natInterfaces {
ifIdx, _, found := c.ifIndexes.LookupIdx(natInterface.Name)
if !found {
c.notEnabledIfs[natInterface.Name] = natInterface // cache interface
c.log.Debugf("Interface %s missing, cannot enable it for NAT yet, cached", natInterface.Name)
} else {
if natInterface.OutputFeature {
// enable nat interface and output feature
if err := c.natHandler.EnableNat44InterfaceOutput(ifIdx, natInterface.IsInside); err != nil {
return errors.Errorf("failed to enable interface %s for NAT44 as output feature: %v",
natInterface.Name, err)
}
} else {
// enable interface only
if err := c.natHandler.EnableNat44Interface(ifIdx, natInterface.IsInside); err != nil {
return errors.Errorf("failed to enable interface %s for NAT44: %v", natInterface.Name, err)
}
}
}
}
return nil
}
// disables set of interfaces in NAT
func (c *NatConfigurator) disableNatInterfaces(natInterfaces []*nat.Nat44Global_NatInterface) error {
for _, natInterface := range natInterfaces {
// Check if interface is not in the cache
for ifName := range c.notEnabledIfs {
if ifName == natInterface.Name {
delete(c.notEnabledIfs, ifName)
}
}
// Check if interface exists
ifIdx, _, found := c.ifIndexes.LookupIdx(natInterface.Name)
if !found {
c.notDisabledIfs[natInterface.Name] = natInterface // cache interface
c.log.Debugf("Interface %s missing, cannot disable it for NAT yet, cached", natInterface.Name)
} else {
if natInterface.OutputFeature {
// disable nat interface and output feature
if err := c.natHandler.DisableNat44InterfaceOutput(ifIdx, natInterface.IsInside); err != nil {
return errors.Errorf("failed to disable NAT44 interface %s as output feature: %v",
natInterface.Name, err)
}
} else {
// disable interface
if err := c.natHandler.DisableNat44Interface(ifIdx, natInterface.IsInside); err != nil {
return errors.Errorf("failed to disable NAT44 interface %s: %v", natInterface.Name, err)
}
}
}
}
return nil
}
// Configures NAT address pool. If an address pool cannot is invalid and cannot be configured, it is skipped.
func (c *NatConfigurator) addAddressPool(addressPools []*nat.Nat44Global_AddressPool) (err error) {
for _, addressPool := range addressPools {
if addressPool.FirstSrcAddress == "" && addressPool.LastSrcAddress == "" {
return errors.Errorf("failed to add address pool: invalid config, no IP address provided")
}
var firstIP []byte
var lastIP []byte
if addressPool.FirstSrcAddress != "" {
firstIP = net.ParseIP(addressPool.FirstSrcAddress).To4()
if firstIP == nil {
return errors.Errorf("failed to add address pool: unable to parse IP address %s",
addressPool.FirstSrcAddress)
}
}
if addressPool.LastSrcAddress != "" {
lastIP = net.ParseIP(addressPool.LastSrcAddress).To4()
if lastIP == nil {
return errors.Errorf("failed to add address pool: unable to parse IP address %s",
addressPool.LastSrcAddress)
}
}
// Both fields have to be set, at least at the same value if only one of them is set
if firstIP == nil {
firstIP = lastIP
} else if lastIP == nil {
lastIP = firstIP // Matthew 20:16
}
if err = c.natHandler.AddNat44AddressPool(firstIP, lastIP, addressPool.VrfId, addressPool.TwiceNat); err != nil {
return errors.Errorf("failed to add NAT44 address pool %s - %s: %v", firstIP, lastIP, err)
}
}
return nil
}
// Removes NAT address pool. Invalid address pool configuration is skipped with warning, configurator assumes that
// such a data could not be configured to the vpp.
func (c *NatConfigurator) delAddressPool(addressPools []*nat.Nat44Global_AddressPool) error {
for _, addressPool := range addressPools {
if addressPool.FirstSrcAddress == "" && addressPool.LastSrcAddress == "" {
// No address pool to remove
continue
}
var firstIP []byte
var lastIP []byte
if addressPool.FirstSrcAddress != "" {
firstIP = net.ParseIP(addressPool.FirstSrcAddress).To4()
if firstIP == nil {
// Do not return error here
c.log.Warnf("First NAT44 address pool IP %s cannot be parsed and removed, skipping",
addressPool.FirstSrcAddress)
continue
}
}
if addressPool.LastSrcAddress != "" {
lastIP = net.ParseIP(addressPool.LastSrcAddress).To4()
if lastIP == nil {
// Do not return error here
c.log.Warnf("Last NAT44 address pool IP %s cannot be parsed and removed, skipping",
addressPool.LastSrcAddress)
continue
}
}
// Both fields have to be set, at least at the same value if only one of them is set
if firstIP == nil {
firstIP = lastIP
} else if lastIP == nil {
lastIP = firstIP
}
// remove address pool
if err := c.natHandler.DelNat44AddressPool(firstIP, lastIP, addressPool.VrfId, addressPool.TwiceNat); err != nil {
errors.Errorf("failed to delete NAT44 address pool %s - %s: %v", firstIP, lastIP, err)
}
}
return nil
}
// configures a list of static mappings for provided label
func (c *NatConfigurator) configureStaticMappings(label string, mappings []*nat.Nat44DNat_DNatConfig_StaticMapping) error {
for _, mappingEntry := range mappings {
localIPList := mappingEntry.LocalIps
if len(localIPList) == 0 {
return errors.Errorf("cannot configure DNAT static mapping %s: no local address provided", label)
} else if len(localIPList) == 1 {
// Case without load balance (one local address)
if err := c.handleStaticMapping(mappingEntry, label, true); err != nil {
return err
}
} else {
// Case with load balance (more local addresses)
if err := c.handleStaticMappingLb(mappingEntry, label, true); err != nil {
return err
}
}
// Register DNAT static mapping
mappingIdentifier := GetStMappingIdentifier(mappingEntry)
c.dNatStMappingIndexes.RegisterName(mappingIdentifier, c.natIndexSeq, nil)
c.natIndexSeq++
c.log.Debugf("DNAT static (lb) mapping registered (ID: %s, Tag: %s)", mappingIdentifier, label)
}
return nil
}
// removes static mappings from configuration with provided label
func (c *NatConfigurator) unconfigureStaticMappings(mappings []*nat.Nat44DNat_DNatConfig_StaticMapping) error {
for mappingIdx, mappingEntry := range mappings {
localIPList := mappingEntry.LocalIps
if len(localIPList) == 0 {
c.log.Warnf("DNAT mapping %s has not local IPs, cannot remove it", mappingIdx)
continue
} else if len(localIPList) == 1 {
// Case without load balance (one local address)
if err := c.handleStaticMapping(mappingEntry, dummyTag, false); err != nil {
return err
}
} else {
// Case with load balance (more local addresses)
if err := c.handleStaticMappingLb(mappingEntry, dummyTag, false); err != nil {
return err
}
}
// Unregister DNAT mapping
mappingIdentifier := GetStMappingIdentifier(mappingEntry)
c.dNatStMappingIndexes.UnregisterName(mappingIdentifier)
c.log.Debugf("DNAT lb-mapping unregistered (ID %v)", mappingIdentifier)
}
return nil
}
// configures single static mapping entry with load balancer
func (c *NatConfigurator) handleStaticMappingLb(staticMappingLb *nat.Nat44DNat_DNatConfig_StaticMapping, tag string, add bool) (err error) {
// Validate tag
if tag == dummyTag && add {
c.log.Warn("Static mapping will be configured with generic tag")
}
// Parse external IP address
exIPAddrByte := net.ParseIP(staticMappingLb.ExternalIp).To4()
if exIPAddrByte == nil {
return errors.Errorf("cannot configure DNAT lb static mapping: unable to parse external IP %s", exIPAddrByte.String())
}
// In this case, external port is required
if staticMappingLb.ExternalPort == 0 {
return errors.Errorf("cannot configure DNAT lb static mapping: external port is not set")
}
// Address mapping with load balancer
ctx := &vppcalls.StaticMappingLbContext{
Tag: tag,
ExternalIP: exIPAddrByte,
ExternalPort: uint16(staticMappingLb.ExternalPort),
Protocol: getProtocol(staticMappingLb.Protocol, c.log),
LocalIPs: getLocalIPs(staticMappingLb.LocalIps, c.log),
TwiceNat: staticMappingLb.TwiceNat == nat.TwiceNatMode_ENABLED,
SelfTwiceNat: staticMappingLb.TwiceNat == nat.TwiceNatMode_SELF,
}
if len(ctx.LocalIPs) == 0 {
return errors.Errorf("cannot configure DNAT mapping: no local IP was successfully parsed")
}
if add {
if err := c.natHandler.AddNat44StaticMappingLb(ctx); err != nil {
return errors.Errorf("failed to add NAT44 lb static mapping: %v", err)
}
} else {
if err := c.natHandler.DelNat44StaticMappingLb(ctx); err != nil {
return errors.Errorf("failed to delete NAT44 static mapping: %v", err)
}
}
return nil
}
// handler for single static mapping entry
func (c *NatConfigurator) handleStaticMapping(staticMapping *nat.Nat44DNat_DNatConfig_StaticMapping, tag string, add bool) (err error) {
var ifIdx uint32 = 0xffffffff // default value - means no external interface is set
var exIPAddr net.IP
// Validate tag
if tag == dummyTag && add {
c.log.Warn("Static mapping will be configured with generic tag")
}
// Parse local IP address and port
lcIPAddr := net.ParseIP(staticMapping.LocalIps[0].LocalIp).To4()
lcPort := staticMapping.LocalIps[0].LocalPort
lcVrf := staticMapping.LocalIps[0].VrfId
if lcIPAddr == nil {
return errors.Errorf("cannot configure DNAT static mapping: unable to parse local IP %s", lcIPAddr.String())
}
// Check external interface (prioritized over external IP)
if staticMapping.ExternalInterface != "" {
// Check external interface
var found bool
ifIdx, _, found = c.ifIndexes.LookupIdx(staticMapping.ExternalInterface)
if !found {
return errors.Errorf("cannot configure DNAT static mapping: required external interface %s is missing",
staticMapping.ExternalInterface)
}
} else {
// Parse external IP address
exIPAddr = net.ParseIP(staticMapping.ExternalIp).To4()
if exIPAddr == nil {
return errors.Errorf("cannot configure DNAT static mapping: unable to parse external IP %s", exIPAddr.String())
}
}
// Resolve mapping (address only or address and port)
var addrOnly bool
if lcPort == 0 || staticMapping.ExternalPort == 0 {
addrOnly = true
}
// Address mapping with load balancer
ctx := &vppcalls.StaticMappingContext{
Tag: tag,
AddressOnly: addrOnly,
LocalIP: lcIPAddr,
LocalPort: uint16(lcPort),
ExternalIP: exIPAddr,
ExternalPort: uint16(staticMapping.ExternalPort),
ExternalIfIdx: ifIdx,
Protocol: getProtocol(staticMapping.Protocol, c.log),
Vrf: lcVrf,
TwiceNat: staticMapping.TwiceNat == nat.TwiceNatMode_ENABLED,
SelfTwiceNat: staticMapping.TwiceNat == nat.TwiceNatMode_SELF,
}
if add {
if err := c.natHandler.AddNat44StaticMapping(ctx); err != nil {
return errors.Errorf("failed to add NAT44 static mapping: %v", err)
}
} else {
if err := c.natHandler.DelNat44StaticMapping(ctx); err != nil {
return errors.Errorf("failed to delete NAT44 static mapping: %v", err)
}
}
return nil
}
// configures a list of identity mappings with label
func (c *NatConfigurator) configureIdentityMappings(label string, mappings []*nat.Nat44DNat_DNatConfig_IdentityMapping) error {
for _, idMapping := range mappings {
if idMapping.IpAddress == "" && idMapping.AddressedInterface == "" {
return errors.Errorf("cannot configure DNAT %s identity mapping: no IP address or interface provided", label)
}
// Case without load balance (one local address)
if err := c.handleIdentityMapping(idMapping, label, true); err != nil {
return err
}
// Register DNAT identity mapping
mappingIdentifier := GetIDMappingIdentifier(idMapping)
c.dNatIDMappingIndexes.RegisterName(mappingIdentifier, c.natIndexSeq, nil)
c.natIndexSeq++
c.log.Debugf("DNAT identity mapping registered (ID: %s, Tag: %s)", mappingIdentifier, label)
}
return nil
}
// removes identity mappings from configuration with provided label
func (c *NatConfigurator) unconfigureIdentityMappings(mappings []*nat.Nat44DNat_DNatConfig_IdentityMapping) error {
var wasErr error
for mappingIdx, idMapping := range mappings {
if idMapping.IpAddress == "" && idMapping.AddressedInterface == "" {
return errors.Errorf("cannot configure DNAT identity mapping %d: no IP address or interface provided",
mappingIdx)
}
if err := c.handleIdentityMapping(idMapping, dummyTag, false); err != nil {
return err
}
// Unregister DNAT identity mapping
mappingIdentifier := GetIDMappingIdentifier(idMapping)
c.dNatIDMappingIndexes.UnregisterName(mappingIdentifier)
c.natIndexSeq++
c.log.Debugf("DNAT identity mapping unregistered (ID: %v)", mappingIdentifier)
}
return wasErr
}
// handler for single identity mapping entry
func (c *NatConfigurator) handleIdentityMapping(idMapping *nat.Nat44DNat_DNatConfig_IdentityMapping, tag string, isAdd bool) (err error) {
// Verify interface if exists
var ifIdx uint32
if idMapping.AddressedInterface != "" {
var found bool
ifIdx, _, found = c.ifIndexes.LookupIdx(idMapping.AddressedInterface)
if !found {
// TODO: use cache to configure later
return errors.Errorf("failed to configure identity mapping: provided interface %s does not exist",
idMapping.AddressedInterface)
}
}
// Identity mapping (common fields)
ctx := &vppcalls.IdentityMappingContext{
Tag: tag,
Protocol: getProtocol(idMapping.Protocol, c.log),
Port: uint16(idMapping.Port),
IfIdx: ifIdx,
Vrf: idMapping.VrfId,
}
if ctx.IfIdx == 0 {
// Case with IP (optionally port). Verify and parse input IP/port
parsedIP := net.ParseIP(idMapping.IpAddress).To4()
if parsedIP == nil {
return errors.Errorf("failed to configure identity mapping: unable to parse IP address %s", idMapping.IpAddress)
}
// Add IP address to context
ctx.IPAddress = parsedIP
}
// Configure/remove identity mapping
if isAdd {
if err := c.natHandler.AddNat44IdentityMapping(ctx); err != nil {
return errors.Errorf("failed to add NAT44 identity mapping: %v", err)
}
} else {
if err := c.natHandler.DelNat44IdentityMapping(ctx); err != nil {
return errors.Errorf("failed to remove NAT44 identity mapping: %v", err)
}
}
return nil
}
// looks for new and obsolete IN interfaces
func diffInterfaces(oldIfs, newIfs []*nat.Nat44Global_NatInterface) (toSetIn, toSetOut, toUnsetIn, toUnsetOut []*nat.Nat44Global_NatInterface) {
// Find new interfaces
for _, newIf := range newIfs {
var found bool
for _, oldIf := range oldIfs {
if newIf.Name == oldIf.Name && newIf.IsInside == oldIf.IsInside && newIf.OutputFeature == oldIf.OutputFeature {
found = true
break
}
}
if !found {
if newIf.IsInside {
toSetIn = append(toSetIn, newIf)
} else {
toSetOut = append(toSetOut, newIf)
}
}
}
// Find obsolete interfaces
for _, oldIf := range oldIfs {
var found bool
for _, newIf := range newIfs {
if oldIf.Name == newIf.Name && oldIf.IsInside == newIf.IsInside && oldIf.OutputFeature == newIf.OutputFeature {
found = true
break
}
}
if !found {
if oldIf.IsInside {
toUnsetIn = append(toUnsetIn, oldIf)
} else {
toUnsetOut = append(toUnsetOut, oldIf)
}
}
}
return
}
// looks for new and obsolete address pools
func diffAddressPools(oldAPs, newAPs []*nat.Nat44Global_AddressPool) (toAdd, toRemove []*nat.Nat44Global_AddressPool) {
// Find new address pools
for _, newAp := range newAPs {
// If new address pool is a range, add it
if newAp.LastSrcAddress != "" {
toAdd = append(toAdd, newAp)
continue
}
// Otherwise try to find the same address pool
var found bool
for _, oldAp := range oldAPs {
// Skip address pools
if oldAp.LastSrcAddress != "" {
continue
}
if newAp.FirstSrcAddress == oldAp.FirstSrcAddress && newAp.TwiceNat == oldAp.TwiceNat && newAp.VrfId == oldAp.VrfId {
found = true
}
}
if !found {
toAdd = append(toAdd, newAp)
}
}
// Find obsolete address pools
for _, oldAp := range oldAPs {
// If new address pool is a range, remove it
if oldAp.LastSrcAddress != "" {
toRemove = append(toRemove, oldAp)
continue
}
// Otherwise try to find the same address pool
var found bool
for _, newAp := range newAPs {
// Skip address pools (they are already added)
if oldAp.LastSrcAddress != "" {
continue
}
if oldAp.FirstSrcAddress == newAp.FirstSrcAddress && oldAp.TwiceNat == newAp.TwiceNat && oldAp.VrfId == newAp.VrfId {
found = true
}
}
if !found {
toRemove = append(toRemove, oldAp)
}
}
return
}
// returns a list of static mappings to add/remove
func (c *NatConfigurator) diffStatic(oldMappings, newMappings []*nat.Nat44DNat_DNatConfig_StaticMapping) (toAdd, toRemove []*nat.Nat44DNat_DNatConfig_StaticMapping) {
// Find missing mappings
for _, newMap := range newMappings {
var found bool
for _, oldMap := range oldMappings {
// VRF, protocol and twice map
if newMap.Protocol != oldMap.Protocol || newMap.TwiceNat != oldMap.TwiceNat {
continue
}
// External interface, IP and port
if newMap.ExternalInterface != oldMap.ExternalInterface || newMap.ExternalIp != oldMap.ExternalIp ||
newMap.ExternalPort != oldMap.ExternalPort {
continue
}
// Local IPs
if !c.compareLocalIPs(oldMap.LocalIps, newMap.LocalIps) {
continue
}
found = true
}
if !found {
toAdd = append(toAdd, newMap)
}
}
// Find obsolete mappings
for _, oldMap := range oldMappings {
var found bool
for _, newMap := range newMappings {
// VRF, protocol and twice map
if newMap.Protocol != oldMap.Protocol || newMap.TwiceNat != oldMap.TwiceNat {
continue
}
// External interface, IP and port
if newMap.ExternalInterface != oldMap.ExternalInterface || newMap.ExternalIp != oldMap.ExternalIp ||
newMap.ExternalPort != oldMap.ExternalPort {
continue
}
// Local IPs
if !c.compareLocalIPs(oldMap.LocalIps, newMap.LocalIps) {
continue
}
found = true
}
if !found {
toRemove = append(toRemove, oldMap)
}
}
return
}
// returns a list of identity mappings to add/remove
func (c *NatConfigurator) diffIdentity(oldMappings, newMappings []*nat.Nat44DNat_DNatConfig_IdentityMapping) (toAdd, toRemove []*nat.Nat44DNat_DNatConfig_IdentityMapping) {
// Find missing mappings
for _, newMap := range newMappings {
var found bool
for _, oldMap := range oldMappings {
// VRF and protocol
if newMap.VrfId != oldMap.VrfId || newMap.Protocol != oldMap.Protocol {
continue
}
// Addressed interface, IP address and port
if newMap.AddressedInterface != oldMap.AddressedInterface || newMap.IpAddress != oldMap.IpAddress ||
newMap.Port != oldMap.Port {
continue
}
found = true
}
if !found {
toAdd = append(toAdd, newMap)