@@ -15,6 +15,7 @@ import (
15
15
const (
16
16
dnsPort = 53
17
17
networkAPIVersion = "networking.k8s.io/v1"
18
+ networkPolicyKind = "NetworkPolicy"
18
19
)
19
20
20
21
type deploymentConnectivity struct {
@@ -45,9 +46,44 @@ func (deployConn *deploymentConnectivity) addEgressRule(
45
46
deployConn .egressConns = append (deployConn .egressConns , rule )
46
47
}
47
48
48
- func synthNetpols (connections []* common.Connections ) []* network.NetworkPolicy {
49
+ // Generate a default-deny NetworkPolicy for the given namespace
50
+ func getNsDefaultDenyPolicy (namespace string ) * network.NetworkPolicy {
51
+ return & network.NetworkPolicy {
52
+ TypeMeta : metaV1.TypeMeta {
53
+ Kind : networkPolicyKind ,
54
+ APIVersion : networkAPIVersion ,
55
+ },
56
+ ObjectMeta : metaV1.ObjectMeta {
57
+ Name : "default-deny-in-namespace-" + namespace ,
58
+ Namespace : namespace ,
59
+ },
60
+ Spec : network.NetworkPolicySpec {
61
+ PodSelector : metaV1.LabelSelector {}, // select all pods in the namespace
62
+ Ingress : []network.NetworkPolicyIngressRule {}, // deny all ingress
63
+ Egress : []network.NetworkPolicyEgressRule {}, // deny all egress
64
+ PolicyTypes : []network.PolicyType {network .PolicyTypeIngress , network .PolicyTypeEgress },
65
+ },
66
+ }
67
+ }
68
+
69
+ // Generate default-deny NetworkPolicy for each namespace of the given resources
70
+ func getNsDefaultDenyPolicies (resources []common.Resource ) []* network.NetworkPolicy {
71
+ denyNetpols := []* network.NetworkPolicy {}
72
+ namespaces := map [string ]bool {}
73
+ for resIdx := range resources {
74
+ namespace := resources [resIdx ].Resource .Namespace
75
+ if _ , ok := namespaces [namespace ]; ! ok {
76
+ namespaces [namespace ] = true
77
+ denyNetpols = append (denyNetpols , getNsDefaultDenyPolicy (namespace ))
78
+ }
79
+ }
80
+ return denyNetpols
81
+ }
82
+
83
+ func synthNetpols (resources []common.Resource , connections []* common.Connections ) []* network.NetworkPolicy {
49
84
deployConnectivity := determineConnectivityPerDeployment (connections )
50
85
netpols := buildNetpolPerDeployment (deployConnectivity )
86
+ netpols = append (netpols , getNsDefaultDenyPolicies (resources )... )
51
87
return netpols
52
88
}
53
89
@@ -152,7 +188,7 @@ func buildNetpolPerDeployment(deployConnectivity []*deploymentConnectivity) []*n
152
188
}
153
189
netpol := network.NetworkPolicy {
154
190
TypeMeta : metaV1.TypeMeta {
155
- Kind : "NetworkPolicy" ,
191
+ Kind : networkPolicyKind ,
156
192
APIVersion : networkAPIVersion ,
157
193
},
158
194
ObjectMeta : metaV1.ObjectMeta {
0 commit comments