-
Notifications
You must be signed in to change notification settings - Fork 12
/
service.go
391 lines (303 loc) · 9.49 KB
/
service.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
package networkwebsockets
import (
"fmt"
"log"
"math/rand"
"net"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"text/template"
"time"
tls "github.com/richtr/go-tls-srp"
)
var (
// Proxy path matchers
serviceNameRegexStr = "[A-Za-z0-9\\+=\\*\\._-]{1,255}"
isValidCreateRequest = regexp.MustCompile(fmt.Sprintf("^/%s$", serviceNameRegexStr))
isValidProxyRequest = regexp.MustCompile(fmt.Sprintf("^/%s$", serviceNameRegexStr))
// TLS-SRP configuration components
Salt = []byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}
serviceTab = CredentialsStore(map[string]string{})
)
// Generate a new random identifier
func GenerateId() string {
rand.Seed(time.Now().UTC().UnixNano())
return fmt.Sprintf("%d", rand.Int())
}
type HTTPHandler interface {
ServeLocalRequest(w http.ResponseWriter, r *http.Request)
ServeProxyRequest(w http.ResponseWriter, r *http.Request)
}
type DefaultServiceHandler struct {
service *Service
}
func (sh *DefaultServiceHandler) ServeLocalRequest(w http.ResponseWriter, r *http.Request) {
service := sh.service
if service == nil {
http.Error(w, fmt.Sprintln("This interface is not attached to a service"), 403)
return
}
// Only allow access from localhost to all services
if isRequestFromLocalHost := service.checkRequestIsFromLocalHost(r.Host); !isRequestFromLocalHost {
http.Error(w, fmt.Sprintln("This interface is only accessible from the local machine"), 403)
return
}
if r.Method != "GET" {
http.Error(w, "Method Not Allowed", 405)
return
}
serviceName := strings.TrimPrefix(r.URL.Path, "/")
// Serve console page for use in web browser if no service name has been requested
if serviceName == "" {
consoleHTML, err := Asset("_templates/console.html")
if err != nil {
// Asset was not found.
http.Error(w, "Not Found", 404)
return
}
t := template.Must(template.New("console").Parse(string(consoleHTML)))
if t == nil {
http.Error(w, "Internal Server Error", 501)
return
}
t.Execute(w, service.Port)
return
}
if isValidRequest := isValidCreateRequest.MatchString(r.URL.Path); !isValidRequest {
http.Error(w, "Not Found", 404)
return
}
if isValidWSUpgradeRequest := strings.ToLower(r.Header.Get("Upgrade")); isValidWSUpgradeRequest != "websocket" {
http.Error(w, "Bad Request", 400)
return
}
// Resolve to network web socket channel
channel := service.GetChannelByName(serviceName)
if channel == nil {
channel = NewChannel(service, serviceName)
}
// Serve network web socket channel peer
ws, err := upgradeHTTPToWebSocket(w, r)
if err != nil {
http.Error(w, "Bad Request", 400)
return
}
// Create, bind and start a new peer connection
peer := NewPeer(ws)
peer.Start(channel)
}
func (sh *DefaultServiceHandler) ServeProxyRequest(w http.ResponseWriter, r *http.Request) {
service := sh.service
if service == nil {
http.Error(w, fmt.Sprintln("This interface is not attached to a service"), 403)
return
}
if r.Method != "GET" {
http.Error(w, "Method Not Allowed", 405)
return
}
if isValidRequest := isValidProxyRequest.MatchString(r.URL.Path); !isValidRequest {
http.Error(w, "Not Found", 404)
return
}
if isValidWSUpgradeRequest := strings.ToLower(r.Header.Get("Upgrade")); isValidWSUpgradeRequest != "websocket" {
http.Error(w, "Bad Request", 400)
return
}
requestedWebSocketSubProtocols := r.Header.Get("Sec-Websocket-Protocol")
if requestedWebSocketSubProtocols != "nws-proxy-draft-01" {
http.Error(w, "Bad Request", 400)
return
}
// Resolve servicePath to an active named websocket service
for _, channel := range service.Channels {
if channel.proxyPath == r.URL.Path {
ws, err := upgradeHTTPToWebSocket(w, r)
if err != nil {
http.Error(w, "Bad Request", 400)
return
}
// Create, bind and start a new proxy connection
proxy := NewProxy(ws, true)
proxy.Start(channel)
return
}
}
http.Error(w, "Not Found", 404)
return
}
type Service struct {
Host string
Port int
ProxyPort int
Handler HTTPHandler
// All Network Web Socket channels that this service manages
Channels map[string]*Channel
discoveryBrowser *DiscoveryBrowser
done chan int // blocks until .Stop() is called on this service
localListener net.Listener
netListener net.Listener
}
func NewService(host string, port int) *Service {
if host == "" {
hostname, err := os.Hostname()
if err != nil {
log.Printf("Could not determine device hostname: %v\n", err)
return nil
}
host = hostname
}
if port <= 1024 || port >= 65534 {
port = 9009
}
service := &Service{
Host: host,
Port: port,
ProxyPort: 0,
Channels: make(map[string]*Channel),
discoveryBrowser: NewDiscoveryBrowser(),
done: make(chan int),
}
// Setup a new default http service handler
service.Handler = &DefaultServiceHandler{service}
return service
}
func (service *Service) Start() <-chan int {
// Start HTTP/Network Web Socket creation server
service.StartHTTPServer()
// Start TLS-SRP Network Web Socket (wss) proxy server
service.StartProxyServer()
// Start mDNS/DNS-SD Network Web Socket discovery service
service.StartDiscoveryBrowser(10)
return service.StopNotify()
}
func (service *Service) StartHTTPServer() {
// Create a new custom http server multiplexer
serveMux := http.NewServeMux()
// Serve network web socket creation endpoints for localhost clients
serveMux.HandleFunc("/", service.Handler.ServeLocalRequest)
// Listen and on loopback address + port
listener, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", service.Port))
if err != nil {
log.Fatal("Could not serve web server. ", err)
}
service.localListener = listener
log.Printf("Serving Network Web Socket Creator Proxy at address [ ws://localhost:%d/ ]", service.Port)
go http.Serve(listener, serveMux)
}
func (service *Service) StartProxyServer() {
// Create a new custom http server multiplexer
serveMux := http.NewServeMux()
// Serve secure network web socket proxy endpoints for network clients
serveMux.HandleFunc("/", service.Handler.ServeProxyRequest)
// Generate random server salt for use in TLS-SRP data storage
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, 32)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
srpSaltKey := string(b)
tlsServerConfig := &tls.Config{
SRPLookup: serviceTab,
SRPSaltKey: srpSaltKey,
SRPSaltSize: len(Salt),
}
// Listen on all addresses + port
tlsSrpListener, err := tls.Listen("tcp", ":0", tlsServerConfig)
if err != nil {
log.Fatal("Could not serve proxy server. ", err)
}
service.netListener = tlsSrpListener
// Obtain and store the port of the proxy endpoint
_, port, err := net.SplitHostPort(tlsSrpListener.Addr().String())
if err != nil {
log.Fatal("Could not determine bound port of proxy server. ", err)
}
service.ProxyPort, _ = strconv.Atoi(port)
log.Printf("Serving Network Web Socket Network Proxy at address [ wss://%s:%d/ ]", service.Host, service.ProxyPort)
go http.Serve(tlsSrpListener, serveMux)
}
func (service *Service) StartDiscoveryBrowser(timeoutSeconds int) {
log.Printf("Listening for Network Web Socket services on the local network...")
go func() {
defer service.discoveryBrowser.Shutdown()
for !service.discoveryBrowser.closed {
service.discoveryBrowser.Browse(service, timeoutSeconds)
}
}()
}
// Check whether we know the given service name
func (service *Service) GetChannelByName(serviceName string) *Channel {
for _, channel := range service.Channels {
if channel.serviceName == serviceName {
return channel
}
}
return nil
}
// Check whether a DNS-SD derived Network Web Socket hash is owned by the current proxy instance
func (service *Service) isOwnProxyService(serviceRecord *DNSRecord) bool {
for _, channel := range service.Channels {
if channel.serviceHash == serviceRecord.Hash_Base64 {
return true
}
}
return false
}
// Check whether a DNS-SD derived Network Web Socket hash is currently connected as a service
func (service *Service) isActiveProxyService(serviceRecord *DNSRecord) bool {
for _, channel := range service.Channels {
for _, proxy := range channel.proxies {
if proxy.Hash_Base64 == serviceRecord.Hash_Base64 {
return true
}
}
}
return false
}
// Stop stops the server gracefully, and shuts down the running goroutine.
// Stop should be called after a Start(s), otherwise it will block forever.
func (service *Service) Stop() {
if service.discoveryBrowser != nil {
service.discoveryBrowser.closed = true
}
if service.localListener != nil {
service.localListener.Close()
}
if service.netListener != nil {
service.netListener.Close()
}
service.done <- 1
}
// StopNotify returns a channel that receives a empty integer
// when the server is stopped.
func (service *Service) StopNotify() <-chan int { return service.done }
//
// HELPER FUNCTIONS
//
func (service *Service) checkRequestIsFromLocalHost(host string) bool {
allowedLocalHosts := map[string]bool{
fmt.Sprintf("localhost:%d", service.Port): true,
fmt.Sprintf("127.0.0.1:%d", service.Port): true,
fmt.Sprintf("::1:%d", service.Port): true,
fmt.Sprintf("%s:%d", service.Host, service.Port): true,
}
if allowedLocalHosts[host] {
return true
}
return false
}
/** Simple in-memory storage table for TLS-SRP usernames/passwords **/
type CredentialsStore map[string]string
func (cs CredentialsStore) Lookup(user string) (v, s []byte, grp tls.SRPGroup, err error) {
grp = tls.SRPGroup4096
p := cs[user]
if p == "" {
return nil, nil, grp, nil
}
v = tls.SRPVerifier(user, p, Salt, grp)
return v, Salt, grp, nil
}