-
Notifications
You must be signed in to change notification settings - Fork 14
/
onionconnection.go
482 lines (396 loc) · 10.7 KB
/
onionconnection.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
// Copyright 2015 The GoTor Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"crypto/sha256"
"io"
"net"
)
const READ_QUEUE_LENGTH = 100
const WRITE_QUEUE_LENGTH = 2000
const CIRC_QUEUE_LENGTH = 2000
type CircReadQueue chan CircuitCommand
type OnionConnection struct {
parentOR *ORCtx
readQueue chan Cell
circuitReadQueue CircReadQueue
writeQueue chan []byte
circuits map[CircuitID]*Circuit
relayCircuits map[CircuitID]*RelayCircuit
usedTLSCtx *TorTLS
negotiatedVersion LinkVersion
isOutbound bool
weAuthenticated bool
theyAuthenticated bool
theirFingerprint Fingerprint
theirFingerprint256 []byte
}
func newOnionConnection(tlsctx *TorTLS, or *ORCtx) *OnionConnection {
StatsAddConnection()
return &OnionConnection{
usedTLSCtx: tlsctx,
circuits: make(map[CircuitID]*Circuit),
relayCircuits: make(map[CircuitID]*RelayCircuit),
readQueue: make(chan Cell, READ_QUEUE_LENGTH),
writeQueue: make(chan []byte, WRITE_QUEUE_LENGTH),
circuitReadQueue: make(CircReadQueue, CIRC_QUEUE_LENGTH),
parentOR: or,
}
}
func (c *OnionConnection) cleanup() {
StatsRemoveConnection()
if c.theyAuthenticated {
if err := c.parentOR.EndConnection(c.theirFingerprint, c); err != nil {
Log(LOG_NOTICE, "Warning during deregistration: %s", err)
}
}
close(c.writeQueue)
for _, circ := range c.relayCircuits {
c.destroyRelayCircuit(circ, true, false, DESTROY_REASON_OR_CONN_CLOSED)
}
c.relayCircuits = nil
for _, circ := range c.circuits {
c.destroyCircuit(circ, true, false, DESTROY_REASON_OR_CONN_CLOSED)
}
c.circuits = nil
// It is guaranteed that after calling EndConnection we will no longer receive any CircuitRequest
// So just process whatever was left.
readTheQueue:
for {
select {
case cmd := <-c.circuitReadQueue:
creationRequest, ok := cmd.(*CircuitRequest)
if ok {
creationRequest.successQueue <- &CircuitDestroyed{
reason: 8, // OR_CONN_CLOSED
id: creationRequest.localID,
//truncate: true,
}
}
cmd.ReleaseBuffers()
default:
break readTheQueue
}
}
}
func HandleORConnClient(or *ORCtx, conn net.Conn, req *CircuitRequest) {
// XXX WTF BUG: The Tor spec requires us to allow AUTHORIZE/VPADDING before VERSIONS
tlsConn, usedTLSCtx, err := or.WrapTLS(conn, true)
if err != nil {
Log(LOG_WARN, "%s", err)
if req != nil {
req.successQueue <- &CircuitDestroyed{
reason: 2, //INTERNAL
id: req.localID,
//truncate: true,
}
}
return
}
defer tlsConn.Close()
me := newOnionConnection(usedTLSCtx, or)
me.isOutbound = true
if req != nil {
me.circuitReadQueue <- req
req = nil
}
defer me.cleanup()
hash_inbound := sha256.New()
hash_outbound := sha256.New()
// Spawn the reader later - we still need to negotiate the version
go me.writer(tlsConn)
if err := me.negotiateVersionClient(tlsConn, hash_inbound, hash_outbound); err != nil {
Log(LOG_INFO, "%s", err)
return
}
go me.reader(tlsConn)
Log(LOG_CIRC, "Negotiated version %d", me.negotiatedVersion)
handshake:
for {
cell, ok := <-me.readQueue
if !ok {
Log(LOG_CIRC, "Connection closed")
return
}
hash_inbound.Write(cell.Bytes())
Log(LOG_CIRC, "pre-runloop got a %s", cell.Command())
switch cell.Command() {
case CMD_NETINFO:
me.sendNetinfo(hash_outbound)
break handshake
case CMD_PADDING, CMD_VPADDING:
// Ignore
case CMD_AUTH_CHALLENGE:
err := me.handleAuthChallenge(cell, hash_inbound, hash_outbound, tlsConn)
if err != nil {
Log(LOG_INFO, "%s", err)
return
}
case CMD_CERTS:
peerCert, err := tlsConn.PeerCertificate()
if err = me.handleCerts(cell, peerCert); err != nil {
Log(LOG_INFO, "%s", err)
return
}
default:
Log(LOG_NOTICE, "Cell %s not allowed. Disconnecting", cell.Command())
return
}
cell.ReleaseBuffers()
}
if me.theyAuthenticated {
if err := or.RegisterConnection(me.theirFingerprint, me); err != nil {
// No worries
Log(LOG_INFO, "register warning: %s", err)
}
}
hash_inbound = nil
hash_outbound = nil
me.Runloop()
}
func HandleORConnServer(or *ORCtx, conn net.Conn) {
tlsConn, usedTLSCtx, err := or.WrapTLS(conn, false)
if err != nil {
Log(LOG_WARN, "%s", err)
return
}
defer tlsConn.Close() // As soon as we leave this function, we make sure the connection is closed
me := newOnionConnection(usedTLSCtx, or)
me.isOutbound = false
defer me.cleanup()
// Spawn the reader later - we still need to negotiate the version
go me.writer(tlsConn)
if err := me.negotiateVersionServer(tlsConn); err != nil {
Log(LOG_INFO, "%s", err)
return
}
go me.reader(tlsConn)
Log(LOG_CIRC, "Negotiated version %d", me.negotiatedVersion)
if err := me.sendCerts(nil); err != nil {
Log(LOG_INFO, "%s", err)
return
}
me.weAuthenticated = true
if err := me.sendAuthChallenge(); err != nil {
Log(LOG_INFO, "%s", err)
return
}
if err := me.sendNetinfo(nil); err != nil {
Log(LOG_INFO, "%s", err)
return
}
handshake:
for {
cell, ok := <-me.readQueue
if !ok {
Log(LOG_INFO, "readqueue stopped working")
return
}
switch cell.Command() {
case CMD_AUTHORIZE, CMD_PADDING, CMD_VPADDING:
// Ignore
case CMD_CERTS:
if err := me.handleCerts(cell, nil); err != nil {
Log(LOG_INFO, "%s", err)
return
}
case CMD_AUTHENTICATE:
// XXX
case CMD_NETINFO:
// Good
break handshake
default:
// Not good
Log(LOG_NOTICE, "Unexpected %s - dropping connection", cell.Command())
return
}
cell.ReleaseBuffers()
}
me.Runloop()
}
func (me *OnionConnection) Runloop() {
Log(LOG_CIRC, "handshake done, runloop starting")
for {
var err ActionableError
var circID CircuitID // XXX This is messed up.
select {
case cell, ok := <-me.readQueue:
if !ok {
return
}
circID = cell.CircID()
if cell.Command() != CMD_PADDING {
Log(LOG_DEBUG, "%s got a %s: %v", me.theirFingerprint, cell.Command(), cell)
}
err = me.routeCellToFunction(cell)
cell.ReleaseBuffers()
case circData := <-me.circuitReadQueue:
circID = circData.CircID()
err = me.routeCircuitCommandToFunction(circData)
circData.ReleaseBuffers()
}
if err != nil {
switch err.Handle() {
case ERROR_CLOSE_CONNECTION:
Log(LOG_NOTICE, "Closing connection: %s", err)
return
case ERROR_CLOSE_CIRCUIT:
if circID == 0 {
Log(LOG_WARN, "Got a ERROR_CLOSE_CIRCUIT for CircID=0. Disconnecting")
return
}
me.writeQueue <- NewCell(me.negotiatedVersion, circID, CMD_DESTROY, []byte{byte(err.CircDestroyReason())}).Bytes()
if circID.MSB(me.negotiatedVersion) != me.isOutbound { // Front
circ, ok := me.circuits[circID]
if !ok {
Log(LOG_WARN, "Got a ERROR_CLOSE_CIRCUIT but don't know the circuit. Disconnecting. Original: %s", err)
return
}
me.destroyCircuit(circ, true, true, err.CircDestroyReason())
Log(LOG_NOTICE, "Closing circuit: %s", err)
} else {
circ, ok := me.relayCircuits[circID]
if !ok {
Log(LOG_WARN, "Got a ERROR_CLOSE_CIRCUIT but don't know the circuit. Disconnecting. Original: %s", err)
return
}
me.destroyRelayCircuit(circ, true, true, err.CircDestroyReason())
Log(LOG_NOTICE, "Closing relayCircuit: %s", err)
}
case ERROR_REFUSE_CIRCUIT:
if circID == 0 {
Log(LOG_WARN, "Got a ERROR_CLOSE_CIRCUIT for CircID=0. Disconnecting")
return
}
me.writeQueue <- NewCell(me.negotiatedVersion, circID, CMD_DESTROY, []byte{byte(err.CircDestroyReason())}).Bytes()
default:
Log(LOG_WARN, "Disconnecting: not sure what to do with error %v", err)
return
}
}
}
}
func (c *OnionConnection) reader(conn io.Reader) {
defer close(c.readQueue)
var buffer [SSLRecordSize]byte
readPos, decodePos := 0, 0
for {
bytes, err := conn.Read(buffer[readPos:])
if err != nil && bytes <= 0 {
Log(LOG_INFO, "%s", err)
return
}
readPos += bytes
circLen := 4
if c.negotiatedVersion < 4 {
circLen = 2
}
for decodePos+3+circLen < readPos { // while we have enough data to figure out command && length
if buffer[decodePos+circLen] == 7 || buffer[decodePos+circLen]&0x80 != 0 { // Variable length
varLen := (int(buffer[decodePos+circLen+1]) << 8) + int(buffer[decodePos+circLen+2])
varLen += circLen + 3 // Don't forget about the cell overhead
if varLen >= SSLRecordSize {
Log(LOG_INFO, "Dropping connection with variable-length cell that is WAY too large")
return
}
if readPos-decodePos >= varLen {
var varCell []byte
if varLen <= MAX_CELL_SIZE {
varCell = GetCellBuf(false)[0:varLen]
} else {
varCell = make([]byte, varLen)
}
copy(varCell, buffer[decodePos:decodePos+varLen])
decodePos += varLen
if c.negotiatedVersion < 4 {
c.readQueue <- (*Cell3)(&varCell)
} else {
c.readQueue <- (*Cell4)(&varCell)
}
} else {
break
}
} else { // Constant (514) length cell
if readPos-decodePos >= 510+circLen {
cell := GetCellBuf(false)
copy(cell, buffer[decodePos:decodePos+510+circLen])
cell = cell[0 : 510+circLen]
decodePos += 510 + circLen
if c.negotiatedVersion < 4 {
c.readQueue <- (*Cell3)(&cell)
} else {
c.readQueue <- (*Cell4)(&cell)
}
} else {
break
}
}
}
if decodePos == readPos {
decodePos = 0
readPos = 0
} else if decodePos > readPos {
panic("BUG: we decoded more than we read")
} else if decodePos != 0 {
copy(buffer[:], buffer[decodePos:readPos])
readPos -= decodePos
decodePos = 0
}
}
}
func (c *OnionConnection) writer(conn net.Conn) {
defer func() {
Log(LOG_INFO, "writer ended")
conn.Close()
}()
var buffer [SSLRecordSize]byte
var nextItem []byte
for {
if nextItem != nil {
_, err := conn.Write(nextItem)
if err != nil {
Log(LOG_INFO, "%s", err)
return
}
ReturnCellBuf(nextItem)
nextItem = nil
}
select {
case data, ok := <-c.writeQueue:
if !ok {
return
}
Log(LOG_DEBUG, "writing %d: %v", len(data), data)
datalen := len(data)
copy(buffer[:], data)
ReturnCellBuf(data)
extradata:
for { // See if we got any extra data
select {
case data2, ok := <-c.writeQueue:
if !ok {
break extradata
}
if datalen+len(data2) > cap(buffer) {
nextItem = data2
break extradata
}
copy(buffer[datalen:], data2)
datalen += len(data2)
ReturnCellBuf(data2)
if datalen+MAX_CELL_SIZE > cap(buffer) {
break extradata
}
default:
break extradata
}
}
_, err := conn.Write(buffer[:datalen])
if err != nil {
Log(LOG_INFO, "%s", err)
return
}
}
}
}