packet.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package firewall
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/netip"
  6. )
  7. type m = map[string]any
  8. const (
  9. ProtoAny = 0 // When we want to handle HOPOPT (0) we can change this, if ever
  10. ProtoTCP = 6
  11. ProtoUDP = 17
  12. ProtoICMP = 1
  13. ProtoICMPv6 = 58
  14. PortAny = 0 // Special value for matching `port: any`
  15. PortFragment = -1 // Special value for matching `port: fragment`
  16. )
  17. type TransportTuple struct {
  18. FirstAddr [16]byte
  19. SecondAddr [16]byte
  20. FirstPort uint16
  21. SecondPort uint16
  22. IsV6 bool
  23. }
  24. type Packet struct {
  25. LocalAddr netip.Addr
  26. RemoteAddr netip.Addr
  27. // LocalPort is the destination port for incoming traffic, or the source port for outgoing. Zero for ICMP.
  28. LocalPort uint16
  29. // RemotePort is the source port for incoming traffic, or the destination port for outgoing.
  30. // For ICMP, it's the "identifier". This is only used for connection tracking, actual firewall rules will not filter on ICMP identifier
  31. RemotePort uint16
  32. Protocol uint8
  33. Fragment bool
  34. }
  35. func (fp *Packet) Copy() *Packet {
  36. return &Packet{
  37. LocalAddr: fp.LocalAddr,
  38. RemoteAddr: fp.RemoteAddr,
  39. LocalPort: fp.LocalPort,
  40. RemotePort: fp.RemotePort,
  41. Protocol: fp.Protocol,
  42. Fragment: fp.Fragment,
  43. }
  44. }
  45. func (fp Packet) MarshalJSON() ([]byte, error) {
  46. var proto string
  47. switch fp.Protocol {
  48. case ProtoTCP:
  49. proto = "tcp"
  50. case ProtoICMP:
  51. proto = "icmp"
  52. case ProtoICMPv6:
  53. proto = "icmpv6"
  54. case ProtoUDP:
  55. proto = "udp"
  56. default:
  57. proto = fmt.Sprintf("unknown %v", fp.Protocol)
  58. }
  59. return json.Marshal(m{
  60. "LocalAddr": fp.LocalAddr.String(),
  61. "RemoteAddr": fp.RemoteAddr.String(),
  62. "LocalPort": fp.LocalPort,
  63. "RemotePort": fp.RemotePort,
  64. "Protocol": proto,
  65. "Fragment": fp.Fragment,
  66. })
  67. }