/
nic_bridged.go
1762 lines (1459 loc) · 57.6 KB
/
nic_bridged.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
package device
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"math/rand"
"net"
"net/http"
"os"
"slices"
"strconv"
"strings"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/mdlayher/netx/eui64"
"github.com/lxc/incus/internal/revert"
"github.com/lxc/incus/internal/server/db"
"github.com/lxc/incus/internal/server/db/cluster"
deviceConfig "github.com/lxc/incus/internal/server/device/config"
"github.com/lxc/incus/internal/server/dnsmasq"
"github.com/lxc/incus/internal/server/dnsmasq/dhcpalloc"
"github.com/lxc/incus/internal/server/instance"
"github.com/lxc/incus/internal/server/instance/instancetype"
"github.com/lxc/incus/internal/server/ip"
"github.com/lxc/incus/internal/server/network"
"github.com/lxc/incus/internal/server/network/ovs"
"github.com/lxc/incus/internal/server/resources"
localUtil "github.com/lxc/incus/internal/server/util"
internalUtil "github.com/lxc/incus/internal/util"
"github.com/lxc/incus/shared/api"
"github.com/lxc/incus/shared/logger"
"github.com/lxc/incus/shared/util"
"github.com/lxc/incus/shared/validate"
)
type bridgeNetwork interface {
UsesDNSMasq() bool
}
type nicBridged struct {
deviceCommon
network network.Network // Populated in validateConfig().
}
// CanHotPlug returns whether the device can be managed whilst the instance is running. Returns true.
func (d *nicBridged) CanHotPlug() bool {
return true
}
// CanMigrate returns whether the device can be migrated to any other cluster member.
func (d *nicBridged) CanMigrate() bool {
return d.network != nil
}
// validateConfig checks the supplied config for correctness.
func (d *nicBridged) validateConfig(instConf instance.ConfigReader) error {
if !instanceSupported(instConf.Type(), instancetype.Container, instancetype.VM) {
return ErrUnsupportedDevType
}
var requiredFields []string
optionalFields := []string{
"name",
"network",
"parent",
"mtu",
"queue.tx.length",
"hwaddr",
"host_name",
"limits.ingress",
"limits.egress",
"limits.max",
"limits.priority",
"ipv4.address",
"ipv6.address",
"ipv4.routes",
"ipv6.routes",
"ipv4.routes.external",
"ipv6.routes.external",
"security.mac_filtering",
"security.ipv4_filtering",
"security.ipv6_filtering",
"security.port_isolation",
"boot.priority",
"vlan",
}
// checkWithManagedNetwork validates the device's settings against the managed network.
checkWithManagedNetwork := func(n network.Network) error {
if n.Status() != api.NetworkStatusCreated {
return fmt.Errorf("Specified network is not fully created")
}
if n.Type() != "bridge" {
return fmt.Errorf("Specified network must be of type bridge")
}
netConfig := n.Config()
if d.config["ipv4.address"] != "" {
dhcpv4Subnet := n.DHCPv4Subnet()
// Check that DHCPv4 is enabled on parent network (needed to use static assigned IPs) when
// IP filtering isn't enabled (if it is we allow the use of static IPs for this purpose).
if dhcpv4Subnet == nil && util.IsFalseOrEmpty(d.config["security.ipv4_filtering"]) {
return fmt.Errorf(`Cannot specify "ipv4.address" when DHCP is disabled (unless using security.ipv4_filtering) on network %q`, n.Name())
}
// Check the static IP supplied is valid for the linked network. It should be part of the
// network's subnet, but not necessarily part of the dynamic allocation ranges.
if dhcpv4Subnet != nil && d.config["ipv4.address"] != "none" && !dhcpalloc.DHCPValidIP(dhcpv4Subnet, nil, net.ParseIP(d.config["ipv4.address"])) {
return fmt.Errorf("Device IP address %q not within network %q subnet", d.config["ipv4.address"], n.Name())
}
parentAddress := netConfig["ipv4.address"]
if slices.Contains([]string{"", "none"}, parentAddress) {
return nil
}
ip, _, err := net.ParseCIDR(parentAddress)
if err != nil {
return fmt.Errorf("Invalid network ipv4.address: %w", err)
}
if d.config["ipv4.address"] == "none" && util.IsFalseOrEmpty(d.config["security.ipv4_filtering"]) {
return fmt.Errorf("Cannot have ipv4.address as none unless using security.ipv4_filtering")
}
// IP should not be the same as the parent managed network address.
if ip.Equal(net.ParseIP(d.config["ipv4.address"])) {
return fmt.Errorf("IP address %q is assigned to parent managed network device %q", d.config["ipv4.address"], d.config["parent"])
}
}
if d.config["ipv6.address"] != "" {
dhcpv6Subnet := n.DHCPv6Subnet()
// Check that DHCPv6 is enabled on parent network (needed to use static assigned IPs) when
// IP filtering isn't enabled (if it is we allow the use of static IPs for this purpose).
if (dhcpv6Subnet == nil || util.IsFalseOrEmpty(netConfig["ipv6.dhcp.stateful"])) && util.IsFalseOrEmpty(d.config["security.ipv6_filtering"]) {
return fmt.Errorf(`Cannot specify "ipv6.address" when DHCP or "ipv6.dhcp.stateful" are disabled (unless using security.ipv6_filtering) on network %q`, n.Name())
}
// Check the static IP supplied is valid for the linked network. It should be part of the
// network's subnet, but not necessarily part of the dynamic allocation ranges.
if dhcpv6Subnet != nil && d.config["ipv6.address"] != "none" && !dhcpalloc.DHCPValidIP(dhcpv6Subnet, nil, net.ParseIP(d.config["ipv6.address"])) {
return fmt.Errorf("Device IP address %q not within network %q subnet", d.config["ipv6.address"], n.Name())
}
parentAddress := netConfig["ipv6.address"]
if slices.Contains([]string{"", "none"}, parentAddress) {
return nil
}
ip, _, err := net.ParseCIDR(parentAddress)
if err != nil {
return fmt.Errorf("Invalid network ipv6.address: %w", err)
}
if d.config["ipv6.address"] == "none" && util.IsFalseOrEmpty(d.config["security.ipv6_filtering"]) {
return fmt.Errorf("Cannot have ipv6.address as none unless using security.ipv6_filtering")
}
// IP should not be the same as the parent managed network address.
if ip.Equal(net.ParseIP(d.config["ipv6.address"])) {
return fmt.Errorf("IP address %q is assigned to parent managed network device %q", d.config["ipv6.address"], d.config["parent"])
}
}
// When we know the parent network is managed, we can validate the NIC's VLAN settings based on
// on the bridge driver type.
if slices.Contains([]string{"", "native"}, netConfig["bridge.driver"]) {
// Check VLAN 0 isn't set when using a native Linux managed bridge, as not supported.
if d.config["vlan"] == "0" {
return fmt.Errorf("VLAN ID 0 is not allowed for native Linux bridges")
}
// Check that none of the supplied VLAN IDs are VLAN 0 when using a native Linux managed
// bridge, as not supported.
networkVLANList, err := networkVLANListExpand(util.SplitNTrimSpace(d.config["vlan.tagged"], ",", -1, true))
if err != nil {
return err
}
for _, vlanID := range networkVLANList {
if vlanID == 0 {
return fmt.Errorf("VLAN tagged ID 0 is not allowed for native Linux bridges")
}
}
}
return nil
}
// Check that if network proeperty is set that conflicting keys are not present.
if d.config["network"] != "" {
requiredFields = append(requiredFields, "network")
bannedKeys := []string{"nictype", "parent", "mtu"}
for _, bannedKey := range bannedKeys {
if d.config[bannedKey] != "" {
return fmt.Errorf("Cannot use %q property in conjunction with %q property", bannedKey, "network")
}
}
// Load managed network. api.ProjectDefaultName is used here as bridge networks don't support projects.
var err error
d.network, err = network.LoadByName(d.state, api.ProjectDefaultName, d.config["network"])
if err != nil {
return fmt.Errorf("Error loading network config for %q: %w", d.config["network"], err)
}
// Validate NIC settings with managed network.
err = checkWithManagedNetwork(d.network)
if err != nil {
return err
}
// Apply network settings to NIC.
netConfig := d.network.Config()
// Link device to network bridge.
d.config["parent"] = d.config["network"]
// Apply network level config options to device config before validation.
if netConfig["bridge.mtu"] != "" {
d.config["mtu"] = netConfig["bridge.mtu"]
}
} else {
// If no network property supplied, then parent property is required.
requiredFields = append(requiredFields, "parent")
// Check if parent is a managed network.
// api.ProjectDefaultName is used here as bridge networks don't support projects.
d.network, _ = network.LoadByName(d.state, api.ProjectDefaultName, d.config["parent"])
if d.network != nil {
// Validate NIC settings with managed network.
err := checkWithManagedNetwork(d.network)
if err != nil {
return err
}
} else {
// Check that static IPs are only specified with IP filtering when using an unmanaged
// parent bridge.
if util.IsTrue(d.config["security.ipv4_filtering"]) {
if d.config["ipv4.address"] == "" {
return fmt.Errorf("IPv4 filtering requires a manually specified ipv4.address when using an unmanaged parent bridge")
}
} else if d.config["ipv4.address"] != "" {
// Static IP cannot be used with unmanaged parent.
return fmt.Errorf("Cannot use manually specified ipv4.address when using unmanaged parent bridge")
}
if util.IsTrue(d.config["security.ipv6_filtering"]) {
if d.config["ipv6.address"] == "" {
return fmt.Errorf("IPv6 filtering requires a manually specified ipv6.address when using an unmanaged parent bridge")
}
} else if d.config["ipv6.address"] != "" {
// Static IP cannot be used with unmanaged parent.
return fmt.Errorf("Cannot use manually specified ipv6.address when using unmanaged parent bridge")
}
}
}
// Check that IP filtering isn't being used with VLAN filtering.
if util.IsTrue(d.config["security.ipv4_filtering"]) || util.IsTrue(d.config["security.ipv6_filtering"]) {
if d.config["vlan"] != "" || d.config["vlan.tagged"] != "" {
return fmt.Errorf("IP filtering cannot be used with VLAN filtering")
}
}
// Check there isn't another NIC with any of the same addresses specified on the same cluster member.
// Can only validate this when the instance is supplied (and not doing profile validation).
if d.inst != nil {
err := d.checkAddressConflict()
if err != nil {
return err
}
}
rules := nicValidationRules(requiredFields, optionalFields, instConf)
// Add bridge specific vlan validation.
rules["vlan"] = func(value string) error {
if value == "" || value == "none" {
return nil
}
return validate.IsNetworkVLAN(value)
}
// Add bridge specific vlan.tagged validation.
rules["vlan.tagged"] = func(value string) error {
if value == "" {
return nil
}
// Check that none of the supplied VLAN IDs are the same as the untagged VLAN ID.
for _, vlanID := range util.SplitNTrimSpace(value, ",", -1, true) {
if vlanID == d.config["vlan"] {
return fmt.Errorf("Tagged VLAN ID %q cannot be the same as untagged VLAN ID", vlanID)
}
_, _, err := validate.ParseNetworkVLANRange(vlanID)
if err != nil {
return err
}
}
return nil
}
// Add bridge specific ipv4/ipv6 validation rules
rules["ipv4.address"] = func(value string) error {
if value == "" || value == "none" {
return nil
}
return validate.IsNetworkAddressV4(value)
}
rules["ipv6.address"] = func(value string) error {
if value == "" || value == "none" {
return nil
}
return validate.IsNetworkAddressV6(value)
}
// Now run normal validation.
err := d.config.Validate(rules)
if err != nil {
return err
}
return nil
}
// checkAddressConflict checks for conflicting IP/MAC addresses on another NIC connected to same network on the
// same cluster member. Can only validate this when the instance is supplied (and not doing profile validation).
// Returns api.StatusError with status code set to http.StatusConflict if conflicting address found.
func (d *nicBridged) checkAddressConflict() error {
node := d.inst.Location()
ourNICIPs := make(map[string]net.IP, 2)
ourNICIPs["ipv4.address"] = net.ParseIP(d.config["ipv4.address"])
ourNICIPs["ipv6.address"] = net.ParseIP(d.config["ipv6.address"])
ourNICMAC, _ := net.ParseMAC(d.config["hwaddr"])
if ourNICMAC == nil {
ourNICMAC, _ = net.ParseMAC(d.volatileGet()["hwaddr"])
}
// Check if any instance devices use this network.
// Managed bridge networks have a per-server DHCP daemon so perform a node level search.
filter := cluster.InstanceFilter{Node: &node}
// Set network name for comparison (needs to support connecting to unmanaged networks).
networkName := d.config["parent"]
if d.network != nil {
networkName = d.network.Name()
}
// Bridge networks are always in the default project.
return network.UsedByInstanceDevices(d.state, api.ProjectDefaultName, networkName, "bridge", func(inst db.InstanceArgs, nicName string, nicConfig map[string]string) error {
// Skip our own device. This avoids triggering duplicate device errors during
// updates or when making temporary copies of our instance during migrations.
sameLogicalInstance := instance.IsSameLogicalInstance(d.inst, &inst)
if sameLogicalInstance && d.Name() == nicName {
return nil
}
// Skip NICs connected to other VLANs (not perfect though as one NIC could
// explicitly specify the default untagged VLAN and these would be connected to
// same L2 even though the values are different, and there is a different default
// value for native and openvswith parent bridges).
if d.config["vlan"] != nicConfig["vlan"] {
return nil
}
// Check there isn't another instance with the same DNS name connected to a managed network
// that has DNS enabled and is connected to the same untagged VLAN.
if d.network != nil && d.network.Config()["dns.mode"] != "none" && nicCheckDNSNameConflict(d.inst.Name(), inst.Name) {
if sameLogicalInstance {
return api.StatusErrorf(http.StatusConflict, "Instance DNS name %q conflict between %q and %q because both are connected to same network", strings.ToLower(inst.Name), d.name, nicName)
}
return api.StatusErrorf(http.StatusConflict, "Instance DNS name %q already used on network", strings.ToLower(inst.Name))
}
// Check NIC's MAC address doesn't match this NIC's MAC address.
devNICMAC, _ := net.ParseMAC(nicConfig["hwaddr"])
if devNICMAC == nil {
devNICMAC, _ = net.ParseMAC(inst.Config[fmt.Sprintf("volatile.%s.hwaddr", nicName)])
}
if ourNICMAC != nil && devNICMAC != nil && bytes.Equal(ourNICMAC, devNICMAC) {
return api.StatusErrorf(http.StatusConflict, "MAC address %q already defined on another NIC", devNICMAC.String())
}
// Check NIC's static IPs don't match this NIC's static IPs.
for _, key := range []string{"ipv4.address", "ipv6.address"} {
if d.config[key] == "" {
continue // No static IP specified on this NIC.
}
// Parse IPs to avoid being tripped up by presentation differences.
devNICIP := net.ParseIP(nicConfig[key])
if ourNICIPs[key] != nil && devNICIP != nil && ourNICIPs[key].Equal(devNICIP) {
return api.StatusErrorf(http.StatusConflict, "IP address %q already defined on another NIC", devNICIP.String())
}
}
return nil
}, filter)
}
// validateEnvironment checks the runtime environment for correctness.
func (d *nicBridged) validateEnvironment() error {
if d.inst.Type() == instancetype.Container && d.config["name"] == "" {
return fmt.Errorf("Requires name property to start")
}
if !util.PathExists(fmt.Sprintf("/sys/class/net/%s", d.config["parent"])) {
return fmt.Errorf("Parent device %q doesn't exist", d.config["parent"])
}
return nil
}
// UpdatableFields returns a list of fields that can be updated without triggering a device remove & add.
func (d *nicBridged) UpdatableFields(oldDevice Type) []string {
// Check old and new device types match.
_, match := oldDevice.(*nicBridged)
if !match {
return []string{}
}
return []string{"limits.ingress", "limits.egress", "limits.max", "limits.priority", "ipv4.routes", "ipv6.routes", "ipv4.routes.external", "ipv6.routes.external", "ipv4.address", "ipv6.address", "security.mac_filtering", "security.ipv4_filtering", "security.ipv6_filtering"}
}
// Add is run when a device is added to a non-snapshot instance whether or not the instance is running.
func (d *nicBridged) Add() error {
networkVethFillFromVolatile(d.config, d.volatileGet())
// Rebuild dnsmasq entry if needed and reload.
err := d.rebuildDnsmasqEntry()
if err != nil {
return err
}
return nil
}
// PreStartCheck checks the managed parent network is available (if relevant).
func (d *nicBridged) PreStartCheck() error {
// Non-managed network NICs are not relevant for checking managed network availability.
if d.network == nil {
return nil
}
// If managed network is not available, don't try and start instance.
if d.network.LocalStatus() == api.NetworkStatusUnavailable {
return api.StatusErrorf(http.StatusServiceUnavailable, "Network %q unavailable on this server", d.network.Name())
}
return nil
}
// Start is run when the device is added to a running instance or instance is starting up.
func (d *nicBridged) Start() (*deviceConfig.RunConfig, error) {
err := d.validateEnvironment()
if err != nil {
return nil, err
}
revert := revert.New()
defer revert.Fail()
saveData := make(map[string]string)
saveData["host_name"] = d.config["host_name"]
var peerName string
var mtu uint32
// Create veth pair and configure the peer end with custom hwaddr and mtu if supplied.
if d.inst.Type() == instancetype.Container {
if saveData["host_name"] == "" {
saveData["host_name"], err = d.generateHostName("veth", d.config["hwaddr"])
if err != nil {
return nil, err
}
}
peerName, mtu, err = networkCreateVethPair(saveData["host_name"], d.config)
} else if d.inst.Type() == instancetype.VM {
if saveData["host_name"] == "" {
saveData["host_name"], err = d.generateHostName("tap", d.config["hwaddr"])
if err != nil {
return nil, err
}
}
peerName = saveData["host_name"] // VMs use the host_name to link to the TAP FD.
mtu, err = networkCreateTap(saveData["host_name"], d.config)
}
if err != nil {
return nil, err
}
revert.Add(func() { _ = network.InterfaceRemove(saveData["host_name"]) })
// Populate device config with volatile fields if needed.
networkVethFillFromVolatile(d.config, saveData)
// Rebuild dnsmasq config if parent is a managed bridge network using dnsmasq and static lease file is
// missing.
bridgeNet, ok := d.network.(bridgeNetwork)
if ok && d.network.IsManaged() && bridgeNet.UsesDNSMasq() {
deviceStaticFileName := dnsmasq.DHCPStaticAllocationPath(d.network.Name(), dnsmasq.StaticAllocationFileName(d.inst.Project().Name, d.inst.Name(), d.Name()))
if !util.PathExists(deviceStaticFileName) {
err = d.rebuildDnsmasqEntry()
if err != nil {
return nil, fmt.Errorf("Failed creating DHCP static allocation: %w", err)
}
}
}
// Apply host-side routes to bridge interface.
routes := []string{}
routes = append(routes, util.SplitNTrimSpace(d.config["ipv4.routes"], ",", -1, true)...)
routes = append(routes, util.SplitNTrimSpace(d.config["ipv6.routes"], ",", -1, true)...)
routes = append(routes, util.SplitNTrimSpace(d.config["ipv4.routes.external"], ",", -1, true)...)
routes = append(routes, util.SplitNTrimSpace(d.config["ipv6.routes.external"], ",", -1, true)...)
err = networkNICRouteAdd(d.config["parent"], routes...)
if err != nil {
return nil, err
}
// Apply host-side limits.
err = networkSetupHostVethLimits(&d.deviceCommon, nil, true)
if err != nil {
return nil, err
}
// Disable IPv6 on host-side veth interface (prevents host-side interface getting link-local address)
// which isn't needed because the host-side interface is connected to a bridge.
err = localUtil.SysctlSet(fmt.Sprintf("net/ipv6/conf/%s/disable_ipv6", saveData["host_name"]), "1")
if err != nil && !os.IsNotExist(err) {
return nil, err
}
// Apply and host-side network filters (uses enriched host_name from networkVethFillFromVolatile).
r, err := d.setupHostFilters(nil)
if err != nil {
return nil, err
}
revert.Add(r)
// Attach host side veth interface to bridge.
err = network.AttachInterface(d.config["parent"], saveData["host_name"])
if err != nil {
return nil, err
}
revert.Add(func() { _ = network.DetachInterface(d.config["parent"], saveData["host_name"]) })
// Attempt to disable router advertisement acceptance.
err = localUtil.SysctlSet(fmt.Sprintf("net/ipv6/conf/%s/accept_ra", saveData["host_name"]), "0")
if err != nil && !os.IsNotExist(err) {
return nil, err
}
// Attempt to enable port isolation.
if util.IsTrue(d.config["security.port_isolation"]) {
link := &ip.Link{Name: saveData["host_name"]}
err = link.BridgeLinkSetIsolated(true)
if err != nil {
return nil, err
}
}
// Detect bridge type.
nativeBridge := network.IsNativeBridge(d.config["parent"])
// Setup VLAN settings on bridge port.
if nativeBridge {
err = d.setupNativeBridgePortVLANs(saveData["host_name"])
} else {
err = d.setupOVSBridgePortVLANs(saveData["host_name"])
}
if err != nil {
return nil, err
}
// Check if hairpin mode needs to be enabled.
if nativeBridge && d.network != nil {
brNetfilterEnabled := false
for _, ipVersion := range []uint{4, 6} {
if network.BridgeNetfilterEnabled(ipVersion) == nil {
brNetfilterEnabled = true
break
}
}
if brNetfilterEnabled {
var listenAddresses map[int64]string
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
listenAddresses, err = tx.GetNetworkForwardListenAddresses(ctx, d.network.ID(), true)
return err
})
if err != nil {
return nil, fmt.Errorf("Failed loading network forwards: %w", err)
}
// If br_netfilter is enabled and bridge has forwards, we enable hairpin mode on NIC's
// bridge port in case any of the forwards target this NIC and the instance attempts to
// connect to the forward's listener. Without hairpin mode on the target of the forward
// will not be able to connect to the listener.
if len(listenAddresses) > 0 {
link := &ip.Link{Name: saveData["host_name"]}
err = link.BridgeLinkSetHairpin(true)
if err != nil {
return nil, fmt.Errorf("Error enabling hairpin mode on bridge port %q: %w", link.Name, err)
}
d.logger.Debug("Enabled hairpin mode on NIC bridge port", logger.Ctx{"dev": link.Name})
}
}
}
err = d.volatileSet(saveData)
if err != nil {
return nil, err
}
runConf := deviceConfig.RunConfig{}
runConf.PostHooks = []func() error{d.postStart}
runConf.NetworkInterface = []deviceConfig.RunConfigItem{
{Key: "type", Value: "phys"},
{Key: "name", Value: d.config["name"]},
{Key: "flags", Value: "up"},
{Key: "link", Value: peerName},
{Key: "hwaddr", Value: d.config["hwaddr"]},
}
if d.inst.Type() == instancetype.VM {
runConf.NetworkInterface = append(runConf.NetworkInterface,
[]deviceConfig.RunConfigItem{
{Key: "devName", Value: d.name},
{Key: "mtu", Value: fmt.Sprintf("%d", mtu)},
}...)
}
revert.Success()
return &runConf, nil
}
// postStart is run after the device is added to the instance.
func (d *nicBridged) postStart() error {
err := bgpAddPrefix(&d.deviceCommon, d.network, d.config)
if err != nil {
return err
}
return nil
}
// Update applies configuration changes to a started device.
func (d *nicBridged) Update(oldDevices deviceConfig.Devices, isRunning bool) error {
oldConfig := oldDevices[d.name]
v := d.volatileGet()
// Populate device config with volatile fields if needed.
networkVethFillFromVolatile(d.config, v)
networkVethFillFromVolatile(oldConfig, v)
// If an IPv6 address has changed, flush all existing IPv6 leases for instance so instance
// isn't allocated old IP. This is important with IPv6 because DHCPv6 supports multiple IP
// address allocation and would result in instance having leases for both old and new IPs.
if d.config["hwaddr"] != "" && d.config["ipv6.address"] != oldConfig["ipv6.address"] {
err := d.networkClearLease(d.inst.Name(), d.config["parent"], d.config["hwaddr"], clearLeaseIPv6Only)
if err != nil {
return err
}
}
revert := revert.New()
defer revert.Fail()
// If instance is running, apply host side limits and filters first before rebuilding
// dnsmasq config below so that existing config can be used as part of the filter removal.
if isRunning {
err := d.validateEnvironment()
if err != nil {
return err
}
// Validate old config so that it is enriched with network parent config needed for route removal.
err = Validate(d.inst, d.state, d.name, oldConfig)
if err != nil {
return err
}
// Remove old host-side routes from bridge interface.
oldRoutes := []string{}
oldRoutes = append(oldRoutes, util.SplitNTrimSpace(oldConfig["ipv4.routes"], ",", -1, true)...)
oldRoutes = append(oldRoutes, util.SplitNTrimSpace(oldConfig["ipv6.routes"], ",", -1, true)...)
oldRoutes = append(oldRoutes, util.SplitNTrimSpace(oldConfig["ipv4.routes.external"], ",", -1, true)...)
oldRoutes = append(oldRoutes, util.SplitNTrimSpace(oldConfig["ipv6.routes.external"], ",", -1, true)...)
networkNICRouteDelete(oldConfig["parent"], oldRoutes...)
// Apply host-side routes to bridge interface.
routes := []string{}
routes = append(routes, util.SplitNTrimSpace(d.config["ipv4.routes"], ",", -1, true)...)
routes = append(routes, util.SplitNTrimSpace(d.config["ipv6.routes"], ",", -1, true)...)
routes = append(routes, util.SplitNTrimSpace(d.config["ipv4.routes.external"], ",", -1, true)...)
routes = append(routes, util.SplitNTrimSpace(d.config["ipv6.routes.external"], ",", -1, true)...)
err = networkNICRouteAdd(d.config["parent"], routes...)
if err != nil {
return err
}
// Apply host-side limits.
err = networkSetupHostVethLimits(&d.deviceCommon, oldConfig, true)
if err != nil {
return err
}
// Apply and host-side network filters (uses enriched host_name from networkVethFillFromVolatile).
r, err := d.setupHostFilters(oldConfig)
if err != nil {
return err
}
revert.Add(r)
}
// Rebuild dnsmasq entry if needed and reload.
err := d.rebuildDnsmasqEntry()
if err != nil {
return err
}
// If an IPv6 address has changed, if the instance is running we should bounce the host-side
// veth interface to give the instance a chance to detect the change and re-apply for an
// updated lease with new IP address.
if d.config["ipv6.address"] != oldConfig["ipv6.address"] && d.config["host_name"] != "" && util.PathExists(fmt.Sprintf("/sys/class/net/%s", d.config["host_name"])) {
link := &ip.Link{Name: d.config["host_name"]}
err := link.SetDown()
if err != nil {
return err
}
err = link.SetUp()
if err != nil {
return err
}
}
// If an external address changed, update the BGP advertisements.
err = bgpRemovePrefix(&d.deviceCommon, oldConfig)
if err != nil {
return err
}
err = bgpAddPrefix(&d.deviceCommon, d.network, d.config)
if err != nil {
return err
}
revert.Success()
return nil
}
// Stop is run when the device is removed from the instance.
func (d *nicBridged) Stop() (*deviceConfig.RunConfig, error) {
// Remove BGP announcements.
err := bgpRemovePrefix(&d.deviceCommon, d.config)
if err != nil {
return nil, err
}
// Populate device config with volatile fields (hwaddr and host_name) if needed.
networkVethFillFromVolatile(d.config, d.volatileGet())
err = networkClearHostVethLimits(&d.deviceCommon)
if err != nil {
return nil, err
}
// Setup post-stop actions.
runConf := deviceConfig.RunConfig{
PostHooks: []func() error{d.postStop},
}
return &runConf, nil
}
// postStop is run after the device is removed from the instance.
func (d *nicBridged) postStop() error {
defer func() {
_ = d.volatileSet(map[string]string{
"host_name": "",
})
}()
v := d.volatileGet()
networkVethFillFromVolatile(d.config, v)
if d.config["host_name"] != "" && network.InterfaceExists(d.config["host_name"]) {
// Detach host-side end of veth pair from bridge (required for openvswitch particularly).
err := network.DetachInterface(d.config["parent"], d.config["host_name"])
if err != nil {
return fmt.Errorf("Failed to detach interface %q from %q: %w", d.config["host_name"], d.config["parent"], err)
}
// Removing host-side end of veth pair will delete the peer end too.
err = network.InterfaceRemove(d.config["host_name"])
if err != nil {
return fmt.Errorf("Failed to remove interface %q: %w", d.config["host_name"], err)
}
}
// Remove host-side routes from bridge interface.
routes := []string{}
routes = append(routes, util.SplitNTrimSpace(d.config["ipv4.routes"], ",", -1, true)...)
routes = append(routes, util.SplitNTrimSpace(d.config["ipv6.routes"], ",", -1, true)...)
routes = append(routes, util.SplitNTrimSpace(d.config["ipv4.routes.external"], ",", -1, true)...)
routes = append(routes, util.SplitNTrimSpace(d.config["ipv6.routes.external"], ",", -1, true)...)
networkNICRouteDelete(d.config["parent"], routes...)
if util.IsTrue(d.config["security.mac_filtering"]) || util.IsTrue(d.config["security.ipv4_filtering"]) || util.IsTrue(d.config["security.ipv6_filtering"]) {
d.removeFilters(d.config)
}
return nil
}
// Remove is run when the device is removed from the instance or the instance is deleted.
func (d *nicBridged) Remove() error {
if d.config["parent"] != "" {
dnsmasq.ConfigMutex.Lock()
defer dnsmasq.ConfigMutex.Unlock()
if network.InterfaceExists(d.config["parent"]) {
err := d.networkClearLease(d.inst.Name(), d.config["parent"], d.config["hwaddr"], clearLeaseAll)
if err != nil {
return fmt.Errorf("Failed clearing leases: %w", err)
}
}
// Remove dnsmasq config if it exists (doesn't return error if file is missing).
err := dnsmasq.RemoveStaticEntry(d.config["parent"], d.inst.Project().Name, d.inst.Name(), d.Name())
if err != nil {
return err
}
// Reload dnsmasq to apply new settings if dnsmasq is running.
err = dnsmasq.Kill(d.config["parent"], true)
if err != nil {
return err
}
}
return nil
}
// rebuildDnsmasqEntry rebuilds the dnsmasq host entry if connected to a managed network and reloads dnsmasq.
func (d *nicBridged) rebuildDnsmasqEntry() error {
// Rebuild dnsmasq config if parent is a managed bridge network using dnsmasq.
bridgeNet, ok := d.network.(bridgeNetwork)
if !ok || !d.network.IsManaged() || !bridgeNet.UsesDNSMasq() {
return nil
}
dnsmasq.ConfigMutex.Lock()
defer dnsmasq.ConfigMutex.Unlock()
ipv4Address := d.config["ipv4.address"]
ipv6Address := d.config["ipv6.address"]
// If address is set to none treat it the same as not being specified
if ipv4Address == "none" {
ipv4Address = ""
}
if ipv6Address == "none" {
ipv6Address = ""
}
// If IP filtering is enabled, and no static IP in config, check if there is already a
// dynamically assigned static IP in dnsmasq config and write that back out in new config.
if (util.IsTrue(d.config["security.ipv4_filtering"]) && ipv4Address == "") || (util.IsTrue(d.config["security.ipv6_filtering"]) && ipv6Address == "") {
deviceStaticFileName := dnsmasq.StaticAllocationFileName(d.inst.Project().Name, d.inst.Name(), d.Name())
_, curIPv4, curIPv6, err := dnsmasq.DHCPStaticAllocation(d.config["parent"], deviceStaticFileName)
if err != nil && !os.IsNotExist(err) {
return err
}
if ipv4Address == "" && curIPv4.IP != nil {
ipv4Address = curIPv4.IP.String()
}
if ipv6Address == "" && curIPv6.IP != nil {
ipv6Address = curIPv6.IP.String()
}
}
err := dnsmasq.UpdateStaticEntry(d.config["parent"], d.inst.Project().Name, d.inst.Name(), d.Name(), d.network.Config(), d.config["hwaddr"], ipv4Address, ipv6Address)
if err != nil {
return err
}
// Reload dnsmasq to apply new settings.
err = dnsmasq.Kill(d.config["parent"], true)
if err != nil {
return err
}
return nil
}
// setupHostFilters applies any host side network filters.
// Returns a revert fail function that can be used to undo this function if a subsequent step fails.
func (d *nicBridged) setupHostFilters(oldConfig deviceConfig.Device) (revert.Hook, error) {
revert := revert.New()
defer revert.Fail()
// Check br_netfilter kernel module is loaded and enabled for IPv6 before clearing existing rules.
// We won't try to load it as its default mode can cause unwanted traffic blocking.
if util.IsTrue(d.config["security.ipv6_filtering"]) {
err := network.BridgeNetfilterEnabled(6)
if err != nil {
return nil, fmt.Errorf("security.ipv6_filtering requires bridge netfilter: %w", err)
}
}
// Remove any old network filters if non-empty oldConfig supplied as part of update.
if oldConfig != nil && (util.IsTrue(oldConfig["security.mac_filtering"]) || util.IsTrue(oldConfig["security.ipv4_filtering"]) || util.IsTrue(oldConfig["security.ipv6_filtering"])) {
d.removeFilters(oldConfig)
}
// Setup network filters.
if util.IsTrue(d.config["security.mac_filtering"]) || util.IsTrue(d.config["security.ipv4_filtering"]) || util.IsTrue(d.config["security.ipv6_filtering"]) {
err := d.setFilters()
if err != nil {
return nil, err
}
revert.Add(func() { d.removeFilters(d.config) })
}
cleanup := revert.Clone().Fail
revert.Success()
return cleanup, nil
}
// removeFilters removes any network level filters defined for the instance.
func (d *nicBridged) removeFilters(m deviceConfig.Device) {
if m["hwaddr"] == "" {
d.logger.Error("Failed to remove network filters: hwaddr not defined")
return
}
if m["host_name"] == "" {
d.logger.Error("Failed to remove network filters: host_name not defined")
return
}
IPv4Nets, IPv6Nets, err := allowedIPNets(m)
if err != nil {
d.logger.Error("Failed to calculate static IP network filters", logger.Ctx{"err": err})
return
}
// Remove filters for static MAC and IPs (if specified above).
// This covers the case when filtering is used with an unmanaged bridge.
d.logger.Debug("Clearing instance firewall static filters", logger.Ctx{"parent": m["parent"], "host_name": m["host_name"], "hwaddr": m["hwaddr"], "IPv4Nets": IPv4Nets, "IPv6Nets": IPv6Nets})
err = d.state.Firewall.InstanceClearBridgeFilter(d.inst.Project().Name, d.inst.Name(), d.name, m["parent"], m["host_name"], m["hwaddr"], IPv4Nets, IPv6Nets)
if err != nil {
d.logger.Error("Failed to remove static IP network filters", logger.Ctx{"err": err})
}
// If allowedIPNets returned nil for IPv4 or IPv6, it is possible that total protocol blocking was set up
// because the device has a managed parent network with DHCP disabled. Pass in empty slices to catch this case.