Repository navigation
Expand file tree
/
Copy pathserver.go
More file actions
230 lines (190 loc) · 6.68 KB
/
Copy pathserver.go
File metadata and controls
230 lines (190 loc) · 6.68 KB
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
package fronted
import (
"crypto/tls"
"fmt"
"net"
"net/http"
"os"
"time"
"github.com/getlantern/enproxy"
"github.com/getlantern/idletiming"
"github.com/getlantern/keyman"
"github.com/getlantern/tlsdefaults"
)
var (
dialTimeout = 10 * time.Second
httpIdleTimeout = 70 * time.Second
// Points in time, mostly used for generating certificates
tenYearsFromToday = time.Now().AddDate(10, 0, 0)
)
type Server struct {
// Addr: listen address in form of host:port
Addr string
// ReadTimeout: (optional) timeout for read ops
ReadTimeout time.Duration
// WriteTimeout: (optional) timeout for write ops
WriteTimeout time.Duration
// CertContext for server's certificates. If nil, the server will use
// unencrypted connections instead of TLS.
CertContext *CertContext
// TLSConfig: tls configuration to use on inbound connections. If nil, will
// use some sensible defaults.
TLSConfig *tls.Config
// Host: FQDN that is guaranteed to hit this server
Host string
// HostFn: Function mapping a http.Request to the FQDN of this particular
// server, hopefully using the same front as the original request
HostFn func(*http.Request) string
// AllowNonGlobalDestinations: if false, requests to LAN, Loopback, etc.
// will be disallowed.
AllowNonGlobalDestinations bool
// Allow: Optional function that checks whether the given request to the
// given destAddr is allowed. If it is not allowed, this function should
// return an error.
Allow func(req *http.Request, destAddr string) (int, error)
// OnBytesSent: optional callback for learning about bytes sent by this
// server to upstream destinations.
OnBytesSent func(ip string, destAddr string, req *http.Request, bytes int64)
// OnBytesSent: optional callback for learning about bytes received by this
// server from upstream destinations.
OnBytesReceived func(ip string, destAddr string, req *http.Request, bytes int64)
}
// CertContext encapsulates the certificates used by a Server
type CertContext struct {
PKFile string
ServerCertFile string
PK *keyman.PrivateKey
ServerCert *keyman.Certificate
}
func (server *Server) Listen() (net.Listener, error) {
listener, err := server.listen()
if err != nil {
return nil, err
}
// We use an idle timing listener to time out idle HTTP connections, since
// the CDNs seem to like keeping lots of connections open indefinitely.
return idletiming.Listener(listener, httpIdleTimeout, func(conn net.Conn) {
err := conn.Close()
if err != nil {
log.Debugf("Unable to close connection: %v", err)
}
}), nil
}
func (server *Server) listen() (net.Listener, error) {
if server.CertContext != nil {
return server.listenTLS()
} else {
return server.listenUnencrypted()
}
}
func (server *Server) listenTLS() (net.Listener, error) {
host, _, err := net.SplitHostPort(server.Addr)
if err != nil {
return nil, fmt.Errorf("Unable to split host and port for %v: %v", server.Addr, err)
}
err = server.CertContext.InitServerCert(host)
if err != nil {
return nil, fmt.Errorf("Unable to init server cert: %s", err)
}
tlsConfig := server.TLSConfig
if server.TLSConfig == nil {
tlsConfig = tlsdefaults.Server()
}
cert, err := tls.LoadX509KeyPair(server.CertContext.ServerCertFile, server.CertContext.PKFile)
if err != nil {
return nil, fmt.Errorf("Unable to load certificate and key from %s and %s: %s", server.CertContext.ServerCertFile, server.CertContext.PKFile, err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
listener, err := tls.Listen("tcp", server.Addr, tlsConfig)
if err != nil {
return nil, fmt.Errorf("Unable to listen for tls connections at %s: %s", server.Addr, err)
}
return listener, err
}
func (server *Server) listenUnencrypted() (net.Listener, error) {
listener, err := net.Listen("tcp", server.Addr)
if err != nil {
return nil, fmt.Errorf("Unable to listen for unencrypted connections at %s: %s", server.Addr, err)
}
return listener, err
}
func (server *Server) Serve(l net.Listener) error {
// Set up an enproxy Proxy
proxy := &enproxy.Proxy{
Dial: server.dialDestination,
Host: server.Host,
HostFn: server.HostFn,
OnBytesReceived: server.OnBytesReceived,
OnBytesSent: server.OnBytesSent,
}
if server.AllowNonGlobalDestinations {
proxy.Allow = server.Allow
} else {
proxy.Allow = func(req *http.Request, destAddr string) (int, error) {
code, err := server.checkForNonGlobalDestination(destAddr)
if err != nil {
return code, err
}
if server.Allow != nil {
return server.Allow(req, destAddr)
}
return http.StatusOK, nil
}
}
proxy.Start()
httpServer := &http.Server{
Handler: proxy,
ReadTimeout: server.ReadTimeout,
WriteTimeout: server.WriteTimeout,
}
log.Debugf("About to start server (https) proxy at %s", server.Addr)
return httpServer.Serve(l)
}
// dialDestination dials the destination server and wraps the resulting net.Conn
// in a countingConn if an InstanceId was configured.
func (server *Server) dialDestination(addr string) (net.Conn, error) {
return net.DialTimeout("tcp", addr, dialTimeout)
}
func (server *Server) checkForNonGlobalDestination(addr string) (int, error) {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return http.StatusBadRequest, fmt.Errorf("Enproxy unable to split host and port for %v: %v", addr, err)
}
ipAddr, err := net.ResolveIPAddr("ip", host)
if err != nil || len(ipAddr.IP) == 0 {
// It's not really clear what we should return if we can't resolve the DNS, so
// might as well go with status tea pot!
return http.StatusTeapot, fmt.Errorf("Unable to resolve destination IP addr %v: %v", host, err)
}
if !ipAddr.IP.IsGlobalUnicast() {
return http.StatusBadRequest, fmt.Errorf("Not accepting connections to non-global address: %s", addr)
}
return http.StatusOK, nil
}
// InitServerCert initializes a PK + cert for use by a server proxy, signed by
// the CA certificate. We always generate a new certificate just in case.
func (ctx *CertContext) InitServerCert(host string) (err error) {
if ctx.PK, err = keyman.LoadPKFromFile(ctx.PKFile); err != nil {
if os.IsNotExist(err) {
log.Debugf("Creating new PK at: %s", ctx.PKFile)
if ctx.PK, err = keyman.GeneratePK(2048); err != nil {
return
}
if err = ctx.PK.WriteToFile(ctx.PKFile); err != nil {
return fmt.Errorf("Unable to save private key: %s", err)
}
} else {
return fmt.Errorf("Unable to read private key, even though it exists: %s", err)
}
}
log.Debugf("Creating new server cert at: %s", ctx.ServerCertFile)
ctx.ServerCert, err = ctx.PK.TLSCertificateFor("Lantern", host, tenYearsFromToday, true, nil)
if err != nil {
return
}
err = ctx.ServerCert.WriteToFile(ctx.ServerCertFile)
if err != nil {
return
}
return nil
}