aboutsummaryrefslogtreecommitdiff
path: root/connection_streams_controller.go
blob: 038c2c56086db61243d86788ee60212cff6b9f20 (plain) (blame)
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
364
365
366
367
368
369
370
371
372
373
374
375
/*
 * This file is part of caronte (https://github.com/eciavatta/caronte).
 * Copyright (c) 2020 Emiliano Ciavatta.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package main

import (
	"bytes"
	"context"
	"fmt"
	"github.com/eciavatta/caronte/parsers"
	log "github.com/sirupsen/logrus"
	"strings"
	"time"
)

const (
	initialMessagesSize     = 1024
	initialRegexSlicesCount = 8
	pwntoolsMaxServerBytes  = 20
)

type ConnectionStream struct {
	ID               RowID                   `bson:"_id"`
	ConnectionID     RowID                   `bson:"connection_id"`
	FromClient       bool                    `bson:"from_client"`
	DocumentIndex    int                     `bson:"document_index"`
	Payload          []byte                  `bson:"payload"`
	PayloadString    string                  `bson:"payload_string"`
	BlocksIndexes    []int                   `bson:"blocks_indexes"`
	BlocksTimestamps []time.Time             `bson:"blocks_timestamps"`
	BlocksLoss       []bool                  `bson:"blocks_loss"`
	PatternMatches   map[uint][]PatternSlice `bson:"pattern_matches"`
}

type PatternSlice [2]uint64

type Message struct {
	FromClient             bool             `json:"from_client"`
	Content                string           `json:"content"`
	Metadata               parsers.Metadata `json:"metadata"`
	IsMetadataContinuation bool             `json:"is_metadata_continuation"`
	Index                  int              `json:"index"`
	Timestamp              time.Time        `json:"timestamp"`
	IsRetransmitted        bool             `json:"is_retransmitted"`
	RegexMatches           []RegexSlice     `json:"regex_matches"`
}

type RegexSlice struct {
	From uint64 `json:"from"`
	To   uint64 `json:"to"`
}

type GetMessageFormat struct {
	Format string `form:"format"`
}

type DownloadMessageFormat struct {
	Format string `form:"format"`
	Type   string `form:"type"`
}

type ConnectionStreamsController struct {
	storage Storage
}

func NewConnectionStreamsController(storage Storage) ConnectionStreamsController {
	return ConnectionStreamsController{
		storage: storage,
	}
}

func (csc ConnectionStreamsController) GetConnectionMessages(c context.Context, connectionID RowID,
	format GetMessageFormat) ([]*Message, bool) {
	connection := csc.getConnection(c, connectionID)
	if connection.ID.IsZero() {
		return nil, false
	}

	messages := make([]*Message, 0, initialMessagesSize)
	var clientIndex, serverIndex uint64

	var clientBlocksIndex, serverBlocksIndex int
	var clientDocumentIndex, serverDocumentIndex int
	clientStream := csc.getConnectionStream(c, connectionID, true, clientDocumentIndex)
	serverStream := csc.getConnectionStream(c, connectionID, false, serverDocumentIndex)

	hasClientBlocks := func() bool {
		return clientBlocksIndex < len(clientStream.BlocksIndexes)
	}
	hasServerBlocks := func() bool {
		return serverBlocksIndex < len(serverStream.BlocksIndexes)
	}

	var message *Message
	messagesBuffer := make([]*Message, 0, 16)
	contentChunkBuffer := new(bytes.Buffer)
	var lastContentSlice []byte
	var sideChanged, lastClient, lastServer bool
	for !clientStream.ID.IsZero() || !serverStream.ID.IsZero() {
		if hasClientBlocks() && (!hasServerBlocks() || // next payload is from client
			clientStream.BlocksTimestamps[clientBlocksIndex].UnixNano() <=
				serverStream.BlocksTimestamps[serverBlocksIndex].UnixNano()) {
			start := clientStream.BlocksIndexes[clientBlocksIndex]
			end := 0
			if clientBlocksIndex < len(clientStream.BlocksIndexes)-1 {
				end = clientStream.BlocksIndexes[clientBlocksIndex+1]
			} else {
				end = len(clientStream.Payload)
			}
			size := uint64(end - start)

			message = &Message{
				FromClient:      true,
				Content:         DecodeBytes(clientStream.Payload[start:end], format.Format),
				Index:           start,
				Timestamp:       clientStream.BlocksTimestamps[clientBlocksIndex],
				IsRetransmitted: clientStream.BlocksLoss[clientBlocksIndex],
				RegexMatches:    findMatchesBetween(clientStream.PatternMatches, clientIndex, clientIndex+size),
			}
			clientIndex += size
			clientBlocksIndex++

			lastContentSlice = clientStream.Payload[start:end]
			sideChanged, lastClient, lastServer = lastServer, true, false
		} else { // next payload is from server
			start := serverStream.BlocksIndexes[serverBlocksIndex]
			end := 0
			if serverBlocksIndex < len(serverStream.BlocksIndexes)-1 {
				end = serverStream.BlocksIndexes[serverBlocksIndex+1]
			} else {
				end = len(serverStream.Payload)
			}
			size := uint64(end - start)

			message = &Message{
				FromClient:      false,
				Content:         DecodeBytes(serverStream.Payload[start:end], format.Format),
				Index:           start,
				Timestamp:       serverStream.BlocksTimestamps[serverBlocksIndex],
				IsRetransmitted: serverStream.BlocksLoss[serverBlocksIndex],
				RegexMatches:    findMatchesBetween(serverStream.PatternMatches, serverIndex, serverIndex+size),
			}
			serverIndex += size
			serverBlocksIndex++

			lastContentSlice = serverStream.Payload[start:end]
			sideChanged, lastClient, lastServer = lastClient, false, true
		}

		if !hasClientBlocks() {
			clientDocumentIndex++
			clientBlocksIndex = 0
			clientIndex = 0
			clientStream = csc.getConnectionStream(c, connectionID, true, clientDocumentIndex)
		}
		if !hasServerBlocks() {
			serverDocumentIndex++
			serverBlocksIndex = 0
			serverIndex = 0
			serverStream = csc.getConnectionStream(c, connectionID, false, serverDocumentIndex)
		}

		updateMetadata := func() {
			metadata := parsers.Parse(contentChunkBuffer.Bytes())
			var isMetadataContinuation bool
			for _, elem := range messagesBuffer {
				elem.Metadata = metadata
				elem.IsMetadataContinuation = isMetadataContinuation
				isMetadataContinuation = true
			}

			messagesBuffer = messagesBuffer[:0]
			contentChunkBuffer.Reset()
		}

		if sideChanged {
			updateMetadata()
		}
		messagesBuffer = append(messagesBuffer, message)
		contentChunkBuffer.Write(lastContentSlice)

		if clientStream.ID.IsZero() && serverStream.ID.IsZero() {
			updateMetadata()
		}

		messages = append(messages, message)
	}

	return messages, true
}

func (csc ConnectionStreamsController) DownloadConnectionMessages(c context.Context, connectionID RowID,
	format DownloadMessageFormat) (string, bool) {
	connection := csc.getConnection(c, connectionID)
	if connection.ID.IsZero() {
		return "", false
	}

	var sb strings.Builder
	includeClient, includeServer := format.Type != "only_server", format.Type != "only_client"
	isPwntools := format.Type == "pwntools"

	var clientBlocksIndex, serverBlocksIndex int
	var clientDocumentIndex, serverDocumentIndex int
	var clientStream ConnectionStream
	if includeClient {
		clientStream = csc.getConnectionStream(c, connectionID, true, clientDocumentIndex)
	}
	var serverStream ConnectionStream
	if includeServer {
		serverStream = csc.getConnectionStream(c, connectionID, false, serverDocumentIndex)
	}

	hasClientBlocks := func() bool {
		return clientBlocksIndex < len(clientStream.BlocksIndexes)
	}
	hasServerBlocks := func() bool {
		return serverBlocksIndex < len(serverStream.BlocksIndexes)
	}

	if isPwntools {
		if format.Format == "base32" || format.Format == "base64" {
			sb.WriteString("import base64\n")
		}
		sb.WriteString("from pwn import *\n\n")
		sb.WriteString(fmt.Sprintf("p = remote('%s', %d)\n", connection.DestinationIP, connection.DestinationPort))
	}

	lastIsClient, lastIsServer := true, true
	for !clientStream.ID.IsZero() || !serverStream.ID.IsZero() {
		if hasClientBlocks() && (!hasServerBlocks() || // next payload is from client
			clientStream.BlocksTimestamps[clientBlocksIndex].UnixNano() <=
				serverStream.BlocksTimestamps[serverBlocksIndex].UnixNano()) {
			start := clientStream.BlocksIndexes[clientBlocksIndex]
			end := 0
			if clientBlocksIndex < len(clientStream.BlocksIndexes)-1 {
				end = clientStream.BlocksIndexes[clientBlocksIndex+1]
			} else {
				end = len(clientStream.Payload)
			}

			if !lastIsClient {
				sb.WriteString("\n")
			}
			lastIsClient = true
			lastIsServer = false
			if isPwntools {
				sb.WriteString(decodePwntools(clientStream.Payload[start:end], true, format.Format))
			} else {
				sb.WriteString(DecodeBytes(clientStream.Payload[start:end], format.Format))
			}
			clientBlocksIndex++
		} else { // next payload is from server
			start := serverStream.BlocksIndexes[serverBlocksIndex]
			end := 0
			if serverBlocksIndex < len(serverStream.BlocksIndexes)-1 {
				end = serverStream.BlocksIndexes[serverBlocksIndex+1]
			} else {
				end = len(serverStream.Payload)
			}

			if !lastIsServer {
				sb.WriteString("\n")
			}
			lastIsClient = false
			lastIsServer = true
			if isPwntools {
				sb.WriteString(decodePwntools(serverStream.Payload[start:end], false, format.Format))
			} else {
				sb.WriteString(DecodeBytes(serverStream.Payload[start:end], format.Format))
			}
			serverBlocksIndex++
		}

		if includeClient && !hasClientBlocks() {
			clientDocumentIndex++
			clientBlocksIndex = 0
			clientStream = csc.getConnectionStream(c, connectionID, true, clientDocumentIndex)
		}
		if includeServer && !hasServerBlocks() {
			serverDocumentIndex++
			serverBlocksIndex = 0
			serverStream = csc.getConnectionStream(c, connectionID, false, serverDocumentIndex)
		}
	}

	return sb.String(), true
}

func (csc ConnectionStreamsController) getConnection(c context.Context, connectionID RowID) Connection {
	var connection Connection
	if err := csc.storage.Find(Connections).Context(c).Filter(OrderedDocument{{"_id", connectionID}}).
		First(&connection); err != nil {
		log.WithError(err).WithField("id", connectionID).Panic("failed to get connection")
	}
	return connection
}

func (csc ConnectionStreamsController) getConnectionStream(c context.Context, connectionID RowID, fromClient bool,
	documentIndex int) ConnectionStream {
	var result ConnectionStream
	if err := csc.storage.Find(ConnectionStreams).Filter(OrderedDocument{
		{"connection_id", connectionID},
		{"from_client", fromClient},
		{"document_index", documentIndex},
	}).Context(c).First(&result); err != nil {
		log.WithError(err).WithField("connection_id", connectionID).Panic("failed to get a ConnectionStream")
	}
	return result
}

func findMatchesBetween(patternMatches map[uint][]PatternSlice, from, to uint64) []RegexSlice {
	regexSlices := make([]RegexSlice, 0, initialRegexSlicesCount)
	for _, slices := range patternMatches {
		for _, slice := range slices {
			if from > slice[1] || to <= slice[0] {
				continue
			}

			var start, end uint64
			if from > slice[0] {
				start = 0
			} else {
				start = slice[0] - from
			}

			if to <= slice[1] {
				end = to - from
			} else {
				end = slice[1] - from
			}

			regexSlices = append(regexSlices, RegexSlice{From: start, To: end})
		}
	}
	return regexSlices
}

func decodePwntools(payload []byte, isClient bool, format string) string {
	if !isClient && len(payload) > pwntoolsMaxServerBytes {
		payload = payload[len(payload)-pwntoolsMaxServerBytes:]
	}

	var content string
	switch format {
	case "hex":
		content = fmt.Sprintf("bytes.fromhex('%s')", DecodeBytes(payload, format))
	case "base32":
		content = fmt.Sprintf("base64.b32decode('%s')", DecodeBytes(payload, format))
	case "base64":
		content = fmt.Sprintf("base64.b64decode('%s')", DecodeBytes(payload, format))
	default:
		content = fmt.Sprintf("'%s'", strings.Replace(DecodeBytes(payload, "ascii"), "'", "\\'", -1))
	}

	if isClient {
		return fmt.Sprintf("p.send(%s)\n", content)
	}

	return fmt.Sprintf("p.recvuntil(%s)\n", content)
}