-
Notifications
You must be signed in to change notification settings - Fork 10
/
wgit.go
657 lines (579 loc) · 19.7 KB
/
wgit.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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
package mwgp
import (
"bytes"
"encoding/binary"
"fmt"
"golang.zx2c4.com/wireguard/device"
"log"
"math/rand"
"net"
"sync"
"sync/atomic"
"time"
)
type Peer struct {
// the index the client told us whom CLIENT is
// in MessageInitiation.Sender (client -> us, register)
// in MessageResponse.Receiver (us -> client, translate)
// in MessageCookieReply.Receiver (us -> client, translate)
// in MessageTransport(s->c).Receiver (us -> client, translate)
clientOriginIndex uint32
// the index we told server whom CLIENT is
// in MessageInitiation.Sender (us -> server, translate)
// in MessageResponse.Receiver (server -> us, match)
// in MessageCookieReply.Receiver (server -> us, match)
// in MessageTransport(s->c).Receiver (server -> us, match)
clientProxyIndex uint32
// the index the server told us whom SERVER is
// in MessageResponse.Sender (server -> us, register)
// in MessageTransport(c->s).Receiver (us -> server, translate)
serverOriginIndex uint32
// the index we told client whom SERVER is
// in MessageResponse.Sender (us -> client, translate)
// in MessageTransport(c->s).Receiver (client -> us, match)
serverProxyIndex uint32
// the cookie generator initialized with the server public key
// used to generate mac{1,2} for MessageInitialize(c->s)
clientCookieGenerator device.CookieGenerator
clientPublicKey NoisePublicKey
// the cookie generator initialized with the client public key
// used to generate mac{1,2} for MessageResponse(s->c)
serverCookieGenerator device.CookieGenerator
serverPublicKey NoisePublicKey
clientDestination *net.UDPAddr
serverDestination *net.UDPAddr
lastActive atomic.Value // time.Time
clientSourceValidateLevel int
serverSourceValidateLevel int
obfuscateEnabled bool
}
func (p *Peer) IsServerReplied() bool {
return p.serverProxyIndex != 0
}
type WireGuardIndexTranslationTable struct {
// client <-> us
clientConn *net.UDPConn
ClientListen *net.UDPAddr
ClientReadFromUDPFunc func(conn *net.UDPConn, packet *Packet) (err error)
ClientWriteToUDPFunc func(conn *net.UDPConn, packet *Packet) (err error)
clientReadChan chan *Packet
clientWriteChan chan *Packet
// us <-> server
serverConn *net.UDPConn
ServerListen *net.UDPAddr
ServerReadFromUDPFunc func(conn *net.UDPConn, packet *Packet) (err error)
ServerWriteToUDPFunc func(conn *net.UDPConn, packet *Packet) (err error)
serverReadChan chan *Packet
serverWriteChan chan *Packet
Timeout time.Duration
ExtractPeerFunc func(msg *device.MessageInitiation) (fi *ServerConfigPeer, err error)
CacheJar WGITCacheJar
// clientProxyIndex -> Peer
clientMap map[uint32]*Peer
// serverProxyIndex -> Peer
serverMap map[uint32]*Peer
mapLock sync.RWMutex
expireChan <-chan time.Time
packetPool sync.Pool
// UpdateAllServerDestinationChan is used to set all server address for mwgp-client (in case of DNS update).
// this channel is not intended to be used by mwgp-server.
UpdateAllServerDestinationChan chan *net.UDPAddr
// MaxPacketSize is the maximum size of a WireGuard packet.
//
// We use the default value of 65536, which is the maximum possible size of a UDP packet.
//
// However, in most cases, 1500 is sufficient because WireGuard will only send
// large UDP packets when you configure a large MTU on the WireGuard interface.
//
// If you are running mwgp on a server with limited memory, you can adjust this to
// reduce memory consumption.
MaxPacketSize uint
}
func defaultReadFromUDPFunc(conn *net.UDPConn, packet *Packet) (err error) {
packet.Length, packet.Source, err = conn.ReadFromUDP(packet.Data[:])
if err != nil {
return
}
return
}
func defaultWriteToUDPFunc(conn *net.UDPConn, packet *Packet) (err error) {
_, err = conn.WriteToUDP(packet.Slice(), packet.Destination)
if err != nil {
return
}
return
}
func NewWireGuardIndexTranslationTable() (table *WireGuardIndexTranslationTable) {
table = &WireGuardIndexTranslationTable{
ClientReadFromUDPFunc: defaultReadFromUDPFunc,
ServerReadFromUDPFunc: defaultReadFromUDPFunc,
ClientWriteToUDPFunc: defaultWriteToUDPFunc,
ServerWriteToUDPFunc: defaultWriteToUDPFunc,
clientReadChan: make(chan *Packet, 64),
clientWriteChan: make(chan *Packet, 64),
serverReadChan: make(chan *Packet, 64),
serverWriteChan: make(chan *Packet, 64),
Timeout: 60 * time.Second,
clientMap: make(map[uint32]*Peer),
serverMap: make(map[uint32]*Peer),
UpdateAllServerDestinationChan: make(chan *net.UDPAddr),
MaxPacketSize: defaultMaxPacketSize,
}
table.packetPool.New = func() interface{} {
return &Packet{
Data: make([]byte, table.MaxPacketSize),
}
}
return
}
func (t *WireGuardIndexTranslationTable) Serve() (err error) {
cerr := t.CacheJar.LoadLocked(t.serverMap, t.clientMap)
if cerr != nil {
log.Printf("[warn] forward table cache not loaded: %s\n", cerr.Error())
}
t.clientConn, err = net.ListenUDP("udp", t.ClientListen)
if err != nil {
err = fmt.Errorf("failed to listen on client addr %s: %w", t.ClientListen, err)
return
}
t.serverConn, err = net.ListenUDP("udp", t.ServerListen)
if err != nil {
err = fmt.Errorf("failed to listen on server addr %s: %w", t.ServerListen, err)
return
}
t.expireChan = time.Tick(t.Timeout)
go t.writeLoop()
go t.serverReadLoop()
go t.clientReadLoop()
t.mainLoop()
return
}
func (t *WireGuardIndexTranslationTable) clientReadLoop() {
for {
packet := t.obtainPacket()
err := t.ClientReadFromUDPFunc(t.clientConn, packet)
if err != nil {
log.Printf("[error] failed to read from client conn: %s\n", err.Error())
t.recyclePacket(packet)
continue
}
t.clientReadChan <- packet
}
}
func (t *WireGuardIndexTranslationTable) serverReadLoop() {
for {
packet := t.obtainPacket()
err := t.ServerReadFromUDPFunc(t.serverConn, packet)
if err != nil {
log.Printf("[error] failed to read from server conn: %s\n", err.Error())
t.recyclePacket(packet)
continue
}
t.serverReadChan <- packet
}
}
func (t *WireGuardIndexTranslationTable) writeLoop() {
for {
select {
case packet := <-t.clientWriteChan:
err := t.ClientWriteToUDPFunc(t.clientConn, packet)
if err != nil {
log.Printf("[error] failed to write to client conn dest=%s: %s\n", packet.Destination.String(), err.Error())
}
t.recyclePacket(packet)
case packet := <-t.serverWriteChan:
err := t.ServerWriteToUDPFunc(t.serverConn, packet)
if err != nil {
log.Printf("[error] failed to write to server conn dest=%s: %s\n", packet.Destination.String(), err.Error())
}
t.recyclePacket(packet)
}
}
}
func (t *WireGuardIndexTranslationTable) mainLoop() {
for {
select {
case packet := <-t.clientReadChan:
if packet.MessageType() == device.MessageTransportType {
t.handleClientPacket(packet)
} else {
go t.handleClientPacket(packet)
}
case packet := <-t.serverReadChan:
if packet.MessageType() == device.MessageTransportType {
t.handleServerPacket(packet)
} else {
go t.handleServerPacket(packet)
}
case current := <-t.expireChan:
t.handlePeersExpireCheck(current)
case newServerAddr := <-t.UpdateAllServerDestinationChan:
t.handleAllServerDestinationUpdate(newServerAddr)
}
}
}
func (t *WireGuardIndexTranslationTable) handleClientPacket(packet *Packet) {
packetForwarded := false
defer func() {
if !packetForwarded {
t.recyclePacket(packet)
}
}()
var err error
var peer *Peer
switch packet.MessageType() {
case device.MessageInitiationType:
var msg device.MessageInitiation
reader := bytes.NewReader(packet.Slice())
err = binary.Read(reader, binary.LittleEndian, &msg)
if err != nil {
break
}
peer, err = t.processClientMessageInitiation(packet.Source, &msg)
if err != nil {
break
}
// for mwgp-server only, mwgp-client won't match this since its client would be official WireGuard
if packet.Flags&PacketFlagDeobfuscatedAfterReceived != 0 {
peer.obfuscateEnabled = true
}
case device.MessageTransportType:
peer, err = t.processMessageTransport(packet, false)
default:
err = fmt.Errorf("unexcepted message type %d", packet.MessageType())
}
if err != nil {
log.Printf("[info] failed to handle type %d packet from client %s: %s\n", packet.MessageType(), packet.Source.String(), err.Error())
return
}
if peer == nil {
log.Panicf("[fatal] err == nil && peer == nil, there must be a bug in the code\n")
return
}
switch packet.MessageType() {
case device.MessageInitiationType:
if peer.clientOriginIndex != peer.clientProxyIndex {
err = packet.SetSenderIndex(peer.clientProxyIndex)
packet.FixMACs(&peer.clientCookieGenerator)
}
case device.MessageTransportType:
err = packet.SetReceiverIndex(peer.serverOriginIndex)
}
if err != nil {
log.Printf("[error] failed to patch type %d packet from client %s: %s\n", packet.MessageType(), packet.Source.String(), err.Error())
return
}
packet.Destination = peer.serverDestination
t.serverWriteChan <- packet
packetForwarded = true
}
func (t *WireGuardIndexTranslationTable) handleServerPacket(packet *Packet) {
packetForwarded := false
defer func() {
if !packetForwarded {
t.recyclePacket(packet)
}
}()
var err error
var peer *Peer
switch packet.MessageType() {
case device.MessageResponseType:
var msg device.MessageResponse
reader := bytes.NewReader(packet.Slice())
err = binary.Read(reader, binary.LittleEndian, &msg)
if err != nil {
break
}
peer, err = t.processServerMessageResponse(packet.Source, &msg)
if err != nil {
break
}
case device.MessageCookieReplyType:
var msg device.MessageCookieReply
reader := bytes.NewReader(packet.Slice())
err = binary.Read(reader, binary.LittleEndian, &msg)
if err != nil {
break
}
peer, err = t.processServerMessageCookieReply(packet.Source, &msg)
if err != nil {
break
}
// still pass-through to client to for the MessageInitiation resending
case device.MessageTransportType:
peer, err = t.processMessageTransport(packet, true)
default:
err = fmt.Errorf("unexcepted message type %d", packet.MessageType())
}
if err != nil {
log.Printf("[info] failed to handle type %d packet from server %s: %s\n", packet.MessageType(), packet.Source.String(), err.Error())
return
}
if peer == nil {
log.Panicf("[fatal] err == nil && peer == nil, there must be a bug in the code\n")
return
}
switch packet.MessageType() {
case device.MessageResponseType:
if peer.serverOriginIndex != peer.serverProxyIndex || peer.clientOriginIndex != peer.clientProxyIndex {
err = packet.SetSenderIndex(peer.serverProxyIndex)
if err != nil {
break
}
err = packet.SetReceiverIndex(peer.clientOriginIndex)
if err != nil {
break
}
packet.FixMACs(&peer.serverCookieGenerator)
}
case device.MessageCookieReplyType:
fallthrough
case device.MessageTransportType:
err = packet.SetReceiverIndex(peer.clientOriginIndex)
}
if err != nil {
log.Printf("[error] failed to patch type %d packet from server %s: %s\n", packet.MessageType(), packet.Source.String(), err.Error())
return
}
// for mwgp-server only
if peer.obfuscateEnabled {
packet.Flags |= PacketFlagObfuscateBeforeSend
}
packet.Destination = peer.clientDestination
t.clientWriteChan <- packet
packetForwarded = true
}
func (t *WireGuardIndexTranslationTable) processClientMessageInitiation(src *net.UDPAddr, msg *device.MessageInitiation) (peer *Peer, err error) {
// the MessageInitiation is the only message we can decrypt.
sp, err := t.ExtractPeerFunc(msg)
if err != nil {
return
}
if sp == nil {
log.Panicf("[fatal] ExtractPeerFunc must return a non-nil sp when err == nil\n")
return
}
peer = &Peer{}
peer.clientPublicKey = *sp.ClientPublicKey
peer.clientCookieGenerator.Init(sp.serverPublicKey.NoisePublicKey)
peer.serverPublicKey = sp.serverPublicKey
peer.serverCookieGenerator.Init(sp.ClientPublicKey.NoisePublicKey)
peer.clientOriginIndex = msg.Sender
peer.clientDestination = src
peer.serverDestination = sp.forwardToAddress
peer.clientSourceValidateLevel = sp.ClientSourceValidateLevel
peer.lastActive.Store(time.Now())
t.mapLock.Lock()
peer.clientProxyIndex = t.generateProxyIndexLocked(t.clientMap, peer.clientOriginIndex)
t.clientMap[peer.clientProxyIndex] = peer
t.mapLock.Unlock()
log.Printf("[info] received message initiation from client, peer create stage #1: %s(idx:%08x->%08x) <=> %s\n",
peer.clientDestination.String(), peer.clientOriginIndex, peer.clientProxyIndex,
peer.serverDestination.String())
return
}
func (t *WireGuardIndexTranslationTable) processServerMessageResponse(src *net.UDPAddr, msg *device.MessageResponse) (peer *Peer, err error) {
// we cannot decrypt the MessageResponse, but we need to handle the sender_index from server.
if msg.Receiver == 0 {
err = fmt.Errorf("received message hanndshake_response from server %s with impossible receiver_index=0", src.String())
return
}
// make sure the client won't be removed from clientMap
// before we added it into serverMap in a raced condition (otherwise the peer will leak).
// so we cannot use RLock()+RUnLock()+Lock() here.
t.mapLock.Lock()
defer t.mapLock.Unlock()
var ok bool
if peer, ok = t.clientMap[msg.Receiver]; ok {
peer.lastActive.Store(time.Now())
peer.serverOriginIndex = msg.Sender
peer.serverProxyIndex = t.generateProxyIndexLocked(t.serverMap, peer.serverOriginIndex)
t.serverMap[peer.serverProxyIndex] = peer
log.Printf("[info] received message response from server, peer create stage #2: %s(idx:%08x->%08x) <=> %s(idx:%08x->%08x)\n",
peer.clientDestination.String(), peer.clientOriginIndex, peer.clientProxyIndex,
peer.serverDestination.String(), peer.serverOriginIndex, peer.serverProxyIndex)
go t.persistForwardTableCache()
return
}
err = fmt.Errorf("no matched peer found for clientMap[%08x], referred by MessageResponse.Receiver from server %s", msg.Receiver, src.String())
return
}
func (t *WireGuardIndexTranslationTable) processServerMessageCookieReply(src *net.UDPAddr, msg *device.MessageCookieReply) (peer *Peer, err error) {
if msg.Receiver == 0 {
err = fmt.Errorf("received message cookie_reply from server %s with impossible receiver_index=0", src.String())
return
}
var ok bool
t.mapLock.RLock()
peer, ok = t.clientMap[msg.Receiver]
t.mapLock.RUnlock()
if !ok {
err = fmt.Errorf("no matched peer found for clientMap[%08x], referred by MessageCookieReply.Receiver from server %s", msg.Receiver, src.String())
return
}
ok = peer.clientCookieGenerator.ConsumeReply(msg)
if !ok {
err = fmt.Errorf("failed to consume cookie reply from server %s", src.String())
return
}
return
}
func (t *WireGuardIndexTranslationTable) processMessageTransport(packet *Packet, s2c bool) (peer *Peer, err error) {
// we cannot decrypt MessageTransport,
// but their receiver_index has the same offset and that is the only information we need
receiverIndex, err := packet.ReceiverIndex()
if err != nil {
return
}
if receiverIndex == 0 {
if s2c {
err = fmt.Errorf("received message transport from server %s with impossible receiver_index=0", packet.Source.String())
} else {
err = fmt.Errorf("received message transport from client %s with impossible receiver_index=0", packet.Source.String())
}
return
}
var m map[uint32]*Peer
if s2c {
m = t.clientMap
} else {
m = t.serverMap
}
var ok bool
t.mapLock.RLock()
peer, ok = m[receiverIndex]
t.mapLock.RUnlock()
if !ok {
if s2c {
err = fmt.Errorf("no matched peer found for clientMap[%08x], referred by packet from server %s", receiverIndex, packet.Source.String())
} else {
err = fmt.Errorf("no matched peer found for serverMap[%08x], referred by packet from client %s", receiverIndex, packet.Source.String())
}
return
}
peer.lastActive.Store(time.Now())
if s2c {
// in case of udp out-of-order (seems not possible to happen)
if peer.IsServerReplied() {
ipChanged := !packet.Source.IP.Equal(peer.serverDestination.IP)
portChanged := packet.Source.Port != peer.serverDestination.Port
switch peer.serverSourceValidateLevel {
case SourceValidateLevelIP:
if ipChanged {
err = fmt.Errorf("server IP mismatch (for client %s), expected %s, got %s",
peer.clientDestination,
peer.serverDestination.IP.String(),
packet.Source.IP.String())
return
}
case SourceValidateLevelDefault:
fallthrough
case SourceValidateLevelIPAndPort:
if ipChanged || portChanged {
err = fmt.Errorf("server IP/port mismatch (for server %s), expected %s:%d, got %s:%d",
peer.clientDestination,
peer.serverDestination.IP.String(), peer.serverDestination.Port,
packet.Source.IP.String(), packet.Source.Port)
return
}
}
if ipChanged || portChanged {
log.Printf("[info] allowed server reply from another source: %s => %s\n", peer.clientDestination.String(), packet.Source.String())
}
}
} else {
ipChanged := !packet.Source.IP.Equal(peer.clientDestination.IP)
portChanged := packet.Source.Port != peer.clientDestination.Port
switch peer.clientSourceValidateLevel {
case SourceValidateLevelIP:
if ipChanged {
err = fmt.Errorf("client IP mismatch (for server %s), expected %s, got %s",
peer.serverDestination,
peer.clientDestination.IP.String(),
packet.Source.IP.String())
return
}
case SourceValidateLevelIPAndPort:
if ipChanged || portChanged {
err = fmt.Errorf("client IP/port mismatch (for server %s), expected %s:%d, got %s:%d",
peer.serverDestination,
peer.clientDestination.IP.String(), peer.clientDestination.Port,
packet.Source.IP.String(), packet.Source.Port)
return
}
}
if ipChanged || portChanged {
log.Printf("[info] allowed client romaing: %s => %s\n", peer.clientDestination.String(), packet.Source.String())
peer.clientDestination = packet.Source
}
}
return
}
func (t *WireGuardIndexTranslationTable) generateProxyIndexLocked(m map[uint32]*Peer, origin uint32) (proxy uint32) {
if !DebugAlwaysGenerateProxyIndex {
proxy = origin
}
validate := func(proxy uint32) bool {
// proxy index also cannot be 0, since the zero-value indicates the peer is not yet initialized
if proxy == 0 {
return false
}
if _, ok := m[proxy]; ok {
return false
}
return true
}
if validate(proxy) {
return
}
// spread the generated index to avoid collision
proxy = rand.Uint32()
for {
if validate(proxy) {
break
}
proxy++
}
return
}
func (t *WireGuardIndexTranslationTable) handlePeersExpireCheck(current time.Time) {
defer func() {
go t.persistForwardTableCache()
}()
t.mapLock.Lock()
defer t.mapLock.Unlock()
for _, peer := range t.clientMap {
if peer.lastActive.Load().(time.Time).Before(current.Add(-t.Timeout)) {
delete(t.clientMap, peer.clientProxyIndex)
delete(t.serverMap, peer.serverProxyIndex)
log.Printf("[info] expire peer %s (idx:%08x->%08x) <=> %s (idx:%08x->%08x)\n",
peer.clientDestination.String(), peer.clientOriginIndex, peer.clientProxyIndex,
peer.serverDestination.String(), peer.serverOriginIndex, peer.serverProxyIndex)
}
}
}
func (t *WireGuardIndexTranslationTable) handleAllServerDestinationUpdate(addr *net.UDPAddr) {
defer func() {
go t.persistForwardTableCache()
}()
t.mapLock.Lock()
defer t.mapLock.Unlock()
for _, peer := range t.clientMap {
peer.serverDestination = addr
}
}
func (t *WireGuardIndexTranslationTable) persistForwardTableCache() {
t.mapLock.RLock()
defer t.mapLock.RUnlock()
err := t.CacheJar.SaveLocked(t.serverMap)
if err != nil {
log.Printf("[error] failed to save forward table cache: %s\n", err)
}
}
func (t *WireGuardIndexTranslationTable) obtainPacket() *Packet {
return t.packetPool.Get().(*Packet)
}
func (t *WireGuardIndexTranslationTable) recyclePacket(packet *Packet) {
packet.Reset()
t.packetPool.Put(packet)
}