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
|
package acl
import (
"bufio"
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"slices"
"sort"
"strings"
"sync"
incus "github.com/lxc/incus/v6/client"
internalInstance "github.com/lxc/incus/v6/internal/instance"
"github.com/lxc/incus/v6/internal/server/cluster"
"github.com/lxc/incus/v6/internal/server/cluster/request"
"github.com/lxc/incus/v6/internal/server/db"
dbCluster "github.com/lxc/incus/v6/internal/server/db/cluster"
"github.com/lxc/incus/v6/internal/server/state"
localUtil "github.com/lxc/incus/v6/internal/server/util"
"github.com/lxc/incus/v6/internal/version"
"github.com/lxc/incus/v6/shared/api"
"github.com/lxc/incus/v6/shared/logger"
"github.com/lxc/incus/v6/shared/revert"
"github.com/lxc/incus/v6/shared/util"
"github.com/lxc/incus/v6/shared/validate"
)
// Define type for rule directions.
type ruleDirection string
const (
ruleDirectionIngress ruleDirection = "ingress"
ruleDirectionEgress ruleDirection = "egress"
)
// ReservedNetworkSubects contains a list of reserved network peer names (those starting with @ character) that
// cannot be used when to name peering connections. Otherwise peer connections wouldn't be able to be referenced
// in ACL rules using the "@<peer name>" format without the potential of conflicts.
var ReservedNetworkSubects = []string{"internal", "external"}
// Define reserved ACL subjects.
const (
ruleSubjectInternal = "@internal"
ruleSubjectExternal = "@external"
)
// Define aliases for reserved ACL subjects. This is to allow earlier deprecated names that used the "#" prefix.
// They were deprecated to avoid confusion with YAML comments. So "#internal" and "#external" should not be used.
var (
ruleSubjectInternalAliases = []string{ruleSubjectInternal, "#internal"}
ruleSubjectExternalAliases = []string{ruleSubjectExternal, "#external"}
)
// ValidActions defines valid actions for rules.
var ValidActions = []string{"allow", "allow-stateless", "drop", "reject"}
// common represents a Network ACL.
type common struct {
logger logger.Logger
state *state.State
id int64
projectName string
info *api.NetworkACL
}
// init initialize internal variables.
func (d *common) init(state *state.State, id int64, projectName string, info *api.NetworkACL) {
if info == nil {
d.info = &api.NetworkACL{}
} else {
d.info = info
}
d.logger = logger.AddContext(logger.Ctx{"project": projectName, "networkACL": d.info.Name})
d.id = id
d.projectName = projectName
d.state = state
if d.info.Ingress == nil {
d.info.Ingress = []api.NetworkACLRule{}
}
for i := range d.info.Ingress {
d.info.Ingress[i].Normalise()
}
if d.info.Egress == nil {
d.info.Egress = []api.NetworkACLRule{}
}
for i := range d.info.Egress {
d.info.Egress[i].Normalise()
}
if d.info.Config == nil {
d.info.Config = make(map[string]string)
}
}
// ID returns the Network ACL ID.
func (d *common) ID() int64 {
return d.id
}
// Project returns the project name.
func (d *common) Project() string {
return d.projectName
}
// Info returns copy of internal info for the Network ACL.
func (d *common) Info() *api.NetworkACL {
// Copy internal info to prevent modification externally.
info := api.NetworkACL{}
info.Name = d.info.Name
info.Description = d.info.Description
info.Ingress = append(make([]api.NetworkACLRule, 0, len(d.info.Ingress)), d.info.Ingress...)
info.Egress = append(make([]api.NetworkACLRule, 0, len(d.info.Egress)), d.info.Egress...)
info.Config = localUtil.CopyConfig(d.info.Config)
info.UsedBy = nil // To indicate its not populated (use Usedby() function to populate).
info.Project = d.projectName
return &info
}
// usedBy returns a list of API endpoints referencing this ACL.
// If firstOnly is true then search stops at first result.
func (d *common) usedBy(firstOnly bool) ([]string, error) {
usedBy := []string{}
// Find all networks, profiles and instance NICs that use this Network ACL.
err := UsedBy(d.state, d.projectName, func(ctx context.Context, tx *db.ClusterTx, _ []string, usageType any, _ string, _ map[string]string) error {
switch u := usageType.(type) {
case db.InstanceArgs:
uri := fmt.Sprintf("/%s/instances/%s", version.APIVersion, u.Name)
if u.Project != api.ProjectDefaultName {
uri += fmt.Sprintf("?project=%s", u.Project)
}
usedBy = append(usedBy, uri)
case *api.Network:
uri := fmt.Sprintf("/%s/networks/%s", version.APIVersion, u.Name)
if d.projectName != api.ProjectDefaultName {
uri += fmt.Sprintf("?project=%s", d.projectName)
}
usedBy = append(usedBy, uri)
case dbCluster.Profile:
uri := fmt.Sprintf("/%s/profiles/%s", version.APIVersion, u.Name)
if u.Project != api.ProjectDefaultName {
uri += fmt.Sprintf("?project=%s", u.Project)
}
usedBy = append(usedBy, uri)
case *api.NetworkACL:
uri := fmt.Sprintf("/%s/network-acls/%s", version.APIVersion, u.Name)
if d.projectName != api.ProjectDefaultName {
uri += fmt.Sprintf("?project=%s", d.projectName)
}
usedBy = append(usedBy, uri)
default:
return fmt.Errorf("Unrecognised usage type %T", u)
}
if firstOnly {
return db.ErrInstanceListStop
}
return nil
}, d.Info().Name)
if err != nil {
if errors.Is(err, db.ErrInstanceListStop) {
return usedBy, nil
}
return nil, fmt.Errorf("Failed getting ACL usage: %w", err)
}
return usedBy, nil
}
// UsedBy returns a list of API endpoints referencing this ACL.
func (d *common) UsedBy() ([]string, error) {
return d.usedBy(false)
}
// isUsed returns whether or not the ACL is in use.
func (d *common) isUsed() (bool, error) {
usedBy, err := d.usedBy(true)
if err != nil {
return false, err
}
return len(usedBy) > 0, nil
}
// Etag returns the values used for etag generation.
func (d *common) Etag() []any {
return []any{d.info.Name, d.info.Description, d.info.Ingress, d.info.Egress, d.info.Config}
}
// validateName checks name is valid.
func (d *common) validateName(name string) error {
return ValidName(name)
}
// validateConfig checks the config and rules are valid.
func (d *common) validateConfig(info *api.NetworkACLPut) error {
err := d.validateConfigMap(info.Config, nil)
if err != nil {
return err
}
// Normalise rules before validation for duplicate detection.
for i := range info.Ingress {
info.Ingress[i].Normalise()
}
for i := range info.Egress {
info.Egress[i].Normalise()
}
// Validate each ingress rule.
for i, ingressRule := range info.Ingress {
err := d.validateRule(ruleDirectionIngress, ingressRule)
if err != nil {
return fmt.Errorf("Invalid ingress rule %d: %w", i, err)
}
// Check for duplicates.
for ri, r := range info.Ingress {
if ri == i {
continue // Skip ourselves.
}
if r == ingressRule {
return fmt.Errorf("Duplicate of ingress rule %d", i)
}
}
}
// Validate each egress rule.
for i, egressRule := range info.Egress {
err := d.validateRule(ruleDirectionEgress, egressRule)
if err != nil {
return fmt.Errorf("Invalid egress rule %d: %w", i, err)
}
// Check for duplicates.
for ri, r := range info.Egress {
if ri == i {
continue // Skip ourselves.
}
if r == egressRule {
return fmt.Errorf("Duplicate of egress rule %d", i)
}
}
}
return nil
}
// validateConfigMap checks ACL config map against rules.
func (d *common) validateConfigMap(config map[string]string, rules map[string]func(value string) error) error {
checkedFields := map[string]struct{}{}
// Run the validator against each field.
for k, validator := range rules {
checkedFields[k] = struct{}{} // Mark field as checked.
err := validator(config[k])
if err != nil {
return fmt.Errorf("Invalid value for config option %q: %w", k, err)
}
}
// Look for any unchecked fields, as these are unknown fields and validation should fail.
for k := range config {
_, checked := checkedFields[k]
if checked {
continue
}
// User keys are not validated.
if internalInstance.IsUserConfig(k) {
continue
}
return fmt.Errorf("Invalid config option %q", k)
}
return nil
}
// validateRule validates the rule supplied.
func (d *common) validateRule(direction ruleDirection, rule api.NetworkACLRule) error {
// Validate Action field (required).
if !slices.Contains(ValidActions, rule.Action) {
return fmt.Errorf("Action must be one of: %s", strings.Join(ValidActions, ", "))
}
// Validate State field (required).
validStates := []string{"enabled", "disabled", "logged"}
if !slices.Contains(validStates, rule.State) {
return fmt.Errorf("State must be one of: %s", strings.Join(validStates, ", "))
}
var acls map[string]int64
err := d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// Get map of ACL names to DB IDs (used for generating OVN port group names).
dbAcls, err := dbCluster.GetNetworkACLs(ctx, tx.Tx(), dbCluster.NetworkACLFilter{Project: &d.projectName})
if err != nil {
return err
}
acls = make(map[string]int64, len(dbAcls))
for _, acl := range dbAcls {
acls[acl.Name] = int64(acl.ID)
}
return nil
})
if err != nil {
return fmt.Errorf("Failed getting network ACLs for security ACL subject validation: %w", err)
}
validSubjectNames := make([]string, 0, len(acls)+len(ruleSubjectInternalAliases)+len(ruleSubjectExternalAliases))
validSubjectNames = append(validSubjectNames, ruleSubjectInternalAliases...)
validSubjectNames = append(validSubjectNames, ruleSubjectExternalAliases...)
for aclName := range acls {
validSubjectNames = append(validSubjectNames, aclName)
}
var srcHasName, srcHasIPv4, srcHasIPv6 bool
var dstHasName, dstHasIPv4, dstHasIPv6 bool
// Validate Source field.
if rule.Source != "" {
srcHasName, srcHasIPv4, srcHasIPv6, err = d.validateRuleSubjects("Source", direction, util.SplitNTrimSpace(rule.Source, ",", -1, false), validSubjectNames)
if err != nil {
return fmt.Errorf("Invalid Source: %w", err)
}
}
// Validate Destination field.
if rule.Destination != "" {
dstHasName, dstHasIPv4, dstHasIPv6, err = d.validateRuleSubjects("Destination", direction, util.SplitNTrimSpace(rule.Destination, ",", -1, false), validSubjectNames)
if err != nil {
return fmt.Errorf("Invalid Destination: %w", err)
}
}
// Check combination of subject types is valid for source/destination.
if rule.Source != "" && rule.Destination != "" {
if (srcHasIPv4 && !dstHasIPv4 && !dstHasName) ||
(dstHasIPv4 && !srcHasIPv4 && !srcHasName) ||
(srcHasIPv6 && !dstHasIPv6 && !dstHasName) ||
(dstHasIPv6 && !srcHasIPv6 && !srcHasName) {
return errors.New("Conflicting IP family types used for Source and Destination")
}
}
// Validate Protocol field.
if rule.Protocol != "" {
validProtocols := []string{"icmp4", "icmp6", "tcp", "udp"}
if !slices.Contains(validProtocols, rule.Protocol) {
return fmt.Errorf("Protocol must be one of: %s", strings.Join(validProtocols, ", "))
}
}
// Validate protocol dependent fields.
if slices.Contains([]string{"tcp", "udp"}, rule.Protocol) {
if rule.ICMPType != "" {
return errors.New("ICMP type cannot be used with non-ICMP protocol")
}
if rule.ICMPCode != "" {
return errors.New("ICMP code cannot be used with non-ICMP protocol")
}
// Validate SourcePort field.
if rule.SourcePort != "" {
err := d.validatePorts(util.SplitNTrimSpace(rule.SourcePort, ",", -1, false))
if err != nil {
return fmt.Errorf("Invalid Source port: %w", err)
}
}
// Validate DestinationPort field.
if rule.DestinationPort != "" {
err := d.validatePorts(util.SplitNTrimSpace(rule.DestinationPort, ",", -1, false))
if err != nil {
return fmt.Errorf("Invalid Destination port: %w", err)
}
}
} else if slices.Contains([]string{"icmp4", "icmp6"}, rule.Protocol) {
if rule.SourcePort != "" {
return fmt.Errorf("Source port cannot be used with %q protocol", rule.Protocol)
}
if rule.DestinationPort != "" {
return fmt.Errorf("Destination port cannot be used with %q protocol", rule.Protocol)
}
if rule.Protocol == "icmp4" {
if srcHasIPv6 {
return fmt.Errorf("Cannot use IPv6 source addresses with %q protocol", rule.Protocol)
}
if dstHasIPv6 {
return fmt.Errorf("Cannot use IPv6 destination addresses with %q protocol", rule.Protocol)
}
} else if rule.Protocol == "icmp6" {
if srcHasIPv4 {
return fmt.Errorf("Cannot use IPv4 source addresses with %q protocol", rule.Protocol)
}
if dstHasIPv4 {
return fmt.Errorf("Cannot use IPv4 destination addresses with %q protocol", rule.Protocol)
}
}
// Validate ICMPType field.
if rule.ICMPType != "" {
err := validate.IsUint8(rule.ICMPType)
if err != nil {
return fmt.Errorf("Invalid ICMP type: %w", err)
}
}
// Validate ICMPCode field.
if rule.ICMPCode != "" {
err := validate.IsUint8(rule.ICMPCode)
if err != nil {
return fmt.Errorf("Invalid ICMP code: %w", err)
}
}
} else {
if rule.ICMPType != "" {
return errors.New("ICMP type cannot be used without specifying protocol")
}
if rule.ICMPCode != "" {
return errors.New("ICMP code cannot be used without specifying protocol")
}
if rule.SourcePort != "" {
return errors.New("Source port cannot be used without specifying protocol")
}
if rule.DestinationPort != "" {
return errors.New("Destination port cannot be used without specifying protocol")
}
}
return nil
}
// validateRuleSubjects checks that the source or destination subjects for a rule are valid.
// Accepts a validSubjectNames list of valid ACL or special classifier names.
// Returns whether the subjects include names, IPv4 and IPv6 addresses respectively.
func (d *common) validateRuleSubjects(fieldName string, direction ruleDirection, subjects []string, validSubjectNames []string) (bool, bool, bool, error) {
// Check if named subjects are allowed in field/direction combination.
allowSubjectNames := false
if (fieldName == "Source" && direction == ruleDirectionIngress) || (fieldName == "Destination" && direction == ruleDirectionEgress) {
allowSubjectNames = true
}
isNetworkAddress := func(value string) (uint, error) {
ip := net.ParseIP(value)
if ip == nil {
return 0, fmt.Errorf("Not an IP address %q", value)
}
var ipVersion uint = 4
if ip.To4() == nil {
ipVersion = 6
}
return ipVersion, nil
}
isNetworkAddressCIDR := func(value string) (uint, error) {
ip, _, err := net.ParseCIDR(value)
if err != nil {
return 0, err
}
var ipVersion uint = 4
if ip.To4() == nil {
ipVersion = 6
}
return ipVersion, nil
}
isNetworkRange := func(value string) (uint, error) {
err := validate.IsNetworkRange(value)
if err != nil {
return 0, err
}
ips := strings.SplitN(value, "-", 2)
if len(ips) != 2 {
return 0, errors.New("IP range must contain start and end IP addresses")
}
ip := net.ParseIP(ips[0])
var ipVersion uint = 4
if ip.To4() == nil {
ipVersion = 6
}
return ipVersion, nil
}
checks := []func(s string) (uint, error){
isNetworkAddress,
isNetworkAddressCIDR,
isNetworkRange,
}
validSubject := func(subject string) (uint, error) {
// Check if it is one of the network IP types.
for _, c := range checks {
ipVersion, err := c(subject)
if err == nil {
return ipVersion, nil // Found valid subject.
}
}
// Check if it is one of the valid subject names.
for _, n := range validSubjectNames {
if subject == n {
if allowSubjectNames {
return 0, nil // Found valid subject.
}
return 0, fmt.Errorf("Named subjects not allowed in %q for %q rules", fieldName, direction)
}
}
// Check if it looks like a network peer connection name.
if strings.HasPrefix(subject, "@") {
if allowSubjectNames {
return 0, nil // Found valid subject.
}
return 0, fmt.Errorf("Named subjects not allowed in %q for %q rules", fieldName, direction)
}
return 0, fmt.Errorf("Invalid subject %q", subject)
}
hasIPv4 := false
hasIPv6 := false
hasName := false
for _, s := range subjects {
ipVersion, err := validSubject(s)
if err != nil {
return false, false, false, err
}
switch ipVersion {
case 0:
hasName = true
case 4:
hasIPv4 = true
case 6:
hasIPv6 = true
}
}
return hasName, hasIPv4, hasIPv6, nil
}
// validatePorts checks that the source or destination ports for a rule are valid.
func (d *common) validatePorts(ports []string) error {
for _, port := range ports {
err := validate.IsNetworkPortRange(port)
if err != nil {
return err
}
}
return nil
}
// Update applies the supplied config to the ACL.
func (d *common) Update(config *api.NetworkACLPut, clientType request.ClientType) error {
// Validate the configuration.
err := d.validateConfig(config)
if err != nil {
return err
}
reverter := revert.New()
defer reverter.Fail()
if clientType == request.ClientTypeNormal {
oldConfig := d.info.NetworkACLPut
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Update database. Its important this occurs before we attempt to apply to networks using the ACL
// as usage functions will inspect the database.
return dbCluster.UpdateNetworkACLAPI(ctx, tx.Tx(), d.id, config)
})
if err != nil {
return err
}
// Apply changes internally and reinitialize.
d.info.NetworkACLPut = *config
d.init(d.state, d.id, d.projectName, d.info)
reverter.Add(func() {
_ = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return dbCluster.UpdateNetworkACLAPI(ctx, tx.Tx(), d.id, &oldConfig)
})
d.info.NetworkACLPut = oldConfig
d.init(d.state, d.id, d.projectName, d.info)
})
}
// Get a list of networks that are using this ACL (either directly or indirectly via a NIC).
aclNets := map[string]NetworkACLUsage{}
err = NetworkUsage(d.state, d.projectName, []string{d.info.Name}, aclNets)
if err != nil {
return fmt.Errorf("Failed getting ACL network usage: %w", err)
}
// Separate out OVN networks from non-OVN networks. This is because OVN networks share ACL config, and
// so changes are not applied entirely on a per-network basis and need to be treated differently.
// Separate the bridge networks used indirectly by NIC devices. This is because the ACL rules need to be
// applied to the bridge interface, not the network.
aclOVNNets := map[string]NetworkACLUsage{}
aclBridgeNICs := map[string]NetworkACLUsage{}
for k, v := range aclNets {
if v.Type == "ovn" {
delete(aclNets, k)
aclOVNNets[k] = v
} else if v.Type == "bridge" && v.DeviceName != "" {
delete(aclNets, k)
aclBridgeNICs[k] = v
} else if v.Type != "bridge" {
return fmt.Errorf("Unsupported network ACL type %q", v.Type)
}
}
// Apply ACL changes to non-OVN networks on this member.
for _, aclNet := range aclNets {
err = FirewallApplyACLRules(d.state, d.logger, d.projectName, aclNet)
if err != nil {
return err
}
}
// If there are affected bridge NICs, apply the ACL changes to the bridge interface filter.
if len(aclBridgeNICs) > 0 {
err := BridgeUpdateACLs(d.state, d.logger, d.projectName, aclBridgeNICs)
if err != nil {
return fmt.Errorf("Failed updating bridge NIC ACL: %w", err)
}
}
// If there are affected OVN networks, then apply the changes, but only if the request type is normal.
// This way we won't apply the same changes multiple times for each cluster member.
if len(aclOVNNets) > 0 && clientType == request.ClientTypeNormal {
// Check that OVN is available.
ovnnb, _, err := d.state.OVN()
if err != nil {
return err
}
var aclNameIDs map[string]int64
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Get map of ACL names to DB IDs (used for generating OVN port group names).
acls, err := dbCluster.GetNetworkACLs(ctx, tx.Tx(), dbCluster.NetworkACLFilter{Project: &d.projectName})
if err != nil {
return err
}
aclNameIDs = make(map[string]int64, len(acls))
for _, acl := range acls {
aclNameIDs[acl.Name] = int64(acl.ID)
}
return nil
})
if err != nil {
return fmt.Errorf("Failed getting network ACL IDs for security ACL update: %w", err)
}
// Request that the ACL and any referenced ACLs in the ruleset are created in OVN.
// Pass aclOVNNets info, because although OVN networks share ACL port group definitions, when the
// ACL rules themselves use network specific selectors such as @internal/@external, we then need to
// apply those rules to each network affected by the ACL, so pass the full list of OVN networks
// affected by this ACL (either because the ACL is assigned directly or because it is assigned to
// an OVN NIC in an instance or profile).
cleanup, err := OVNEnsureACLs(d.state, d.logger, ovnnb, d.projectName, aclNameIDs, aclOVNNets, []string{d.info.Name}, true)
if err != nil {
return fmt.Errorf("Failed ensuring ACL is configured in OVN: %w", err)
}
reverter.Add(cleanup)
// Run unused port group cleanup in case any formerly referenced ACL in this ACL's rules means that
// an ACL port group is now considered unused.
err = OVNPortGroupDeleteIfUnused(d.state, d.logger, ovnnb, d.projectName, nil, "", d.info.Name)
if err != nil {
return fmt.Errorf("Failed removing unused OVN port groups: %w", err)
}
}
// Apply ACL changes to non-OVN networks on cluster members.
if clientType == request.ClientTypeNormal && len(aclNets) > 0 {
// Notify all other nodes to update the network if no target specified.
notifier, err := cluster.NewNotifier(d.state, d.state.Endpoints.NetworkCert(), d.state.ServerCert(), cluster.NotifyAll)
if err != nil {
return err
}
err = notifier(func(client incus.InstanceServer) error {
return client.UseProject(d.projectName).UpdateNetworkACL(d.info.Name, d.info.NetworkACLPut, "")
})
if err != nil {
return err
}
}
reverter.Success()
return nil
}
// Rename renames the ACL if not in use.
func (d *common) Rename(newName string) error {
_, err := LoadByName(d.state, d.projectName, newName)
if err == nil {
return errors.New("An ACL by that name exists already")
}
isUsed, err := d.isUsed()
if err != nil {
return err
}
if isUsed {
return errors.New("Cannot rename an ACL that is in use")
}
err = d.validateName(newName)
if err != nil {
return err
}
err = d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
idInt := int(d.id)
acls, err := dbCluster.GetNetworkACLs(ctx, tx.Tx(), dbCluster.NetworkACLFilter{ID: &idInt})
if err != nil {
return err
}
if len(acls) == 0 {
return api.StatusErrorf(http.StatusNotFound, "Network ACL not found")
}
return dbCluster.RenameNetworkACL(ctx, tx.Tx(), acls[0].Project, acls[0].Name, newName)
})
if err != nil {
return err
}
// Apply changes internally.
d.info.Name = newName
return nil
}
// Delete deletes the ACL.
func (d *common) Delete() error {
isUsed, err := d.isUsed()
if err != nil {
return err
}
if isUsed {
return errors.New("Cannot delete an ACL that is in use")
}
return d.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return dbCluster.DeleteNetworkACL(ctx, tx.Tx(), int(d.id))
})
}
// GetLog gets the ACL log.
func (d *common) GetLog(clientType request.ClientType) (string, error) {
// ACLs aren't specific to a particular network type but the log only works with OVN.
logPath := "/var/log/ovn/ovn-controller.log"
if !util.PathExists(logPath) {
return "", errors.New("Only OVN log entries may be retrieved at this time")
}
// Open the log file.
logFile, err := os.Open(logPath)
if err != nil {
return "", fmt.Errorf("Couldn't open OVN log file: %w", err)
}
defer func() { _ = logFile.Close() }()
logEntries := []string{}
scanner := bufio.NewScanner(logFile)
for scanner.Scan() {
logEntry := ovnParseLogEntry(scanner.Text(), fmt.Sprintf("incus_acl%d-", d.id))
if logEntry == "" {
continue
}
logEntries = append(logEntries, logEntry)
}
err = scanner.Err()
if err != nil {
return "", fmt.Errorf("Failed to read OVN log file: %w", err)
}
// Aggregates the entries from the rest of the cluster.
if clientType == request.ClientTypeNormal {
// Setup notifier to reach the rest of the cluster.
notifier, err := cluster.NewNotifier(d.state, d.state.Endpoints.NetworkCert(), d.state.ServerCert(), cluster.NotifyAll)
if err != nil {
return "", err
}
mu := sync.Mutex{}
err = notifier(func(client incus.InstanceServer) error {
// Get the entries.
entries, err := client.UseProject(d.projectName).GetNetworkACLLogfile(d.info.Name)
if err != nil {
return err
}
defer func() { _ = entries.Close() }()
// Prevent concurrent writes to the log entries slice.
mu.Lock()
defer mu.Unlock()
// Parse the response and add to the slice.
scanner := bufio.NewScanner(entries)
for scanner.Scan() {
entry := scanner.Text()
if entry == "" {
continue
}
logEntries = append(logEntries, entry)
}
err = scanner.Err()
if err != nil {
return fmt.Errorf("Failed to read OVN log file: %w", err)
}
return nil
})
if err != nil {
return "", err
}
}
// Just return empty if no log entries (no need for trailing line break).
if len(logEntries) == 0 {
return "", nil
}
// Sort the entries (by timestamp).
sort.Strings(logEntries)
return strings.Join(logEntries, "\n") + "\n", nil
}
|