diff --git a/npc/controller.go b/npc/controller.go index 27dd1a15..eef4af7f 100644 --- a/npc/controller.go +++ b/npc/controller.go @@ -1,10 +1,9 @@ package npc import ( + "fmt" "sync" - goiptables "github.com/coreos/go-iptables/iptables" - "github.com/pkg/errors" coreapi "k8s.io/api/core/v1" extnapi "k8s.io/api/extensions/v1beta1" @@ -39,7 +38,7 @@ type controller struct { nss map[string]*ns // ns name -> ns struct nsSelectors *selectorSet // selector string -> nsSelector - defaultEgressDrop bool + defaultEgressDrop bool // flag to track if base iptable rule to drop egress traffic is added or not } func New(nodeName string, ipt iptables.Interface, ips ipset.Interface) NetworkPolicyController { @@ -126,15 +125,17 @@ func (npc *controller) AddNetworkPolicy(obj interface{}) error { // lazily add default rule to drop egress traffic only when network policies are applied if !npc.defaultEgressDrop { - npc.defaultEgressDrop = true - ipt, err := goiptables.New() + egressNetworkPolicy, err := isEgressNetworkPolicy(obj) if err != nil { - common.Log.Fatalf("Failed to create iptables handler %v", err.Error()) + return err } - if err := ipt.Append(TableFilter, EgressChain, - "-m", "mark", "!", "--mark", EgressMark, "-j", "DROP"); err != nil { - common.Log.Errorf("Failed to add iptable rule to drop egress traffic from the pods by default due to %s", err.Error()) - npc.defaultEgressDrop = false + if egressNetworkPolicy { + npc.defaultEgressDrop = true + if err := npc.ipt.Append(TableFilter, EgressChain, + "-m", "mark", "!", "--mark", EgressMark, "-j", "DROP"); err != nil { + npc.defaultEgressDrop = false + return fmt.Errorf("Failed to add iptable rule to drop egress traffic from the pods by default due to %s", err.Error()) + } } } @@ -218,3 +219,20 @@ func nsName(obj interface{}) (string, error) { return "", errInvalidNetworkPolicyObjType } + +func isEgressNetworkPolicy(obj interface{}) (bool, error) { + if policy, ok := obj.(*networkingv1.NetworkPolicy); ok { + if len(policy.Spec.PolicyTypes) > 0 { + for _, policyType := range policy.Spec.PolicyTypes { + if policyType == networkingv1.PolicyTypeEgress { + return true, nil + } + } + } + if policy.Spec.Egress != nil { + return true, nil + } + return false, nil + } + return false, errInvalidNetworkPolicyObjType +}