4
4
"fmt"
5
5
"net"
6
6
"os"
7
+ "strings"
7
8
"syscall"
8
9
9
10
"github.com/NamelessOne91/bisturi/protocols"
@@ -36,11 +37,17 @@ type RawSocket struct {
36
37
// NewRawSocket opens a raw socket for the specified protocol by calling SYS_SOCKET
37
38
// and returns the struct representing it, or eventual errors
38
39
func NewRawSocket (protocol string , ethType uint16 ) (* RawSocket , error ) {
40
+ filter := "all"
41
+ if strings .HasPrefix (protocol , "udp" ) {
42
+ filter = "udp"
43
+ } else if strings .HasPrefix (protocol , "tcp" ) {
44
+ filter = "tcp"
45
+ }
39
46
40
47
rawSocket := & RawSocket {
41
48
shutdownChan : make (chan os.Signal , 1 ),
42
49
ethType : ethType ,
43
- layer4Filter : protocol ,
50
+ layer4Filter : filter ,
44
51
}
45
52
// AF_PACKET specifies a packet socket, operating at the data link layer (Layer 2)
46
53
// SOCK_RAW specifies a raw socket
@@ -76,31 +83,18 @@ func (rs *RawSocket) ReadToChan(dataChan chan<- NetworkPacket, errChan chan<- er
76
83
}
77
84
78
85
switch rs .ethType {
79
- case syscall .ETH_P_IP :
80
- fallthrough
81
- case syscall .ETH_P_IPV6 :
86
+ case syscall .ETH_P_ARP :
87
+ // TODO: ARP parsing
88
+ case syscall .ETH_P_IP , syscall . ETH_P_IPV6 :
82
89
packet , err := protocols .IPPacketFromBytes (buf [:n ])
83
90
if err != nil {
84
91
errChan <- fmt .Errorf ("error reading IP packet: %v" , err )
85
92
continue
86
93
}
87
-
94
+ // IPv4 VS IPv6 packets filtering should be handled by the socket itself
88
95
l4Protocol := packet .Header ().TransportLayerProtocol ()
89
- switch l4Protocol {
90
- case "udp" :
91
- packet , err := protocols .UDPPacketFromIPPacket (packet )
92
- if err != nil {
93
- errChan <- fmt .Errorf ("error reading UDP packet: %v" , err )
94
- continue
95
- }
96
- dataChan <- packet
97
- case "tcp" :
98
- packet , err := protocols .TCPPacketFromIPPacket (packet )
99
- if err != nil {
100
- errChan <- fmt .Errorf ("error reading TCP packet: %v" , err )
101
- continue
102
- }
103
- dataChan <- packet
96
+ if rs .layer4Filter == "all" || (l4Protocol == rs .layer4Filter ) {
97
+ handleLayer4Protocol (l4Protocol , packet , dataChan , errChan )
104
98
}
105
99
}
106
100
}
@@ -110,3 +104,20 @@ func (rs *RawSocket) ReadToChan(dataChan chan<- NetworkPacket, errChan chan<- er
110
104
func (rs * RawSocket ) Close () error {
111
105
return syscall .Close (rs .fd )
112
106
}
107
+
108
+ func handleLayer4Protocol (protocol string , packet protocols.IPPacket , dataChan chan <- NetworkPacket , errChan chan <- error ) {
109
+ var np NetworkPacket
110
+ var err error
111
+
112
+ switch protocol {
113
+ case "udp" :
114
+ np , err = protocols .UDPPacketFromIPPacket (packet )
115
+ case "tcp" :
116
+ np , err = protocols .TCPPacketFromIPPacket (packet )
117
+ }
118
+
119
+ if err != nil {
120
+ errChan <- fmt .Errorf ("error reading UDP packet: %v" , err )
121
+ }
122
+ dataChan <- np
123
+ }
0 commit comments