/
sni_proxy.go
122 lines (103 loc) · 2.63 KB
/
sni_proxy.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
package tcp
import (
"io"
"log"
"net"
"time"
"github.com/fabiolb/fabio/metrics"
"github.com/fabiolb/fabio/route"
)
// SNIProxy implements an SNI aware transparent TCP proxy which captures the
// TLS client hello, extracts the host name and uses it for finding the
// upstream server. Then it replays the ClientHello message and copies data
// transparently allowing to route a TLS connection based on the SNI header
// without decrypting it.
type SNIProxy struct {
// DialTimeout sets the timeout for establishing the outbound
// connection.
DialTimeout time.Duration
// Lookup returns a target host for the given server name.
// The proxy will panic if this value is nil.
Lookup func(host string) *route.Target
// Conn counts the number of connections.
Conn metrics.Counter
// ConnFail counts the failed upstream connection attempts.
ConnFail metrics.Counter
// Noroute counts the failed Lookup() calls.
Noroute metrics.Counter
}
func (p *SNIProxy) ServeTCP(in net.Conn) error {
defer in.Close()
if p.Conn != nil {
p.Conn.Inc(1)
}
// capture client hello
data := make([]byte, 1024)
n, err := in.Read(data)
if err != nil {
if p.ConnFail != nil {
p.ConnFail.Inc(1)
}
return err
}
data = data[:n]
host, ok := readServerName(data)
if !ok {
log.Print("[DEBUG] tcp+sni: TLS handshake failed")
if p.ConnFail != nil {
p.ConnFail.Inc(1)
}
return nil
}
if host == "" {
log.Print("[DEBUG] tcp+sni: server_name missing")
if p.ConnFail != nil {
p.ConnFail.Inc(1)
}
return nil
}
t := p.Lookup(host)
if t == nil {
if p.Noroute != nil {
p.Noroute.Inc(1)
}
return nil
}
addr := t.URL.Host
out, err := net.DialTimeout("tcp", addr, p.DialTimeout)
if err != nil {
log.Print("[WARN] tcp+sni: cannot connect to upstream ", addr)
if p.ConnFail != nil {
p.ConnFail.Inc(1)
}
return err
}
defer out.Close()
// copy client hello
n, err = out.Write(data)
if err != nil {
log.Print("[WARN] tcp+sni: copy client hello failed. ", err)
if p.ConnFail != nil {
p.ConnFail.Inc(1)
}
return err
}
errc := make(chan error, 2)
cp := func(dst io.Writer, src io.Reader, c metrics.Counter) {
errc <- copyBuffer(dst, src, c)
}
// rx measures the traffic to the upstream server (in <- out)
// tx measures the traffic from the upstream server (out <- in)
rx := metrics.DefaultRegistry.GetCounter(t.TimerName + ".rx")
tx := metrics.DefaultRegistry.GetCounter(t.TimerName + ".tx")
// we've received the ClientHello already
rx.Inc(int64(n))
go cp(in, out, rx)
go cp(out, in, tx)
err = <-errc
if err != nil && err != io.EOF {
log.Print("[WARN]: tcp+sni: ", err)
return err
}
return nil
}