| 1 |
package firewall |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"fmt" |
| 6 |
"net/netip" |
| 7 |
) |
| 8 |
|
| 9 |
type m = map[string]any |
| 10 |
|
| 11 |
const ( |
| 12 |
ProtoAny = 0 // When we want to handle HOPOPT (0) we can change this, if ever |
| 13 |
ProtoTCP = 6 |
| 14 |
ProtoUDP = 17 |
| 15 |
ProtoICMP = 1 |
| 16 |
ProtoICMPv6 = 58 |
| 17 |
|
| 18 |
PortAny = 0 // Special value for matching `port: any` |
| 19 |
PortFragment = -1 // Special value for matching `port: fragment` |
| 20 |
) |
| 21 |
|
| 22 |
type Packet struct { |
| 23 |
LocalAddr netip.Addr |
| 24 |
RemoteAddr netip.Addr |
| 25 |
// LocalPort is the destination port for incoming traffic, or the source port for outgoing. Zero for ICMP. |
| 26 |
LocalPort uint16 |
| 27 |
// RemotePort is the source port for incoming traffic, or the destination port for outgoing. |
| 28 |
// For ICMP, it's the "identifier". This is only used for connection tracking, actual firewall rules will not filter on ICMP identifier |
| 29 |
RemotePort uint16 |
| 30 |
Protocol uint8 |
| 31 |
Fragment bool |
| 32 |
} |
| 33 |
|
| 34 |
func (fp *Packet) Copy() *Packet { |
| 35 |
return &Packet{ |
| 36 |
LocalAddr: fp.LocalAddr, |
| 37 |
RemoteAddr: fp.RemoteAddr, |
| 38 |
LocalPort: fp.LocalPort, |
| 39 |
RemotePort: fp.RemotePort, |
| 40 |
Protocol: fp.Protocol, |
| 41 |
Fragment: fp.Fragment, |
| 42 |
} |
| 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 |
} |