This repository has been archived by the owner on Apr 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
main.go
398 lines (332 loc) · 10 KB
/
main.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package main
import (
"crypto/tls"
"encoding/hex"
"flag"
"fmt"
"github.com/gorilla/websocket"
"github.com/praetorian-inc/trudy/listener"
"github.com/praetorian-inc/trudy/module"
"github.com/praetorian-inc/trudy/pipe"
"io"
"log"
"net"
"net/http"
"strings"
"sync"
)
var connectionCount uint
var websocketConn *websocket.Conn
var websocketMutex *sync.Mutex
var tlsConfig *tls.Config
func main() {
var tcpport string
var tlsport string
var x509 string
var key string
var showConnectionAttempts bool
flag.StringVar(&tcpport, "tcp", "6666", "Listening port for non-TLS connections.")
flag.StringVar(&tlsport, "tls", "6443", "Listening port for TLS connections.")
flag.StringVar(&x509, "x509", "./certificate/trudy.cer", "Path to x509 certificate that will be presented for TLS connection.")
flag.StringVar(&key, "key", "./certificate/trudy.key", "Path to the corresponding private key for the specified x509 certificate")
flag.BoolVar(&showConnectionAttempts, "show", true, "Show connection open and close messages")
flag.Parse()
tcpport = ":" + tcpport
tlsport = ":" + tlsport
setup(tcpport, tlsport, x509, key, showConnectionAttempts)
}
func setup(tcpport, tlsport, x509, key string, show bool) {
//Setup non-TLS TCP listener!
tcpAddr, err := net.ResolveTCPAddr("tcp", tcpport)
if err != nil {
log.Printf("There appears to be an error with the TCP port you specified. See error below.\n%v\n", err.Error())
return
}
tcpListener := new(listener.TCPListener)
//Setup TLS listener!
trdy, err := tls.LoadX509KeyPair(x509, key)
if err != nil {
log.Printf("There appears to be an error with the x509 or key values specified. See error below.\n%v\n", err.Error())
return
}
tlsConfig = &tls.Config{
Certificates: []tls.Certificate{trdy},
InsecureSkipVerify: true,
}
tlsAddr, err := net.ResolveTCPAddr("tcp", tlsport)
if err != nil {
log.Printf("There appears to be an error with the TLS port specified. See error below.\n%v\n", err.Error())
return
}
tlsListener := new(listener.TLSListener)
//All good. Start listening.
tcpListener.Listen("tcp", tcpAddr, &tls.Config{})
tlsListener.Listen("tcp", tlsAddr, tlsConfig)
log.Println("[INFO] Trudy lives!")
log.Printf("[INFO] Listening for TLS connections on port %s\n", tlsport)
log.Printf("[INFO] Listening for all other TCP connections on port %s\n", tcpport)
go websocketHandler()
go connectionDispatcher(tlsListener, "TLS", show)
connectionDispatcher(tcpListener, "TCP", show)
}
func connectionDispatcher(listener listener.TrudyListener, name string, show bool) {
defer listener.Close()
for {
fd, conn, err := listener.Accept()
if err != nil {
continue
}
p := new(pipe.TrudyPipe)
if name == "TLS" {
err = p.New(connectionCount, fd, conn, true)
} else {
err = p.New(connectionCount, fd, conn, false)
}
if err != nil {
log.Println("[ERR] Error creating new pipe.")
continue
}
if show {
log.Printf("[INFO] ( %v ) %v Connection accepted!\n", connectionCount, name)
}
go clientHandler(p, show)
go serverHandler(p)
connectionCount++
}
}
func errHandler(err error) {
if err != nil {
panic(err)
}
}
//clientHandler manages data that is sent from the client to the server.
func clientHandler(pipe pipe.Pipe, show bool) {
if show {
defer log.Printf("[INFO] ( %v ) Closing TCP connection.\n", pipe.Id())
}
defer pipe.Close()
buffer := make([]byte, 65535)
for {
bytesRead, clientReadErr := pipe.ReadFromClient(buffer)
if clientReadErr != io.EOF && clientReadErr != nil {
break
}
if clientReadErr != io.EOF && bytesRead == 0 {
continue
}
data := module.Data{FromClient: true,
Bytes: buffer[:bytesRead],
TLSConfig: tlsConfig,
ServerAddr: pipe.ServerInfo(),
ClientAddr: pipe.ClientInfo()}
data.Deserialize()
if data.Drop() {
continue
}
if data.DoMangle() {
data.Mangle()
bytesRead = len(data.Bytes)
}
if data.DoIntercept() {
if websocketConn == nil {
log.Printf("[ERR] Websocket Connection has not been setup yet! Cannot intercept.")
continue
}
websocketMutex.Lock()
bs := fmt.Sprintf("% x", data.Bytes)
if err := websocketConn.WriteMessage(websocket.TextMessage, []byte(bs)); err != nil {
log.Printf("[ERR] Failed to write to websocket: %v\n", err)
websocketMutex.Unlock()
continue
}
_, moddedBytes, err := websocketConn.ReadMessage()
websocketMutex.Unlock()
if err != nil {
log.Printf("[ERR] Failed to read from websocket: %v\n", err)
continue
}
str := string(moddedBytes)
str = strings.Replace(str, " ", "", -1)
moddedBytes, err = hex.DecodeString(str)
if err != nil {
log.Printf("[ERR] Failed to decode hexedited data.")
continue
}
data.Bytes = moddedBytes
bytesRead = len(moddedBytes)
}
if data.DoPrint() {
log.Printf("%v -> %v\n%v\n", data.ClientAddr.String(), data.ServerAddr.String(), data.PrettyPrint())
}
data.Serialize()
data.BeforeWriteToServer(pipe)
bytesRead = len(data.Bytes)
_, serverWriteErr := pipe.WriteToServer(data.Bytes[:bytesRead])
if serverWriteErr != nil || clientReadErr == io.EOF {
break
}
data.AfterWriteToServer(pipe)
}
}
//serverHandler manages data that is sent from the server to the client.
func serverHandler(pipe pipe.Pipe) {
buffer := make([]byte, 65535)
defer pipe.Close()
for {
bytesRead, serverReadErr := pipe.ReadFromServer(buffer)
if serverReadErr != io.EOF && serverReadErr != nil {
break
}
if serverReadErr != io.EOF && bytesRead == 0 {
continue
}
data := module.Data{FromClient: false,
Bytes: buffer[:bytesRead],
TLSConfig: tlsConfig,
ClientAddr: pipe.ClientInfo(),
ServerAddr: pipe.ServerInfo()}
data.Deserialize()
if data.Drop() {
continue
}
if data.DoMangle() {
data.Mangle()
bytesRead = len(data.Bytes)
}
if data.DoIntercept() {
if websocketConn == nil {
log.Printf("[ERR] Websocket Connection has not been setup yet! Cannot intercept.")
continue
}
websocketMutex.Lock()
bs := fmt.Sprintf("% x", data.Bytes)
if err := websocketConn.WriteMessage(websocket.TextMessage, []byte(bs)); err != nil {
log.Printf("[ERR] Failed to write to websocket: %v\n", err)
websocketMutex.Unlock()
continue
}
_, moddedBytes, err := websocketConn.ReadMessage()
websocketMutex.Unlock()
if err != nil {
log.Printf("[ERR] Failed to read from websocket: %v\n", err)
continue
}
str := string(moddedBytes)
str = strings.Replace(str, " ", "", -1)
moddedBytes, err = hex.DecodeString(str)
if err != nil {
log.Printf("[ERR] Failed to decode hexedited data.")
continue
}
data.Bytes = moddedBytes
bytesRead = len(moddedBytes)
}
if data.DoPrint() {
log.Printf("%v -> %v\n%v\n", data.ServerAddr.String(), data.ClientAddr.String(), data.PrettyPrint())
}
data.Serialize()
data.BeforeWriteToClient(pipe)
bytesRead = len(data.Bytes)
_, clientWriteErr := pipe.WriteToClient(data.Bytes[:bytesRead])
if clientWriteErr != nil || serverReadErr == io.EOF {
break
}
data.AfterWriteToClient(pipe)
}
}
func websocketHandler() {
websocketMutex = &sync.Mutex{}
upgrader := websocket.Upgrader{ReadBufferSize: 65535, WriteBufferSize: 65535}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, editor)
})
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
var err error
websocketConn, err = upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("[ERR] Could not upgrade websocket connection.")
return
}
})
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
}
const editor string = `<!-- this wonderful page was found here: https://github.com/xem/hex -->
<body onload='
// Reset the textarea value
m.value="00";
// Init the top cell content
for(i=0;i<16;i++)
t.innerHTML+=(0+i.toString(16)).slice(-2)+" ";
'>
<!-- TRUDY SPECIFIC CODE ADDED FOR THIS PROJECT -->
<h1> ~ Trudy Intercept ~ </h1>
<script>
var url = window.location.href
var arr = url.split("/");
var ws_url = "ws://" + arr[2] + "/ws"
var socket = new WebSocket(ws_url)
socket.onmessage = function (event) {
document.getElementById('m').value = event.data
document.getElementById('m').oninput()
document.getElementById('send').disabled = false
}
var sender = function() {
socket.send(document.getElementById('m').value)
document.getElementById('send').disabled = true
document.getElementById('m').value = "00"
document.getElementById('m').oninput()
}
</script>
<button onclick="sender()" id='send' disabled=true>send</button>
<!-- END TRUDY SPECIFIC CODE -->
</body>
<table border><td><pre><td id=t><tr><td id=l width=80>00000000<td><textarea spellcheck=false id=m oninput='
// On input, store the length of clean hex before the textarea caret in b
b=value
.substr(0,selectionStart)
.replace(/[^0-9A-F]/ig,"")
.replace(/(..)/g,"$1 ")
.length;
// Clean the textarea value
value=value
.replace(/[^0-9A-F]/ig,"")
.replace(/(..)/g,"$1 ")
.replace(/ $/,"")
.toUpperCase();
// Set the height of the textarea according to its length
style.height=(1.5+value.length/47)+"em";
// Reset h
h="";
// Loop on textarea lines
for(i=0;i<value.length/48;i++)
// Add line number to h
h+=(1E7+(16*i).toString(16)).slice(-8)+" ";
// Write h on the left column
l.innerHTML=h;
// Reset h
h="";
// Loop on the hex values
for(i=0;i<value.length;i+=3)
// Convert them in numbers
c=parseInt(value.substr(i,2),16),
// Convert in chars (if the charCode is in [64-126] (maybe more later)) or ".".
h=63<c&&127>c?h+String.fromCharCode(c):h+".";
// Write h in the right column (with line breaks every 16 chars)
r.innerHTML=h.replace(/(.{16})/g,"$1 ");
// If the caret position is after a space or a line break, place it at the previous index so we can use backspace to erase hex code
if(value[b]==" ")
b--;
// Put the textarea caret at the right place
setSelectionRange(b,b)'
cols=48></textarea><td width=160 id=r>.</td>
</table>
<style>
*{margin:0;padding:0;vertical-align:top;font:1em/1em courier}
#m{height:1.5em;resize:none;overflow:hidden}
#t{padding:0 2px}
#w{position:absolute;opacity:.001}
</style>
`