Debian Codegraph @

pkg/ip/ipmasq_nftables_linux.go

raw symbols SCIP
1 // Copyright 2023 CNI authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package ip
16
17 import (
18 "context"
19 "fmt"
20 "net"
21 "strings"
22
23 "sigs.k8s.io/knftables"
24
25 "github.com/containernetworking/cni/pkg/types"
26 "github.com/containernetworking/plugins/pkg/utils"
27 )
28
29 const (
30 ipMasqTableName = "cni_plugins_masquerade"
31 ipMasqChainName = "masq_checks"
32 )
33
34 // The nftables ipmasq implementation is mostly like the iptables implementation, with
35 // minor updates to fix a bug (adding `ifname`) and to allow future GC support.
36 //
37 // We add a rule for each mapping, with a comment containing a hash of its identifiers,
38 // so that we can later reliably delete the rules we want. (This is important because in
39 // edge cases, it's possible the plugin might see "ADD container A with IP 192.168.1.3",
40 // followed by "ADD container B with IP 192.168.1.3" followed by "DEL container A with IP
41 // 192.168.1.3", and we need to make sure that the DEL causes us to delete the rule for
42 // container A, and not the rule for container B.)
43 //
44 // It would be more nftables-y to have a chain with a single rule doing a lookup against a
45 // set with an element per mapping, rather than having a chain with a rule per mapping.
46 // But there's no easy, non-racy way to say "delete the element 192.168.1.3 from the set,
47 // but only if it was added for container A, not if it was added for container B".
48
49 // hashForNetwork returns a unique hash for this network
50 func hashForNetwork(network string) string {
51 return utils.MustFormatHashWithPrefix(16, "", network)
52 }
53
54 // hashForInstance returns a unique hash identifying the rules for this
55 // network/ifname/containerID
56 func hashForInstance(network, ifname, containerID string) string {
57 return hashForNetwork(network) + "-" + utils.MustFormatHashWithPrefix(16, "", ifname+":"+containerID)
58 }
59
60 // commentForInstance returns a comment string that begins with a unique hash and
61 // ends with a (possibly-truncated) human-readable description.
62 func commentForInstance(network, ifname, containerID string) string {
63 comment := fmt.Sprintf("%s, net: %s, if: %s, id: %s",
64 hashForInstance(network, ifname, containerID),
65 strings.ReplaceAll(network, `"`, ``),
66 strings.ReplaceAll(ifname, `"`, ``),
67 strings.ReplaceAll(containerID, `"`, ``),
68 )
69 if len(comment) > knftables.CommentLengthMax {
70 comment = comment[:knftables.CommentLengthMax]
71 }
72 return comment
73 }
74
75 // setupIPMasqNFTables is the nftables-based implementation of SetupIPMasqForNetworks
76 func setupIPMasqNFTables(ipns []*net.IPNet, network, ifname, containerID string) error {
77 nft, err := knftables.New(knftables.InetFamily, ipMasqTableName)
78 if err != nil {
79 return err
80 }
81 return setupIPMasqNFTablesWithInterface(nft, ipns, network, ifname, containerID)
82 }
83
84 func setupIPMasqNFTablesWithInterface(nft knftables.Interface, ipns []*net.IPNet, network, ifname, containerID string) error {
85 staleRules, err := findRules(nft, hashForInstance(network, ifname, containerID))
86 if err != nil {
87 return err
88 }
89
90 tx := nft.NewTransaction()
91
92 // Ensure that our table and chains exist.
93 tx.Add(&knftables.Table{
94 Comment: knftables.PtrTo("Masquerading for plugins from github.com/containernetworking/plugins"),
95 })
96 tx.Add(&knftables.Chain{
97 Name: ipMasqChainName,
98 Comment: knftables.PtrTo("Masquerade traffic from certain IPs to any (non-multicast) IP outside their subnet"),
99 })
100
101 // Ensure that the postrouting chain exists and has the correct rules. (Has to be
102 // done after creating ipMasqChainName, so we can jump to it.)
103 tx.Add(&knftables.Chain{
104 Name: "postrouting",
105 Type: knftables.PtrTo(knftables.NATType),
106 Hook: knftables.PtrTo(knftables.PostroutingHook),
107 Priority: knftables.PtrTo(knftables.SNATPriority),
108 })
109 tx.Flush(&knftables.Chain{
110 Name: "postrouting",
111 })
112 tx.Add(&knftables.Rule{
113 Chain: "postrouting",
114 Rule: "ip daddr == 224.0.0.0/4 return",
115 })
116 tx.Add(&knftables.Rule{
117 Chain: "postrouting",
118 Rule: "ip6 daddr == ff00::/8 return",
119 })
120 tx.Add(&knftables.Rule{
121 Chain: "postrouting",
122 Rule: knftables.Concat(
123 "goto", ipMasqChainName,
124 ),
125 })
126
127 // Delete stale rules, add new rules to masquerade chain
128 for _, rule := range staleRules {
129 tx.Delete(rule)
130 }
131 for _, ipn := range ipns {
132 ip := "ip"
133 if ipn.IP.To4() == nil {
134 ip = "ip6"
135 }
136
137 // e.g. if ipn is "192.168.1.4/24", then dstNet is "192.168.1.0/24"
138 dstNet := &net.IPNet{IP: ipn.IP.Mask(ipn.Mask), Mask: ipn.Mask}
139
140 tx.Add(&knftables.Rule{
141 Chain: ipMasqChainName,
142 Rule: knftables.Concat(
143 ip, "saddr", "==", ipn.IP,
144 ip, "daddr", "!=", dstNet,
145 "masquerade",
146 ),
147 Comment: knftables.PtrTo(commentForInstance(network, ifname, containerID)),
148 })
149 }
150
151 return nft.Run(context.TODO(), tx)
152 }
153
154 // teardownIPMasqNFTables is the nftables-based implementation of TeardownIPMasqForNetworks
155 func teardownIPMasqNFTables(ipns []*net.IPNet, network, ifname, containerID string) error {
156 nft, err := knftables.New(knftables.InetFamily, ipMasqTableName)
157 if err != nil {
158 return err
159 }
160 return teardownIPMasqNFTablesWithInterface(nft, ipns, network, ifname, containerID)
161 }
162
163 func teardownIPMasqNFTablesWithInterface(nft knftables.Interface, _ []*net.IPNet, network, ifname, containerID string) error {
164 rules, err := findRules(nft, hashForInstance(network, ifname, containerID))
165 if err != nil {
166 return err
167 } else if len(rules) == 0 {
168 return nil
169 }
170
171 tx := nft.NewTransaction()
172 for _, rule := range rules {
173 tx.Delete(rule)
174 }
175 return nft.Run(context.TODO(), tx)
176 }
177
178 // gcIPMasqNFTables is the nftables-based implementation of GCIPMasqForNetwork
179 func gcIPMasqNFTables(network string, attachments []types.GCAttachment) error {
180 nft, err := knftables.New(knftables.InetFamily, ipMasqTableName)
181 if err != nil {
182 return err
183 }
184 return gcIPMasqNFTablesWithInterface(nft, network, attachments)
185 }
186
187 func gcIPMasqNFTablesWithInterface(nft knftables.Interface, network string, attachments []types.GCAttachment) error {
188 // Find all rules for the network
189 rules, err := findRules(nft, hashForNetwork(network))
190 if err != nil {
191 return err
192 } else if len(rules) == 0 {
193 return nil
194 }
195
196 // Compute the comments for all elements of attachments
197 validAttachments := map[string]bool{}
198 for _, attachment := range attachments {
199 validAttachments[commentForInstance(network, attachment.IfName, attachment.ContainerID)] = true
200 }
201
202 // Delete anything in rules that isn't in validAttachments
203 tx := nft.NewTransaction()
204 for _, rule := range rules {
205 if !validAttachments[*rule.Comment] {
206 tx.Delete(rule)
207 }
208 }
209 return nft.Run(context.TODO(), tx)
210 }
211
212 // findRules finds rules with comments that start with commentPrefix.
213 func findRules(nft knftables.Interface, commentPrefix string) ([]*knftables.Rule, error) {
214 rules, err := nft.ListRules(context.TODO(), ipMasqChainName)
215 if err != nil {
216 if knftables.IsNotFound(err) {
217 // If ipMasqChainName doesn't exist yet, that's fine
218 return nil, nil
219 }
220 return nil, err
221 }
222
223 matchingRules := make([]*knftables.Rule, 0, 1)
224 for _, rule := range rules {
225 if rule.Comment != nil && strings.HasPrefix(*rule.Comment, commentPrefix) {
226 matchingRules = append(matchingRules, rule)
227 }
228 }
229
230 return matchingRules, nil
231 }