Skip to content
File

Blob: gateway/gateway.go

go357 lines
1package gateway
2 
3import (
4 "context"
5 "crypto/tls"
6 "io"
7 "net"
8 "net/http"
9 "slices"
10 "strings"
11 "time"
12 
13 "go.miragespace.co/specter/spec/cipher"
14 "go.miragespace.co/specter/spec/protocol"
15 "go.miragespace.co/specter/spec/transport"
16 "go.miragespace.co/specter/spec/transport/q"
17 "go.miragespace.co/specter/spec/tun"
18 "go.miragespace.co/specter/timing"
19 "go.miragespace.co/specter/util"
20 "go.miragespace.co/specter/util/acceptor"
21 
22 "github.com/go-chi/chi/v5"
23 "github.com/go-chi/httprate"
24 "github.com/libp2p/go-yamux/v4"
25 "github.com/quic-go/quic-go"
26 "github.com/quic-go/quic-go/http3"
27 "go.uber.org/zap"
28 "go.uber.org/zap/zapcore"
29 "moul.io/zapfilter"
30)
31 
32type DeadlineReadWriteCloser interface {
33 io.ReadWriteCloser
34 SetReadDeadline(time.Time) error
35}
36 
37type InternalHandlers struct {
38 Overview http.Handler
39 Configuration http.Handler
40 Acme http.Handler
41 Chord http.Handler
42 TunnelServer http.Handler
43 Migrator http.Handler
44}
45 
46type Options struct {
47 TransportBufferSize int
48 ProxyBufferSize int
49}
50 
51type GatewayConfig struct {
52 Handlers InternalHandlers
53 PKIServer protocol.PKIService
54 TunnelServer tun.Server
55 HTTPListener net.Listener
56 H2Listener net.Listener
57 H3Listener q.Listener
58 Logger *zap.Logger
59 HandshakeHintFunc cipher.OnHandshakeFunc
60 RouteCheckFunc func(context.Context, string) error
61 ApplicationMiddleware func(http.Handler, func(*http.Request) (string, error)) http.Handler
62 AdminUser string
63 AdminPass string
64 RootDomains []string
65 GatewayPort int
66 Options Options
67}
68 
69type Gateway struct {
70 apexServer *apexServer
71 httpTunnelAcceptor *acceptor.HTTP2Acceptor
72 http3TunnelAcceptor *acceptor.HTTP3Acceptor
73 tcpApexAcceptor *acceptor.HTTP2Acceptor
74 quicApexAcceptor *acceptor.HTTP3Acceptor
75 tcpApexServer *http.Server
76 h2TunnelServer *http.Server
77 localApexServer *http.Server
78 httpServer *http.Server
79 quicApexServer *http3.Server
80 h3TunnelServer *http3.Server
81 altHeaders string
82 GatewayConfig
83}
84 
85func (c *GatewayConfig) startApex() bool {
86 return len(c.RootDomains) > 0
87}
88 
89func New(conf GatewayConfig) *Gateway {
90 if conf.PKIServer != nil {
91 conf.Logger.Info("Enabling client certificate issuance")
92 }
93 
94 g := &Gateway{
95 GatewayConfig: conf,
96 httpTunnelAcceptor: acceptor.NewH2Acceptor(conf.H2Listener),
97 tcpApexAcceptor: acceptor.NewH2Acceptor(conf.H2Listener),
98 http3TunnelAcceptor: acceptor.NewH3Acceptor(conf.H3Listener),
99 quicApexAcceptor: acceptor.NewH3Acceptor(conf.H3Listener),
100 }
101 
102 // filter out unproductive messages
103 filteredLogger := zap.New(zapfilter.NewFilteringCore(
104 g.Logger.Core(),
105 func(e zapcore.Entry, f []zapcore.Field) bool {
106 if strings.HasPrefix(e.Message, "http: URL query contains semicolon") {
107 return false
108 }
109 if strings.HasPrefix(e.Message, "suppressing panic for copyResponse error in test;") {
110 return false
111 }
112 return true
113 }),
114 )
115 proxyHandler := g.proxyHandler(util.GetStdLogger(filteredLogger, "httpProxy"))
116 
117 qCfg := &quic.Config{
118 HandshakeIdleTimeout: time.Second * 5,
119 KeepAlivePeriod: time.Second * 30,
120 MaxIdleTimeout: time.Second * 60,
121 }
122 
123 if conf.startApex() {
124 if conf.AdminUser == "" || conf.AdminPass == "" {
125 conf.Logger.Info("Missing credentials for internal endpoint, disabling /_internal endpoint")
126 }
127 apex := chi.NewRouter()
128 apex.Use(func(h http.Handler) http.Handler {
129 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
130 g.appendHeaders(r.ProtoAtLeast(3, 0))(w.Header())
131 h.ServeHTTP(w, r)
132 })
133 })
134 g.apexServer = &apexServer{
135 handlers: conf.Handlers,
136 limiter: httprate.LimitAll(10, time.Second), // limit request to apex endpoint to 10 req/s
137 internalProxy: g.getInternalProxyHandler(),
138 pkiServer: conf.PKIServer,
139 authUser: conf.AdminUser,
140 authPass: conf.AdminPass,
141 }
142 g.apexServer.Mount(apex)
143 g.mountCgiHandler(apex)
144 g.tcpApexServer = &http.Server{
145 ReadHeaderTimeout: time.Second * 5,
146 Handler: apex,
147 ErrorLog: util.GetStdLogger(filteredLogger, "tcpApex"),
148 }
149 g.quicApexServer = &http3.Server{
150 QUICConfig: qCfg,
151 EnableDatagrams: false,
152 Handler: apex,
153 }
154 g.localApexServer = &http.Server{
155 Addr: "127.0.0.1:9999",
156 ReadHeaderTimeout: time.Second * 5,
157 Handler: apex,
158 ErrorLog: util.GetStdLogger(filteredLogger, "localApex"),
159 }
160 }
161 
162 g.h2TunnelServer = &http.Server{
163 ReadHeaderTimeout: time.Second * 5,
164 Handler: proxyHandler,
165 ErrorLog: util.GetStdLogger(filteredLogger, "h2Tunnel"),
166 }
167 g.h3TunnelServer = &http3.Server{
168 QUICConfig: qCfg,
169 EnableDatagrams: false,
170 Handler: proxyHandler,
171 }
172 g.httpServer = &http.Server{
173 ReadHeaderTimeout: 5 * time.Second,
174 ReadTimeout: 5 * time.Second,
175 WriteTimeout: 5 * time.Second,
176 IdleTimeout: 5 * time.Second,
177 Handler: g.httpRouter(),
178 ErrorLog: util.GetStdLogger(filteredLogger, "httpServer"),
179 }
180 g.altHeaders = generateAltHeaders(conf.GatewayPort)
181 
182 return g
183}
184 
185func (g *Gateway) AttachRouter(ctx context.Context, router *transport.StreamRouter) {
186 router.HandleChord(protocol.Stream_INTERNAL, nil, func(delegate *transport.StreamDelegate) {
187 g.tcpApexAcceptor.Handle(delegate)
188 })
189}
190 
191func (g *Gateway) MustStart(ctx context.Context) {
192 // provide application context
193 g.h2TunnelServer.BaseContext = func(l net.Listener) context.Context { return ctx }
194 g.httpServer.BaseContext = func(l net.Listener) context.Context { return ctx }
195 
196 go g.h2TunnelServer.Serve(g.httpTunnelAcceptor)
197 go g.h3TunnelServer.ServeListener(g.http3TunnelAcceptor)
198 
199 go g.acceptTCP(ctx)
200 go g.acceptQUIC(ctx)
201 
202 if g.startApex() {
203 g.tcpApexServer.BaseContext = func(l net.Listener) context.Context { return ctx }
204 g.localApexServer.BaseContext = func(l net.Listener) context.Context { return ctx }
205 
206 go g.tcpApexServer.Serve(g.tcpApexAcceptor)
207 go g.quicApexServer.ServeListener(g.quicApexAcceptor)
208 go g.localApexServer.ListenAndServe()
209 }
210 
211 if g.HTTPListener != nil {
212 g.Logger.Info("Enabling HTTP Handler for HTTP Connect and HTTPS Redirect", zap.String("listen", g.HTTPListener.Addr().String()))
213 go g.httpServer.Serve(g.HTTPListener)
214 }
215 
216 g.Logger.Info("gateway server started")
217}
218 
219func (g *Gateway) Close() {
220 g.httpTunnelAcceptor.Close()
221 
222 g.h2TunnelServer.Close()
223 g.h3TunnelServer.Close()
224 
225 if g.startApex() {
226 g.tcpApexAcceptor.Close()
227 g.quicApexAcceptor.Close()
228 
229 g.tcpApexServer.Close()
230 g.quicApexServer.Close()
231 
232 g.localApexServer.Close()
233 }
234}
235 
236func (g *Gateway) acceptTCP(ctx context.Context) {
237 for {
238 conn, err := g.H2Listener.Accept()
239 if err != nil {
240 return
241 }
242 tconn := conn.(*tls.Conn)
243 go g.handleH2Connection(ctx, tconn)
244 }
245}
246 
247func (g *Gateway) acceptQUIC(ctx context.Context) {
248 for {
249 conn, err := g.H3Listener.Accept(ctx)
250 if err != nil {
251 return
252 }
253 go g.handleH3Connection(ctx, conn)
254 }
255}
256 
257func (g *Gateway) handleH3Connection(ctx context.Context, q *quic.Conn) {
258 cs := q.ConnectionState().TLS
259 logger := g.Logger.With(
260 zap.Bool("via-quic", true),
261 zap.String("proto", cs.NegotiatedProtocol),
262 zap.String("tls.ServerName", cs.ServerName),
263 )
264 
265 if len(cs.ServerName) == 0 {
266 q.CloseWithError(0, "")
267 return
268 }
269 
270 if slices.Contains(g.RootDomains, cs.ServerName) {
271 logger.Debug("forwarding apex connection")
272 g.quicApexAcceptor.Handle(q)
273 return
274 }
275 
276 // maybe tunnel it
277 switch cs.NegotiatedProtocol {
278 case tun.ALPN(protocol.Link_TCP):
279 logger.Debug("forwarding tcp connection")
280 g.handleH3Multiplex(ctx, logger, q, cs.ServerName)
281 default:
282 logger.Debug("forwarding http connection")
283 g.http3TunnelAcceptor.Handle(q)
284 }
285}
286 
287func (g *Gateway) handleH3Multiplex(ctx context.Context, logger *zap.Logger, q *quic.Conn, host string) {
288 for {
289 stream, err := q.AcceptStream(ctx)
290 if err != nil {
291 return
292 }
293 go func(stream DeadlineReadWriteCloser) {
294 if err := g.forwardTCP(ctx, host, q.RemoteAddr().String(), stream); err == nil {
295 logger.Debug("forwarding tcp connection")
296 }
297 }(stream)
298 }
299}
300 
301func (g *Gateway) handleH2Connection(ctx context.Context, conn *tls.Conn) {
302 hsCtx, cancel := context.WithTimeout(ctx, timing.TLSHandshakeTimeout)
303 defer cancel()
304 if err := conn.HandshakeContext(hsCtx); err != nil {
305 conn.Close()
306 return
307 }
308 
309 cs := conn.ConnectionState()
310 logger := g.Logger.With(
311 zap.Bool("via-quic", false),
312 zap.String("proto", cs.NegotiatedProtocol),
313 zap.String("tls.ServerName", cs.ServerName),
314 )
315 
316 if len(cs.ServerName) == 0 {
317 conn.Close()
318 return
319 }
320 
321 if slices.Contains(g.RootDomains, cs.ServerName) {
322 logger.Debug("forwarding apex connection")
323 g.tcpApexAcceptor.Handle(conn)
324 return
325 }
326 
327 // maybe tunnel it
328 switch cs.NegotiatedProtocol {
329 case tun.ALPN(protocol.Link_TCP):
330 logger.Debug("forwarding tcp connection")
331 cfg := yamux.DefaultConfig()
332 cfg.LogOutput = io.Discard
333 session, err := yamux.Server(conn, cfg, nil)
334 if err != nil {
335 return
336 }
337 g.handleH2Multiplex(ctx, logger, session, cs.ServerName)
338 default:
339 logger.Debug("forwarding http connection")
340 g.httpTunnelAcceptor.Handle(conn)
341 }
342}
343 
344func (g *Gateway) handleH2Multiplex(ctx context.Context, logger *zap.Logger, session *yamux.Session, host string) {
345 for {
346 stream, err := session.AcceptStream()
347 if err != nil {
348 return
349 }
350 go func(stream DeadlineReadWriteCloser) {
351 if err := g.forwardTCP(ctx, host, session.RemoteAddr().String(), stream); err == nil {
352 logger.Debug("forwarding tcp connection")
353 }
354 }(stream)
355 }
356}