| 1 | // Copyright 2021 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 link |
| 16 | |
| 17 | import ( |
| 18 | "context" |
| 19 | "fmt" |
| 20 | "os" |
| 21 | "time" |
| 22 | |
| 23 | "github.com/networkplumbing/go-nft/nft" |
| 24 | "github.com/networkplumbing/go-nft/nft/schema" |
| 25 | ) |
| 26 | |
| 27 | const ( |
| 28 | natTableName = "nat" |
| 29 | preRoutingBaseChainName = "PREROUTING" |
| 30 | ) |
| 31 | |
| 32 | type NftConfigurer interface { |
| 33 | Apply(*nft.Config) (*nft.Config, error) |
| 34 | Read(filterCommands ...string) (*nft.Config, error) |
| 35 | } |
| 36 | |
| 37 | type SpoofChecker struct { |
| 38 | iface string |
| 39 | macAddress string |
| 40 | refID string |
| 41 | configurer NftConfigurer |
| 42 | rulestore *nft.Config |
| 43 | } |
| 44 | |
| 45 | type defaultNftConfigurer struct{} |
| 46 | |
| 47 | func (dnc defaultNftConfigurer) Apply(cfg *nft.Config) (*nft.Config, error) { |
| 48 | const timeout = 55 * time.Second |
| 49 | ctxWithTimeout, cancelFunc := context.WithTimeout(context.Background(), timeout) |
| 50 | defer cancelFunc() |
| 51 | return nft.ApplyConfigEcho(ctxWithTimeout, cfg) |
| 52 | } |
| 53 | |
| 54 | func (dnc defaultNftConfigurer) Read(filterCommands ...string) (*nft.Config, error) { |
| 55 | const timeout = 55 * time.Second |
| 56 | ctxWithTimeout, cancelFunc := context.WithTimeout(context.Background(), timeout) |
| 57 | defer cancelFunc() |
| 58 | return nft.ReadConfigContext(ctxWithTimeout, filterCommands...) |
| 59 | } |
| 60 | |
| 61 | func NewSpoofChecker(iface, macAddress, refID string) *SpoofChecker { |
| 62 | return NewSpoofCheckerWithConfigurer(iface, macAddress, refID, defaultNftConfigurer{}) |
| 63 | } |
| 64 | |
| 65 | func NewSpoofCheckerWithConfigurer(iface, macAddress, refID string, configurer NftConfigurer) *SpoofChecker { |
| 66 | return &SpoofChecker{iface, macAddress, refID, configurer, nil} |
| 67 | } |
| 68 | |
| 69 | // Setup applies nftables configuration to restrict traffic |
| 70 | // from the provided interface. Only traffic with the mentioned mac address |
| 71 | // is allowed to pass, all others are blocked. |
| 72 | // The configuration follows the format libvirt and ebtables implemented, allowing |
| 73 | // extensions to the rules in the future. |
| 74 | // refID is used to label the rules with a unique comment, identifying the rule-set. |
| 75 | // |
| 76 | // In order to take advantage of the nftables configuration change atomicity, the |
| 77 | // following steps are taken to apply the configuration: |
| 78 | // - Declare the table and chains (they will be created in case not present). |
| 79 | // - Apply the rules, while first flushing the iface/mac specific regular chain rules. |
| 80 | // Two transactions are used because the flush succeeds only if the table/chain it targets |
| 81 | // exists. This avoids the need to query the existing state and acting upon it (a raceful pattern). |
| 82 | // Although two transactions are taken place, only the 2nd one where the rules |
| 83 | // are added has a real impact on the system. |
| 84 | func (sc *SpoofChecker) Setup() error { |
| 85 | baseConfig := nft.NewConfig() |
| 86 | |
| 87 | baseConfig.AddTable(&schema.Table{Family: schema.FamilyBridge, Name: natTableName}) |
| 88 | |
| 89 | baseConfig.AddChain(sc.baseChain()) |
| 90 | ifaceChain := sc.ifaceChain() |
| 91 | baseConfig.AddChain(ifaceChain) |
| 92 | macChain := sc.macChain(ifaceChain.Name) |
| 93 | baseConfig.AddChain(macChain) |
| 94 | |
| 95 | if _, err := sc.configurer.Apply(baseConfig); err != nil { |
| 96 | return fmt.Errorf("failed to setup spoof-check: %v", err) |
| 97 | } |
| 98 | |
| 99 | rulesConfig := nft.NewConfig() |
| 100 | |
| 101 | rulesConfig.FlushChain(ifaceChain) |
| 102 | rulesConfig.FlushChain(macChain) |
| 103 | |
| 104 | rulesConfig.AddRule(sc.matchIfaceJumpToChainRule(preRoutingBaseChainName, ifaceChain.Name)) |
| 105 | rulesConfig.AddRule(sc.jumpToChainRule(ifaceChain.Name, macChain.Name)) |
| 106 | rulesConfig.AddRule(sc.matchMacRule(macChain.Name)) |
| 107 | rulesConfig.AddRule(sc.dropRule(macChain.Name)) |
| 108 | |
| 109 | rulestore, err := sc.configurer.Apply(rulesConfig) |
| 110 | if err != nil { |
| 111 | return fmt.Errorf("failed to setup spoof-check: %v", err) |
| 112 | } |
| 113 | sc.rulestore = rulestore |
| 114 | |
| 115 | return nil |
| 116 | } |
| 117 | |
| 118 | func (sc *SpoofChecker) findPreroutingRule(ruleToFind *schema.Rule) ([]*schema.Rule, error) { |
| 119 | ruleset := sc.rulestore |
| 120 | if ruleset == nil { |
| 121 | chain, err := sc.configurer.Read(listChainBridgeNatPrerouting()...) |
| 122 | if err != nil { |
| 123 | return nil, err |
| 124 | } |
| 125 | ruleset = chain |
| 126 | } |
| 127 | return ruleset.LookupRule(ruleToFind), nil |
| 128 | } |
| 129 | |
| 130 | // Teardown removes the interface and mac-address specific chains and their rules. |
| 131 | // The table and base-chain are expected to survive while the base-chain rule that matches the |
| 132 | // interface is removed. |
| 133 | func (sc *SpoofChecker) Teardown() error { |
| 134 | ifaceChain := sc.ifaceChain() |
| 135 | expectedRuleToFind := sc.matchIfaceJumpToChainRule(preRoutingBaseChainName, ifaceChain.Name) |
| 136 | // It is safer to exclude the statement matching, avoiding cases where a current statement includes |
| 137 | // additional default entries (e.g. counters). |
| 138 | ruleToFindExcludingStatements := *expectedRuleToFind |
| 139 | ruleToFindExcludingStatements.Expr = nil |
| 140 | |
| 141 | rules, ifaceMatchRuleErr := sc.findPreroutingRule(&ruleToFindExcludingStatements) |
| 142 | if ifaceMatchRuleErr == nil && len(rules) > 0 { |
| 143 | c := nft.NewConfig() |
| 144 | for _, rule := range rules { |
| 145 | c.DeleteRule(rule) |
| 146 | } |
| 147 | if _, err := sc.configurer.Apply(c); err != nil { |
| 148 | ifaceMatchRuleErr = fmt.Errorf("failed to delete iface match rule: %v", err) |
| 149 | } |
| 150 | // Drop the cache, it should contain deleted rule(s) now |
| 151 | sc.rulestore = nil |
| 152 | } else { |
| 153 | fmt.Fprintf(os.Stderr, "spoofcheck/teardown: unable to detect iface match rule for deletion: %+v", expectedRuleToFind) |
| 154 | } |
| 155 | |
| 156 | regularChainsConfig := nft.NewConfig() |
| 157 | regularChainsConfig.DeleteChain(ifaceChain) |
| 158 | regularChainsConfig.DeleteChain(sc.macChain(ifaceChain.Name)) |
| 159 | |
| 160 | var regularChainsErr error |
| 161 | if _, err := sc.configurer.Apply(regularChainsConfig); err != nil { |
| 162 | regularChainsErr = fmt.Errorf("failed to delete regular chains: %v", err) |
| 163 | } |
| 164 | |
| 165 | if ifaceMatchRuleErr != nil || regularChainsErr != nil { |
| 166 | return fmt.Errorf("failed to teardown spoof-check: %v, %v", ifaceMatchRuleErr, regularChainsErr) |
| 167 | } |
| 168 | return nil |
| 169 | } |
| 170 | |
| 171 | func (sc *SpoofChecker) matchIfaceJumpToChainRule(chain, toChain string) *schema.Rule { |
| 172 | return &schema.Rule{ |
| 173 | Family: schema.FamilyBridge, |
| 174 | Table: natTableName, |
| 175 | Chain: chain, |
| 176 | Expr: []schema.Statement{ |
| 177 | {Match: &schema.Match{ |
| 178 | Op: schema.OperEQ, |
| 179 | Left: schema.Expression{RowData: []byte(`{"meta":{"key":"iifname"}}`)}, |
| 180 | Right: schema.Expression{String: &sc.iface}, |
| 181 | }}, |
| 182 | {Verdict: schema.Verdict{Jump: &schema.ToTarget{Target: toChain}}}, |
| 183 | }, |
| 184 | Comment: ruleComment(sc.refID), |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | func (sc *SpoofChecker) jumpToChainRule(chain, toChain string) *schema.Rule { |
| 189 | return &schema.Rule{ |
| 190 | Family: schema.FamilyBridge, |
| 191 | Table: natTableName, |
| 192 | Chain: chain, |
| 193 | Expr: []schema.Statement{ |
| 194 | {Verdict: schema.Verdict{Jump: &schema.ToTarget{Target: toChain}}}, |
| 195 | }, |
| 196 | Comment: ruleComment(sc.refID), |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | func (sc *SpoofChecker) matchMacRule(chain string) *schema.Rule { |
| 201 | return &schema.Rule{ |
| 202 | Family: schema.FamilyBridge, |
| 203 | Table: natTableName, |
| 204 | Chain: chain, |
| 205 | Expr: []schema.Statement{ |
| 206 | {Match: &schema.Match{ |
| 207 | Op: schema.OperEQ, |
| 208 | Left: schema.Expression{Payload: &schema.Payload{ |
| 209 | Protocol: schema.PayloadProtocolEther, |
| 210 | Field: schema.PayloadFieldEtherSAddr, |
| 211 | }}, |
| 212 | Right: schema.Expression{String: &sc.macAddress}, |
| 213 | }}, |
| 214 | {Verdict: schema.Verdict{SimpleVerdict: schema.SimpleVerdict{Return: true}}}, |
| 215 | }, |
| 216 | Comment: ruleComment(sc.refID), |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | func (sc *SpoofChecker) dropRule(chain string) *schema.Rule { |
| 221 | return &schema.Rule{ |
| 222 | Family: schema.FamilyBridge, |
| 223 | Table: natTableName, |
| 224 | Chain: chain, |
| 225 | Expr: []schema.Statement{ |
| 226 | {Verdict: schema.Verdict{SimpleVerdict: schema.SimpleVerdict{Drop: true}}}, |
| 227 | }, |
| 228 | Comment: ruleComment(sc.refID), |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | func (sc *SpoofChecker) baseChain() *schema.Chain { |
| 233 | chainPriority := -300 |
| 234 | return &schema.Chain{ |
| 235 | Family: schema.FamilyBridge, |
| 236 | Table: natTableName, |
| 237 | Name: preRoutingBaseChainName, |
| 238 | Type: schema.TypeFilter, |
| 239 | Hook: schema.HookPreRouting, |
| 240 | Prio: &chainPriority, |
| 241 | Policy: schema.PolicyAccept, |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | func (sc *SpoofChecker) ifaceChain() *schema.Chain { |
| 246 | ifaceChainName := "cni-br-iface-" + sc.refID |
| 247 | return &schema.Chain{ |
| 248 | Family: schema.FamilyBridge, |
| 249 | Table: natTableName, |
| 250 | Name: ifaceChainName, |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | func (sc *SpoofChecker) macChain(ifaceChainName string) *schema.Chain { |
| 255 | macChainName := ifaceChainName + "-mac" |
| 256 | return &schema.Chain{ |
| 257 | Family: schema.FamilyBridge, |
| 258 | Table: natTableName, |
| 259 | Name: macChainName, |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | func ruleComment(id string) string { |
| 264 | const refIDPrefix = "macspoofchk-" |
| 265 | return refIDPrefix + id |
| 266 | } |
| 267 | |
| 268 | func listChainBridgeNatPrerouting() []string { |
| 269 | return []string{"chain", "bridge", natTableName, preRoutingBaseChainName} |
| 270 | } |