aboutsummaryrefslogtreecommitdiff
path: root/prototypes/tls-autodetect.go
blob: 50017d5f8a40792e8748050044e0a77f9e000cc1 (plain)
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
//
// Copyright (c) 2018, Přemysl Janouch <p@janouch.name>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//

//
// This is an example TLS-autodetecting chat server.
//
// You may connect to it using either of these:
//  ncat -C localhost 1234
//  ncat -C --ssl localhost 1234
//
// These clients are unable to properly shutdown the connection:
//  telnet localhost 1234
//  openssl s_client -connect localhost:1234
//
package main

import (
	"bufio"
	"crypto/tls"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// --- Utilities ---------------------------------------------------------------

//
// Trivial SSL/TLS autodetection. The first block of data returned by Recvfrom
// must be at least three octets long for this to work reliably, but that should
// not pose a problem in practice. We might try waiting for them.
//
//  SSL2:      1xxx xxxx | xxxx xxxx |    <1>
//                (message length)  (client hello)
//  SSL3/TLS:    <22>    |    <3>    | xxxx xxxx
//            (handshake)|  (protocol version)
//
func detectTLS(sysconn syscall.RawConn) (isTLS bool) {
	sysconn.Read(func(fd uintptr) (done bool) {
		var buf [3]byte
		n, _, err := syscall.Recvfrom(int(fd), buf[:], syscall.MSG_PEEK)
		switch {
		case n == 3:
			isTLS = buf[0]&0x80 != 0 && buf[2] == 1
			fallthrough
		case n == 2:
			isTLS = buf[0] == 22 && buf[1] == 3
		case n == 1:
			isTLS = buf[0] == 22
		case err == syscall.EAGAIN:
			return false
		}
		return true
	})
	return isTLS
}

// --- Declarations ------------------------------------------------------------

type connCloseWrite interface {
	net.Conn
	CloseWrite() error
}

type client struct {
	transport  net.Conn       // underlying connection
	tls        *tls.Conn      // TLS, if detected
	conn       connCloseWrite // high-level connection
	inQ        []byte         // unprocessed input
	outQ       []byte         // unprocessed output
	writing    bool           // whether a writing goroutine is running
	inShutdown bool           // whether we're closing connection
	killTimer  *time.Timer    // timeout
}

type preparedEvent struct {
	client *client
	host   string // client's hostname or literal IP address
	isTLS  bool   // the client seems to use TLS
}

type readEvent struct {
	client *client
	data   []byte // new data from the client
	err    error  // read error
}

type writeEvent struct {
	client  *client
	written int   // amount of bytes written
	err     error // write error
}

var (
	sigs     = make(chan os.Signal, 1)
	conns    = make(chan net.Conn)
	prepared = make(chan preparedEvent)
	reads    = make(chan readEvent)
	writes   = make(chan writeEvent)
	timeouts = make(chan *client)

	tlsConf       *tls.Config
	clients       = make(map[*client]bool)
	listener      net.Listener
	inShutdown    bool
	shutdownTimer <-chan time.Time
)

// --- Server ------------------------------------------------------------------

// Broadcast to all /other/ clients (telnet-friendly, also in accordance to
// the plan of extending this to an IRCd).
func broadcast(line string, except *client) {
	for c := range clients {
		if c != except {
			c.send(line)
		}
	}
}

// Initiate a clean shutdown of the whole daemon.
func initiateShutdown() {
	log.Println("shutting down")
	if err := listener.Close(); err != nil {
		log.Println(err)
	}
	for c := range clients {
		c.closeLink()
	}

	shutdownTimer = time.After(3 * time.Second)
	inShutdown = true
}

// Forcefully tear down all connections.
func forceShutdown(reason string) {
	if !inShutdown {
		log.Fatalln("forceShutdown called without initiateShutdown")
	}

	log.Printf("forced shutdown (%s)\n", reason)
	for c := range clients {
		c.destroy()
	}
}

// --- Client ------------------------------------------------------------------

func (c *client) send(line string) {
	if !c.inShutdown {
		c.outQ = append(c.outQ, (line + "\r\n")...)
		c.flushOutQ()
	}
}

// Tear down the client connection, trying to do so in a graceful manner.
func (c *client) closeLink() {
	if c.inShutdown {
		return
	}
	if c.conn == nil {
		c.destroy()
		return
	}

	// Since we send this goodbye, we don't need to call CloseWrite.
	c.send("Goodbye")
	c.killTimer = time.AfterFunc(3*time.Second, func() {
		timeouts <- c
	})

	c.inShutdown = true
}

// Close the connection and forget about the client.
func (c *client) destroy() {
	// Try to send a "close notify" alert if the TLS object is ready,
	// otherwise just tear down the transport.
	if c.conn != nil {
		_ = c.conn.Close()
	} else {
		_ = c.transport.Close()
	}

	// Clean up the goroutine, although a spurious event may still be sent.
	if c.killTimer != nil {
		c.killTimer.Stop()
	}

	delete(clients, c)
}

// Handle the results from initializing the client's connection.
func (c *client) onPrepared(host string, isTLS bool) {
	if isTLS {
		c.tls = tls.Server(c.transport, tlsConf)
		c.conn = c.tls
	} else {
		c.conn = c.transport.(connCloseWrite)
	}

	// TODO: Save the host in the client structure.
	go read(c)
}

// Handle the results from trying to read from the client connection.
func (c *client) onRead(data []byte, readErr error) {
	c.inQ = append(c.inQ, data...)
	for {
		advance, token, _ := bufio.ScanLines(c.inQ, false /* atEOF */)
		if advance == 0 {
			break
		}

		c.inQ = c.inQ[advance:]
		line := string(token)
		fmt.Println(line)
		broadcast(line, c)
	}

	// TODO: Inform the client about the inQ overrun in the farewell message.
	// TODO: We should stop receiving any more data from this client.
	if len(c.inQ) > 8192 {
		c.closeLink()
		return
	}

	if readErr == io.EOF {
		if c.inShutdown {
			c.destroy()
		} else {
			c.closeLink()
		}
	} else if readErr != nil {
		log.Println(readErr)
		c.destroy()
	}
}

// Spawn a goroutine to flush the outQ if possible and necessary.  If the
// connection is not ready yet, it needs to be retried as soon as it becomes.
func (c *client) flushOutQ() {
	if c.conn != nil && !c.writing {
		go write(c, c.outQ)
		c.writing = true
	}
}

// Handle the results from trying to write to the client connection.
func (c *client) onWrite(written int, writeErr error) {
	c.outQ = c.outQ[written:]
	c.writing = false

	if writeErr != nil {
		log.Println(writeErr)
		c.destroy()
	} else if len(c.outQ) > 0 {
		c.flushOutQ()
	} else if c.inShutdown {
		if c.conn != nil {
			// FIXME: This is only correct for when /we/ initiate the shutdown,
			// otherwise we should perhaps just Close. Though even if we
			// Close, there's a/ no writer to fail on it, and b/ the reader
			// has already exited, too, which is why the client stays alive
			// up until the timeout. It seems that in that case we need to
			// call c.destroy().
			c.conn.CloseWrite()
		} else {
			c.destroy()
		}
	}
}

// --- Worker goroutines -------------------------------------------------------

func accept(ln net.Listener) {
	for {
		if conn, err := ln.Accept(); err != nil {
			// TODO: Consider specific cases in error handling, some errors
			// are transitional while others are fatal.
			log.Println(err)
			break
		} else {
			conns <- conn
		}
	}
}

func prepare(client *client) {
	conn := client.transport
	host, _, err := net.SplitHostPort(conn.RemoteAddr().String())
	if err != nil {
		// In effect, we require TCP/UDP, as they have port numbers.
		log.Fatalln(err)
	}

	// The Cgo resolver doesn't pthread_cancel getnameinfo threads, so not
	// bothering with pointless contexts.
	ch := make(chan string)
	go func() {
		defer close(ch)
		if names, err := net.LookupAddr(host); err != nil {
			log.Println(err)
		} else {
			ch <- names[0]
		}
	}()

	// While we can't cancel it, we still want to set a timeout on it.
	select {
	case <-time.After(5 * time.Second):
	case resolved, ok := <-ch:
		if ok {
			host = resolved
		}
	}

	isTLS := false
	if sysconn, err := conn.(syscall.Conn).SyscallConn(); err != nil {
		// This is just for the TLS detection and doesn't need to be fatal.
		log.Println(err)
	} else {
		isTLS = detectTLS(sysconn)
	}

	prepared <- preparedEvent{client, host, isTLS}

}

func read(client *client) {
	// A new buffer is allocated each time we receive some bytes, because of
	// thread-safety. Therefore the buffer shouldn't be too large, or we'd
	// need to copy it each time into a precisely sized new buffer.
	var err error
	for err == nil {
		var (
			buf [512]byte
			n   int
		)
		n, err = client.conn.Read(buf[:])
		reads <- readEvent{client, buf[:n], err}
	}
}

// Flush outQ, which is passed by parameter so that there are no data races.
func write(client *client, data []byte) {
	// We just write as much as we can, the main goroutine does the looping.
	n, err := client.conn.Write(data)
	writes <- writeEvent{client, n, err}
}

// --- Main --------------------------------------------------------------------

func processOneEvent() {
	select {
	case <-sigs:
		if inShutdown {
			forceShutdown("requested by user")
		} else {
			initiateShutdown()
		}

	case <-shutdownTimer:
		forceShutdown("timeout")

	case conn := <-conns:
		log.Println("accepted client connection")
		c := &client{transport: conn}
		clients[c] = true
		go prepare(c)

	case ev := <-prepared:
		log.Println("client is ready:", ev.host)
		if _, ok := clients[ev.client]; ok {
			ev.client.onPrepared(ev.host, ev.isTLS)
		}

	case ev := <-reads:
		log.Println("received data from client")
		if _, ok := clients[ev.client]; ok {
			ev.client.onRead(ev.data, ev.err)
		}

	case ev := <-writes:
		log.Println("sent data to client")
		if _, ok := clients[ev.client]; ok {
			ev.client.onWrite(ev.written, ev.err)
		}

	case c := <-timeouts:
		if _, ok := clients[c]; ok {
			log.Println("client timeouted")
			c.destroy()
		}
	}
}

func main() {
	// Just deal with unexpected flags, we don't use any ourselves.
	flag.Parse()

	if len(flag.Args()) != 3 {
		log.Fatalf("usage: %s KEY CERT ADDRESS\n", os.Args[0])
	}

	cert, err := tls.LoadX509KeyPair(flag.Arg(1), flag.Arg(0))
	if err != nil {
		log.Fatalln(err)
	}

	tlsConf = &tls.Config{Certificates: []tls.Certificate{cert}}
	listener, err = net.Listen("tcp", flag.Arg(2))
	if err != nil {
		log.Fatalln(err)
	}

	go accept(listener)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

	for !inShutdown || len(clients) > 0 {
		processOneEvent()
	}
}