-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcapability_icmp.go
94 lines (78 loc) · 2.37 KB
/
capability_icmp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package exu
import log "github.com/sirupsen/logrus"
type CapabilityIcmp struct {
*IpDevice
}
func (c CapabilityIcmp) HandleRequest(port *VPort, data *EthernetFrame) CapabilityStatus {
ipv4Packet := &IPv4Packet{}
err := ipv4Packet.UnmarshalBinary(data.Payload())
if err != nil {
return CapabilityStatusFail
}
icmpPayload := &ICMPPayload{}
err = icmpPayload.UnmarshalBinary(ipv4Packet.Payload)
if err != nil {
return CapabilityStatusFail
}
// if the packet is for one of our ports, reply with an ICMP echo reply
if c.portIPs[port].IP.Equal(ipv4Packet.Header.DestinationIP) {
log.WithFields(log.Fields{
"device": c.name,
"port": port.portCname,
"source_ip": ipv4Packet.Header.SourceIP,
"capabilty": "icmp",
}).Debug("received ICMP packet")
// create the ICMP payload
icmpResponsePayload := &ICMPPayload{
Type: ICMPTypeEchoReply,
Code: 0,
Data: icmpPayload.Data,
}
icmpResponsePayload.Checksum = icmpResponsePayload.CalculateChecksum()
icmpResponsePayloadBytes, _ := icmpResponsePayload.MarshalBinary()
ipv4ResponsePacket := &IPv4Packet{
Header: IPv4Header{
Version: 4,
IHL: 5,
TOS: 0,
TotalLength: uint16(20 + len(icmpResponsePayloadBytes)),
ID: 0,
FlagsFragment: 0,
TTL: 64,
Protocol: IPv4ProtocolICMP,
HeaderChecksum: 0,
SourceIP: c.portIPs[port].IP,
DestinationIP: ipv4Packet.Header.SourceIP,
},
Payload: icmpResponsePayloadBytes,
}
ipv4ResponsePacket.Header.HeaderChecksum = ipv4ResponsePacket.Header.CalculateChecksum()
// create the ethernet frame
ethernetFrame, err := NewEthernetFrame(data.Source(), data.Destination(), WithTagging(TaggingUntagged), ipv4ResponsePacket)
if err != nil {
return CapabilityStatusFail
}
// write the frame to the source port
_ = port.Write(ethernetFrame)
return CapabilityStatusDone
}
return CapabilityStatusPass
}
func (c CapabilityIcmp) Match(_ *VPort, data *EthernetFrame) bool {
if data.EtherType().Equal(EtherTypeIPv4) {
ipv4Packet := &IPv4Packet{}
err := ipv4Packet.UnmarshalBinary(data.Payload())
if err != nil {
return false
}
if ipv4Packet.Header.Protocol == IPv4ProtocolICMP {
icmpPayload := &ICMPPayload{}
err = icmpPayload.UnmarshalBinary(ipv4Packet.Payload)
if err != nil {
return false
}
return true
}
}
return false
}