forked from TencentBlueKing/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls.go
363 lines (311 loc) · 8.75 KB
/
tls.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package tls
import (
"crypto/x509"
"time"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/packetbeat/procs"
"github.com/elastic/beats/packetbeat/protos"
"github.com/elastic/beats/packetbeat/protos/applayer"
"github.com/elastic/beats/packetbeat/protos/tcp"
)
type stream struct {
applayer.Stream
parser parser
tcptuple *common.TCPTuple
cmdlineTuple *common.CmdlineTuple
}
type tlsConnectionData struct {
streams [2]*stream
handshakeCompleted int8
eventSent bool
}
// TLS protocol plugin
type tlsPlugin struct {
// config
ports []int
sendCertificates bool
includeRawCertificates bool
transactionTimeout time.Duration
results protos.Reporter
}
var (
debugf = logp.MakeDebug("tls")
isDebug = false
// ensure that tlsPlugin fulfills the TCPPlugin interface
_ protos.TCPPlugin = &tlsPlugin{}
)
func init() {
protos.Register("tls", New)
}
// New returns a new instance of the TLS plugin
func New(
testMode bool,
results protos.Reporter,
cfg *common.Config,
) (protos.Plugin, error) {
p := &tlsPlugin{}
config := defaultConfig
if !testMode {
if err := cfg.Unpack(&config); err != nil {
return nil, err
}
}
if err := p.init(results, &config); err != nil {
return nil, err
}
return p, nil
}
func (plugin *tlsPlugin) init(results protos.Reporter, config *tlsConfig) error {
plugin.setFromConfig(config)
plugin.results = results
isDebug = logp.IsDebug("tls")
return nil
}
func (plugin *tlsPlugin) setFromConfig(config *tlsConfig) {
plugin.ports = config.Ports
plugin.sendCertificates = config.SendCertificates
plugin.includeRawCertificates = config.IncludeRawCertificates
plugin.transactionTimeout = config.TransactionTimeout
}
func (plugin *tlsPlugin) GetPorts() []int {
return plugin.ports
}
func (plugin *tlsPlugin) ConnectionTimeout() time.Duration {
return plugin.transactionTimeout
}
func (plugin *tlsPlugin) Parse(
pkt *protos.Packet,
tcptuple *common.TCPTuple,
dir uint8,
private protos.ProtocolData,
) protos.ProtocolData {
defer logp.Recover("ParseTLS exception")
conn := ensureTLSConnection(private)
conn = plugin.doParse(conn, pkt, tcptuple, dir)
if conn == nil {
return nil
}
return conn
}
func ensureTLSConnection(private protos.ProtocolData) *tlsConnectionData {
if private == nil {
return &tlsConnectionData{}
}
priv, ok := private.(*tlsConnectionData)
if !ok {
logp.Warn("tls connection data type error, creating a new one")
return &tlsConnectionData{}
}
return priv
}
func (plugin *tlsPlugin) doParse(
conn *tlsConnectionData,
pkt *protos.Packet,
tcptuple *common.TCPTuple,
dir uint8,
) *tlsConnectionData {
// Ignore further traffic after the handshake is completed (encrypted connection)
// TODO: request/response analysis
if 0 != conn.handshakeCompleted&(1<<dir) {
return conn
}
st := conn.streams[dir]
if st == nil {
st = newStream(tcptuple)
st.cmdlineTuple = procs.ProcWatcher.FindProcessesTuple(tcptuple.IPPort())
conn.streams[dir] = st
}
if err := st.Append(pkt.Payload); err != nil {
if isDebug {
debugf("%v, dropping TCP stream", err)
}
return nil
}
state := resultOK
for state == resultOK && st.Buf.Len() > 0 {
state = st.parser.parse(&st.Buf)
switch state {
case resultOK, resultMore:
// no-op
case resultFailed:
// drop this tcp stream. Will retry parsing with the next
// segment in it
conn.streams[dir] = nil
if isDebug {
debugf("non-TLS message: TCP stream dropped. Try parsing with the next segment")
}
case resultEncrypted:
conn.handshakeCompleted |= 1 << dir
if conn.handshakeCompleted == 3 {
plugin.sendEvent(conn)
}
}
}
return conn
}
func newStream(tcptuple *common.TCPTuple) *stream {
s := &stream{
tcptuple: tcptuple,
}
s.Stream.Init(tcp.TCPMaxDataInStream)
return s
}
func (plugin *tlsPlugin) ReceivedFin(tcptuple *common.TCPTuple, dir uint8,
private protos.ProtocolData) protos.ProtocolData {
if conn := ensureTLSConnection(private); conn != nil {
plugin.sendEvent(conn)
}
return private
}
func (plugin *tlsPlugin) GapInStream(tcptuple *common.TCPTuple, dir uint8,
nbytes int, private protos.ProtocolData) (priv protos.ProtocolData, drop bool) {
if conn := ensureTLSConnection(private); conn != nil {
plugin.sendEvent(conn)
}
return private, true
}
func (plugin *tlsPlugin) sendEvent(conn *tlsConnectionData) {
if !conn.eventSent {
conn.eventSent = true
if conn.hasInfo() {
event := plugin.createEvent(conn)
plugin.results(event)
}
}
}
func (plugin *tlsPlugin) createEvent(conn *tlsConnectionData) beat.Event {
status := common.OK_STATUS
if conn.handshakeCompleted < 2 {
status = common.ERROR_STATUS
}
emptyStream := &stream{}
client := conn.streams[0]
server := conn.streams[1]
if client == nil {
client = emptyStream
}
if server == nil {
server = emptyStream
}
if client.parser.direction == dirServer || server.parser.direction == dirClient {
client, server = server, client
}
tls := common.MapStr{
"handshake_completed": conn.handshakeCompleted > 1,
}
emptyHello := &helloMessage{}
var clientHello, serverHello *helloMessage
if client.parser.hello != nil {
clientHello = client.parser.hello
tls["client_hello"] = clientHello.toMap()
} else {
clientHello = emptyHello
}
if server.parser.hello != nil {
serverHello = server.parser.hello
tls["server_hello"] = serverHello.toMap()
} else {
serverHello = emptyHello
}
if cert, chain := getCerts(client.parser.certificates, plugin.includeRawCertificates); cert != nil {
tls["client_certificate"] = cert
if chain != nil {
tls["client_certificate_chain"] = chain
}
}
if plugin.sendCertificates {
if cert, chain := getCerts(server.parser.certificates, plugin.includeRawCertificates); cert != nil {
tls["server_certificate"] = cert
if chain != nil {
tls["server_certificate_chain"] = chain
}
}
}
tls["client_certificate_requested"] = server.parser.certRequested
// It is a bit tricky to detect the mechanism used for a resumed session. If the client offered a ticket, then
// ticket is assumed as the method used for resumption even when a session ID is also used (as RFC-5077 requires).
// It is not possible to tell whether the server accepted the ticket or the session ID.
sessionIDMatch := len(clientHello.sessionID) != 0 && clientHello.sessionID == serverHello.sessionID
ticketOffered := len(clientHello.ticket.value) != 0 && serverHello.ticket.present
resumed := !client.parser.keyExchanged && !server.parser.keyExchanged && (sessionIDMatch || ticketOffered)
tls["resumed"] = resumed
if resumed {
if ticketOffered {
tls["resumption_method"] = "ticket"
} else {
tls["resumption_method"] = "id"
}
}
numAlerts := len(client.parser.alerts) + len(server.parser.alerts)
alerts := make([]common.MapStr, 0, numAlerts)
alertTypes := make([]string, 0, numAlerts)
for _, alert := range client.parser.alerts {
alerts = append(alerts, alert.toMap("client"))
alertTypes = append(alertTypes, alert.code.String())
}
for _, alert := range server.parser.alerts {
alerts = append(alerts, alert.toMap("server"))
alertTypes = append(alertTypes, alert.code.String())
}
if numAlerts != 0 {
tls["alerts"] = alerts
tls["alert_types"] = alertTypes
}
src := &common.Endpoint{}
dst := &common.Endpoint{}
tcptuple := client.tcptuple
if tcptuple == nil {
tcptuple = server.tcptuple
}
if tcptuple != nil {
src.IP = tcptuple.SrcIP.String()
src.Port = tcptuple.SrcPort
dst.IP = tcptuple.DstIP.String()
dst.Port = tcptuple.DstPort
}
if client.cmdlineTuple != nil {
src.Proc = string(client.cmdlineTuple.Src)
dst.Proc = string(client.cmdlineTuple.Dst)
} else if server.cmdlineTuple != nil {
src.Proc = string(server.cmdlineTuple.Dst)
dst.Proc = string(server.cmdlineTuple.Src)
}
fields := common.MapStr{
"type": "tls",
"status": status,
"tls": tls,
"src": src,
"dst": dst,
}
// set "server" to SNI, if provided
if value, ok := clientHello.extensions["server_name_indication"]; ok {
if list, ok := value.([]string); ok && len(list) > 0 {
fields["server"] = list[0]
}
}
timestamp := time.Now()
return beat.Event{
Timestamp: timestamp,
Fields: fields,
}
}
func getCerts(certs []*x509.Certificate, includeRaw bool) (common.MapStr, []common.MapStr) {
if len(certs) == 0 {
return nil, nil
}
cert := certToMap(certs[0], includeRaw)
if len(certs) == 1 {
return cert, nil
}
chain := make([]common.MapStr, len(certs)-1)
for idx := 1; idx < len(certs); idx++ {
chain[idx-1] = certToMap(certs[idx], includeRaw)
}
return cert, chain
}
func (conn *tlsConnectionData) hasInfo() bool {
return (conn.streams[0] != nil && conn.streams[0].parser.hasInfo()) ||
(conn.streams[1] != nil && conn.streams[1].parser.hasInfo())
}