-
Notifications
You must be signed in to change notification settings - Fork 38
/
api.go
568 lines (482 loc) · 13.2 KB
/
api.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
// Package API handles the internal API running on all servers.
package api
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/netip"
"strconv"
"sync"
"golang.zx2c4.com/wireguard/device"
"golang.zx2c4.com/wireguard/tun/netstack"
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
"gvisor.dev/gvisor/pkg/tcpip"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv4"
"gvisor.dev/gvisor/pkg/tcpip/network/ipv6"
"wiretap/peer"
"wiretap/transport"
)
var nsLock sync.Mutex
var devLock sync.Mutex
var addressLock sync.Mutex
var indexLock sync.Mutex
var clientIndex uint64 = 0
var serverIndex uint64 = 0
type ServerConfigs struct {
RelayConfig *peer.Config
E2EEConfig *peer.Config
}
type InterfaceType int
const (
Relay InterfaceType = iota
E2EE
)
type NetworkState struct {
NextClientRelayAddr4 netip.Addr
NextClientRelayAddr6 netip.Addr
NextServerRelayAddr4 netip.Addr
NextServerRelayAddr6 netip.Addr
NextClientE2EEAddr4 netip.Addr
NextClientE2EEAddr6 netip.Addr
NextServerE2EEAddr4 netip.Addr
NextServerE2EEAddr6 netip.Addr
ApiAddr netip.Addr
ServerRelaySubnet4 netip.Addr
ServerRelaySubnet6 netip.Addr
}
type HostInterface struct {
Name string
Addrs []net.IPNet
}
type AddAllowedIPsRequest struct {
PublicKey wgtypes.Key
AllowedIPs []net.IPNet
}
type ExposeTuple struct {
RemoteAddr netip.Addr
LocalPort uint
RemotePort uint
Protocol string
}
type ExposeAction int
const (
ExposeActionExpose ExposeAction = iota
ExposeActionList
ExposeActionDelete
)
type ExposeRequest struct {
Action ExposeAction
LocalPort uint
RemotePort uint
Protocol string
Dynamic bool
}
type ExposeConn struct {
TcpListener *net.Listener
UdpConn *net.UDPConn
}
var clientAddresses map[uint64]NetworkState
var serverAddresses map[uint64]NetworkState
// Handle adds rule to top of firewall rules that accepts direct connections to API.
func Handle(tnet *netstack.Net, devRelay *device.Device, devE2EE *device.Device, relayConfig *peer.Config, e2eeConfig *peer.Config, addr netip.Addr, port uint16, lock *sync.Mutex, ns *NetworkState) {
configs := ServerConfigs{
RelayConfig: relayConfig,
E2EEConfig: e2eeConfig,
}
exposeMap := make(map[ExposeTuple]ExposeConn)
var exposeLock sync.RWMutex
serverAddresses = make(map[uint64]NetworkState)
clientAddresses = make(map[uint64]NetworkState)
serverAddresses[serverIndex] = *ns
ns.NextServerRelayAddr4 = ns.NextServerRelayAddr4.Next()
ns.NextServerRelayAddr6 = ns.NextServerRelayAddr6.Next()
ns.NextClientE2EEAddr4 = ns.NextClientE2EEAddr4.Next()
ns.NextClientE2EEAddr6 = ns.NextClientE2EEAddr6.Next()
ns.NextServerE2EEAddr4 = ns.NextServerE2EEAddr4.Next()
ns.NextServerE2EEAddr6 = ns.NextServerE2EEAddr6.Next()
ns.ApiAddr = ns.ApiAddr.Next()
serverIndex += 1
// Stand up API server.
listener, err := tnet.ListenTCP(&net.TCPAddr{IP: addr.AsSlice(), Port: int(port)})
if err != nil {
log.Panic(err)
}
localAddr := tcpip.FullAddress{
NIC: 1,
Addr: tcpip.AddrFromSlice(addr.AsSlice()),
}
http.HandleFunc("/ping", wrapApi(handlePing()))
http.HandleFunc("/serverinfo", wrapApi(handleServerInfo(configs)))
http.HandleFunc("/serverinterfaces", wrapApi(handleServerInterfaces()))
http.HandleFunc("/addpeer", wrapApi(handleAddPeer(devRelay, devE2EE, configs)))
http.HandleFunc("/allocate", wrapApi(handleAllocate(ns)))
http.HandleFunc("/addallowedips", wrapApi(handleAddAllowedIPs(devRelay, configs)))
http.HandleFunc("/expose", wrapApi(handleExpose(tnet, &exposeMap, &exposeLock, localAddr)))
log.Println("API: API listener up")
err = http.Serve(listener, nil)
if err != nil {
log.Panic(err)
}
}
// wrapAPI logs all API requests.
func wrapApi(f http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
log.Printf("(client %s) - API: %s", r.RemoteAddr, r.RequestURI)
f(w, r)
}
}
// writeErr sets status to 500, logs error, and writes error in response.
func writeErr(w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusInternalServerError)
_, err = io.WriteString(w, err.Error())
if err != nil {
log.Printf("API Error: %v", err)
}
}
// handlePing responds with pong message.
func handlePing() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_, err := io.WriteString(w, "pong")
if err != nil {
log.Printf("API Error: %v", err)
}
}
}
// handleServerInfo responds with the configs for this server.
func handleServerInfo(configs ServerConfigs) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
body, err := json.Marshal(configs)
if err != nil {
writeErr(w, err)
return
}
_, err = w.Write(body)
if err != nil {
log.Printf("API Error: %v", err)
}
}
}
// handleServerInterfaces responds with network interface information for this server.
func handleServerInterfaces() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var interfaces []HostInterface
ifs, err := net.Interfaces()
if err != nil {
log.Printf("API Error: %v", err)
}
for _, ifx := range ifs {
newIF := HostInterface{}
newIF.Name = ifx.Name
addrs, err := ifx.Addrs()
if err != nil {
log.Printf("API Error: %v", err)
}
for _, a := range addrs {
_, cidr, err := net.ParseCIDR(a.String())
if err != nil {
log.Printf("API Error: %v", err)
}
newIF.Addrs = append(newIF.Addrs, *cidr)
}
interfaces = append(interfaces, newIF)
}
body, err := json.Marshal(interfaces)
if err != nil {
writeErr(w, err)
return
}
_, err = w.Write(body)
if err != nil {
log.Printf("API Error: %v", err)
}
}
}
// handleAddPeer adds a peer to either this server's relay or e2ee device.
func handleAddPeer(devRelay *device.Device, devE2EE *device.Device, config ServerConfigs) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
interfaceParam, err := strconv.Atoi(r.URL.Query().Get("interface"))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
interfaceType := InterfaceType(interfaceParam)
if interfaceType != Relay && interfaceType != E2EE {
w.WriteHeader(http.StatusBadRequest)
return
}
var p peer.PeerConfig
body, err := io.ReadAll(r.Body)
if err != nil {
writeErr(w, err)
return
}
err = p.UnmarshalJSON(body)
if err != nil {
writeErr(w, err)
return
}
// If addresses not assigned, error out, should have been determined from a previous API call.
peerAddrs := p.GetAllowedIPs()
if len(peerAddrs) == 0 {
writeErr(w, errors.New("no addresses"))
return
}
fmt.Println()
fmt.Println(p.AsIPC())
var dev *device.Device
var c *peer.Config
switch interfaceType {
case Relay:
dev = devRelay
c = config.RelayConfig
case E2EE:
dev = devE2EE
c = config.E2EEConfig
}
devLock.Lock()
defer devLock.Unlock()
err = dev.IpcSet(p.AsIPC())
if err != nil {
writeErr(w, err)
return
}
c.AddPeer(p)
log.Printf("API: Peer Added: %s", p.GetPublicKey().String())
w.WriteHeader(http.StatusOK)
}
}
// handleAllocate reserves address space for a new client or server peer to be integrated into the network.
func handleAllocate(ns *NetworkState) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
typeParam, err := strconv.Atoi(r.URL.Query().Get("type"))
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
peerType := peer.PeerType(typeParam)
if peerType != peer.Client && peerType != peer.Server {
w.WriteHeader(http.StatusBadRequest)
return
}
nsLock.Lock()
defer nsLock.Unlock()
body, err := json.Marshal(ns)
if err != nil {
writeErr(w, err)
return
}
_, err = w.Write(body)
if err != nil {
log.Printf("API Error: %v", err)
}
indexLock.Lock()
addressLock.Lock()
defer indexLock.Unlock()
defer addressLock.Unlock()
switch peer.PeerType(peerType) {
// Clients use Client Relay addresses and E2EE addresses.
case peer.Client:
clientAddresses[clientIndex] = *ns
clientIndex += 1
ns.NextClientRelayAddr4 = ns.NextClientRelayAddr4.Next()
ns.NextClientRelayAddr6 = ns.NextClientRelayAddr6.Next()
ns.NextClientE2EEAddr4 = ns.NextClientE2EEAddr4.Next()
ns.NextClientE2EEAddr6 = ns.NextClientE2EEAddr6.Next()
// IndirectServers use Server Relay addresses, E2EE addresses, and API addresses.
case peer.Server:
serverAddresses[serverIndex] = *ns
serverIndex += 1
ns.NextServerRelayAddr4 = ns.NextServerRelayAddr4.Next()
ns.NextServerRelayAddr6 = ns.NextServerRelayAddr6.Next()
ns.NextServerE2EEAddr4 = ns.NextServerE2EEAddr4.Next()
ns.NextServerE2EEAddr6 = ns.NextServerE2EEAddr6.Next()
ns.ApiAddr = ns.ApiAddr.Next()
}
}
}
// handleAddAllowedIPs adds new route to a specified peer.
func handleAddAllowedIPs(devRelay *device.Device, config ServerConfigs) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
// Parse query parameters.
decoder := json.NewDecoder(r.Body)
var requestArgs AddAllowedIPsRequest
err := decoder.Decode(&requestArgs)
if err != nil {
writeErr(w, err)
return
}
// Verify peer exists.
p := config.RelayConfig.GetPeer(requestArgs.PublicKey)
if p == nil {
writeErr(w, errors.New("peer not found"))
return
}
for _, ip := range requestArgs.AllowedIPs {
err = p.AddAllowedIPs(ip.String())
if err != nil {
writeErr(w, err)
return
}
}
devLock.Lock()
defer devLock.Unlock()
err = devRelay.IpcSet(p.AsIPC())
if err != nil {
writeErr(w, err)
return
}
w.WriteHeader(http.StatusOK)
}
}
func handleExpose(tnet *netstack.Net, exposeMap *map[ExposeTuple]ExposeConn, exposeLock *sync.RWMutex, localAddr tcpip.FullAddress) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
// Parse query parameters.
decoder := json.NewDecoder(r.Body)
var requestArgs ExposeRequest
err := decoder.Decode(&requestArgs)
if err != nil {
writeErr(w, err)
return
}
remoteAddr, _, _ := net.SplitHostPort(r.RemoteAddr)
et := ExposeTuple{
netip.MustParseAddr(remoteAddr),
requestArgs.LocalPort,
requestArgs.RemotePort,
requestArgs.Protocol,
}
switch requestArgs.Action {
// Return list of all exposed ports.
case ExposeActionList:
exposeLock.RLock()
defer exposeLock.RUnlock()
ett := []ExposeTuple{}
for k := range *exposeMap {
ett = append(ett, k)
}
body, err := json.Marshal(ett)
if err != nil {
writeErr(w, err)
return
}
_, err = w.Write(body)
if err != nil {
log.Printf("API Error: %v", err)
}
return
// Start exposing port if not already done.
case ExposeActionExpose:
exposeLock.Lock()
defer exposeLock.Unlock()
_, ok := (*exposeMap)[et]
if ok {
// Already exists, cancel.
writeErr(w, errors.New("port already exposed"))
return
}
proto := ipv4.ProtocolNumber
if et.RemoteAddr.Is6() {
proto = ipv6.ProtocolNumber
}
if requestArgs.Dynamic {
// Handle Dynamic.
l, err := net.Listen("tcp", fmt.Sprintf(":%d", requestArgs.RemotePort))
if err != nil {
writeErr(w, err)
return
}
// Bind successful, perform dynamic forwarding.
go transport.ForwardDynamic(
tnet.Stack(),
&l,
localAddr,
tcpip.FullAddress{NIC: 1, Addr: tcpip.AddrFromSlice(et.RemoteAddr.AsSlice())},
proto,
)
(*exposeMap)[et] = ExposeConn{TcpListener: &l}
} else if requestArgs.Protocol == "tcp" {
// Handle TCP.
l, err := net.Listen(requestArgs.Protocol, fmt.Sprintf(":%d", requestArgs.RemotePort))
if err != nil {
writeErr(w, err)
return
}
// Bind successful, expose port.
go transport.ForwardTcpPort(
tnet.Stack(),
l,
localAddr,
tcpip.FullAddress{NIC: 1, Addr: tcpip.AddrFromSlice(et.RemoteAddr.AsSlice()), Port: uint16(et.LocalPort)},
proto,
)
(*exposeMap)[et] = ExposeConn{TcpListener: &l}
} else {
// Handle UDP.
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", requestArgs.RemotePort))
if err != nil {
writeErr(w, err)
return
}
c, err := net.ListenUDP("udp", addr)
if err != nil {
writeErr(w, err)
return
}
// Bind successful, expose port.
go transport.ForwardUdpPort(
tnet.Stack(),
c,
localAddr,
tcpip.FullAddress{NIC: 1, Addr: tcpip.AddrFromSlice(et.RemoteAddr.AsSlice()), Port: uint16(et.LocalPort)},
proto,
)
(*exposeMap)[et] = ExposeConn{UdpConn: c}
}
// Stop listener and delete from map.
case ExposeActionDelete:
exposeLock.Lock()
defer exposeLock.Unlock()
c, ok := (*exposeMap)[et]
if ok {
if et.Protocol == "tcp" && c.TcpListener != nil {
(*c.TcpListener).Close()
} else if c.UdpConn != nil {
c.UdpConn.Close()
}
delete(*exposeMap, et)
} else {
writeErr(w, errors.New("not found"))
return
}
}
w.WriteHeader(http.StatusOK)
}
}