-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathtzsp_linux.go
244 lines (206 loc) · 6.35 KB
/
tzsp_linux.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
//go:build linux
// +build linux
// Written by Noel Kuntze <noel.kuntze {@@@@@} thermi.consulting>
// Updating by Denis Machard
package workers
import (
"context"
"encoding/binary"
"errors"
"fmt"
"net"
"syscall"
"time"
"github.com/dmachard/go-dnscollector/dnsutils"
"github.com/dmachard/go-dnscollector/pkgconfig"
"github.com/dmachard/go-logger"
"github.com/dmachard/go-netutils"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/rs/tzsp"
)
type TZSPSniffer struct {
*GenericWorker
listen net.UDPConn
}
func NewTZSP(next []Worker, config *pkgconfig.Config, logger *logger.Logger, name string) *TZSPSniffer {
bufSize := config.Global.Worker.ChannelBufferSize
if config.Collectors.Tzsp.ChannelBufferSize > 0 {
bufSize = config.Collectors.Tzsp.ChannelBufferSize
}
s := &TZSPSniffer{GenericWorker: NewGenericWorker(config, logger, name, "tzsp", bufSize, pkgconfig.DefaultMonitor)}
s.SetDefaultRoutes(next)
return s
}
func (w *TZSPSniffer) Listen() error {
w.LogInfo("starting UDP server...")
ServerAddr, err := net.ResolveUDPAddr("udp",
fmt.Sprintf("%s:%d", w.GetConfig().Collectors.Tzsp.ListenIP, w.GetConfig().Collectors.Tzsp.ListenPort),
)
if err != nil {
return err
}
ServerConn, err := net.ListenUDP("udp", ServerAddr)
if err != nil {
return err
}
file, err := ServerConn.File()
if err != nil {
return err
}
err = syscall.SetsockoptInt(int(file.Fd()), syscall.SOL_SOCKET, syscall.SO_TIMESTAMPNS, 1)
if err != nil {
return err
}
// calling File.Fd() disables the SetDeadline methods
err = syscall.SetNonblock(int(file.Fd()), true)
if err != nil {
return err
}
w.LogInfo("is listening on %s", ServerConn.LocalAddr())
w.listen = *ServerConn
return nil
}
func (w *TZSPSniffer) StartCollect() {
w.LogInfo("starting data collection")
defer w.CollectDone()
// start server
if err := w.Listen(); err != nil {
w.LogFatal(pkgconfig.PrefixLogWorker+"["+w.GetName()+"] listening failed: ", err)
}
// init dns processor
dnsProcessor := NewDNSProcessor(w.GetConfig(), w.GetLogger(), w.GetName(), w.GetConfig().Collectors.Tzsp.ChannelBufferSize)
dnsProcessor.SetDefaultRoutes(w.GetDefaultRoutes())
dnsProcessor.SetDefaultDropped(w.GetDroppedRoutes())
go dnsProcessor.StartCollect()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func(ctx context.Context) {
defer func() {
dnsProcessor.Stop()
w.LogInfo("read data terminated")
defer close(done)
}()
buf := make([]byte, 1024)
oob := make([]byte, 1024)
var netErr net.Error
for {
select {
case <-ctx.Done():
w.LogInfo("stopping UDP server...")
w.listen.Close()
return
default:
w.listen.SetReadDeadline(time.Now().Add(1 * time.Second))
bufN, oobn, _, _, err := w.listen.ReadMsgUDPAddrPort(buf, oob)
if err != nil {
if errors.As(err, &netErr) && netErr.Timeout() {
continue
}
w.LogFatal(pkgconfig.PrefixLogWorker+"["+w.GetName()+"] read msg", err)
}
if bufN == 0 {
w.LogFatal(pkgconfig.PrefixLogWorker + "[" + w.GetName() + "] read msg, buffer is empty")
}
if bufN > len(buf) {
w.LogFatal(pkgconfig.PrefixLogWorker + "[" + w.GetName() + "] read msg, bufer overflow")
}
if oobn == 0 {
w.LogFatal(pkgconfig.PrefixLogWorker + "[" + w.GetName() + "] read msg, oob missing")
}
scms, err := syscall.ParseSocketControlMessage(oob[:oobn])
if err != nil {
w.LogFatal(pkgconfig.PrefixLogWorker+"["+w.GetName()+"] parse control msg", err)
}
if len(scms) != 1 {
w.LogInfo("len(scms) != 1")
continue
}
scm := scms[0]
if scm.Header.Type != syscall.SCM_TIMESTAMPNS {
w.LogFatal(pkgconfig.PrefixLogWorker + "[" + w.GetName() + "] scm timestampns missing")
}
tsec := binary.LittleEndian.Uint32(scm.Data[:4])
nsec := binary.LittleEndian.Uint32(scm.Data[8:12])
// copy packet data from buffer
pkt := make([]byte, bufN)
copy(pkt, buf[:bufN])
tzspPacket, err := tzsp.Parse(pkt)
if err != nil {
w.LogError("Failed to parse packet: ", err)
continue
}
var eth layers.Ethernet
var ip4 layers.IPv4
var ip6 layers.IPv6
var tcp layers.TCP
var udp layers.UDP
parser := gopacket.NewDecodingLayerParser(layers.LayerTypeEthernet, ð, &ip4, &ip6, &tcp, &udp)
decodedLayers := make([]gopacket.LayerType, 0, 4)
// decode-it
parser.DecodeLayers(tzspPacket.Data, &decodedLayers)
dm := dnsutils.DNSMessage{}
dm.Init()
ignorePacket := false
for _, layertyp := range decodedLayers {
switch layertyp {
case layers.LayerTypeIPv4:
dm.NetworkInfo.Family = netutils.ProtoIPv4
dm.NetworkInfo.QueryIP = ip4.SrcIP.String()
dm.NetworkInfo.ResponseIP = ip4.DstIP.String()
case layers.LayerTypeIPv6:
dm.NetworkInfo.QueryIP = ip6.SrcIP.String()
dm.NetworkInfo.ResponseIP = ip6.DstIP.String()
dm.NetworkInfo.Family = netutils.ProtoIPv6
case layers.LayerTypeUDP:
dm.NetworkInfo.QueryPort = fmt.Sprint(int(udp.SrcPort))
dm.NetworkInfo.ResponsePort = fmt.Sprint(int(udp.DstPort))
dm.DNS.Payload = udp.Payload
dm.DNS.Length = len(udp.Payload)
dm.NetworkInfo.Protocol = netutils.ProtoUDP
case layers.LayerTypeTCP:
if len(tcp.Payload) < 12 {
// packet way too short; 12 byte is the minimum size a DNS packet (header only,
// no questions, answers, authorities, or additional RRs)
continue
}
dnsLengthField := binary.BigEndian.Uint16(tcp.Payload[0:2])
if len(tcp.Payload) < int(dnsLengthField) {
ignorePacket = true
continue
}
dm.NetworkInfo.QueryPort = fmt.Sprint(int(tcp.SrcPort))
dm.NetworkInfo.ResponsePort = fmt.Sprint(int(tcp.DstPort))
dm.DNS.Payload = tcp.Payload[2:]
dm.DNS.Length = len(tcp.Payload[2:])
dm.NetworkInfo.Protocol = netutils.ProtoTCP
}
}
if !ignorePacket {
dm.DNSTap.Identity = w.GetConfig().GetServerIdentity()
// set timestamp
dm.DNSTap.TimeSec = int(tsec)
dm.DNSTap.TimeNsec = int(nsec)
// just decode QR
if len(dm.DNS.Payload) < 4 {
continue
}
dnsProcessor.GetInputChannel() <- dm
}
}
}
}(ctx)
// main loop
for {
select {
case <-w.OnStop():
w.LogInfo("stopping read goroutine")
cancel()
<-done
return
// save the new config
case cfg := <-w.NewConfig():
w.SetConfig(cfg)
}
}
}