conntrack.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2020 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. package utils
  15. import (
  16. "fmt"
  17. "net"
  18. "github.com/vishvananda/netlink"
  19. "golang.org/x/sys/unix"
  20. "github.com/containernetworking/plugins/pkg/netlinksafe"
  21. )
  22. // Assigned Internet Protocol Numbers
  23. // https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
  24. const (
  25. PROTOCOL_TCP = 6
  26. PROTOCOL_UDP = 17
  27. PROTOCOL_SCTP = 132
  28. )
  29. // getNetlinkFamily returns the Netlink IP family constant
  30. func getNetlinkFamily(isIPv6 bool) netlink.InetFamily {
  31. if isIPv6 {
  32. return unix.AF_INET6
  33. }
  34. return unix.AF_INET
  35. }
  36. // DeleteConntrackEntriesForDstIP delete the conntrack entries for the connections
  37. // specified by the given destination IP and protocol
  38. func DeleteConntrackEntriesForDstIP(dstIP string, protocol uint8) error {
  39. ip := net.ParseIP(dstIP)
  40. if ip == nil {
  41. return fmt.Errorf("error deleting connection tracking state, bad IP %s", ip)
  42. }
  43. family := getNetlinkFamily(ip.To4() == nil)
  44. filter := &netlink.ConntrackFilter{}
  45. filter.AddIP(netlink.ConntrackOrigDstIP, ip)
  46. filter.AddProtocol(protocol)
  47. _, err := netlinksafe.ConntrackDeleteFilters(netlink.ConntrackTable, family, filter)
  48. if err != nil {
  49. return fmt.Errorf("error deleting connection tracking state for protocol: %d IP: %s, error: %v", protocol, ip, err)
  50. }
  51. return nil
  52. }
  53. // DeleteConntrackEntriesForDstPort delete the conntrack entries for the connections specified
  54. // by the given destination port, protocol and IP family
  55. func DeleteConntrackEntriesForDstPort(port uint16, protocol uint8, family netlink.InetFamily) error {
  56. filter := &netlink.ConntrackFilter{}
  57. filter.AddProtocol(protocol)
  58. filter.AddPort(netlink.ConntrackOrigDstPort, port)
  59. _, err := netlinksafe.ConntrackDeleteFilters(netlink.ConntrackTable, family, filter)
  60. if err != nil {
  61. return fmt.Errorf("error deleting connection tracking state for protocol: %d Port: %d, error: %v", protocol, port, err)
  62. }
  63. return nil
  64. }