1
0

packet.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package firewall
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/netip"
  6. "github.com/slackhq/nebula/iputil"
  7. )
  8. type m = map[string]any
  9. const (
  10. ProtoAny = 0 // When we want to handle HOPOPT (0) we can change this, if ever
  11. PortAny = 0 // Special value for matching `port: any`
  12. PortFragment = -1 // Special value for matching `port: fragment`
  13. )
  14. type Packet struct {
  15. LocalAddr netip.Addr
  16. RemoteAddr netip.Addr
  17. // LocalPort is the destination port for incoming traffic, or the source port for outgoing. Zero for ICMP.
  18. LocalPort uint16
  19. // RemotePort is the source port for incoming traffic, or the destination port for outgoing.
  20. // For ICMP, it's the "identifier". This is only used for connection tracking, actual firewall rules will not filter on ICMP identifier
  21. RemotePort uint16
  22. Protocol uint8
  23. Fragment bool
  24. }
  25. func (fp *Packet) Copy() *Packet {
  26. return &Packet{
  27. LocalAddr: fp.LocalAddr,
  28. RemoteAddr: fp.RemoteAddr,
  29. LocalPort: fp.LocalPort,
  30. RemotePort: fp.RemotePort,
  31. Protocol: fp.Protocol,
  32. Fragment: fp.Fragment,
  33. }
  34. }
  35. func (fp Packet) MarshalJSON() ([]byte, error) {
  36. var proto string
  37. switch fp.Protocol {
  38. case iputil.IPProtocolTCP:
  39. proto = "tcp"
  40. case iputil.IPProtocolICMP:
  41. proto = "icmp"
  42. case iputil.IPProtocolICMPv6:
  43. proto = "icmpv6"
  44. case iputil.IPProtocolUDP:
  45. proto = "udp"
  46. default:
  47. proto = fmt.Sprintf("unknown %v", fp.Protocol)
  48. }
  49. return json.Marshal(m{
  50. "LocalAddr": fp.LocalAddr.String(),
  51. "RemoteAddr": fp.RemoteAddr.String(),
  52. "LocalPort": fp.LocalPort,
  53. "RemotePort": fp.RemotePort,
  54. "Protocol": proto,
  55. "Fragment": fp.Fragment,
  56. })
  57. }
  58. // ParsedPacket is a Packet plus the parse byproducts the RX path reuses
  59. type ParsedPacket struct {
  60. Packet
  61. IPHdrLen int
  62. // FragAny reports any fragmentation at all: MF flag or nonzero offset for IPv4, a fragment extension header for IPv6.
  63. // Distinct from Packet.Fragment, which is true only for NON-FIRST fragments
  64. FragAny bool
  65. }