Debian Codegraph @

modules/caddyhttp/reverseproxy/httptransport.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package reverseproxy
16
17 import (
18 "context"
19 "crypto/tls"
20 "crypto/x509"
21 "encoding/base64"
22 "encoding/json"
23 "fmt"
24 weakrand "math/rand/v2"
25 "net"
26 "net/http"
27 "net/url"
28 "os"
29 "reflect"
30 "slices"
31 "strings"
32 "time"
33
34 "github.com/pires/go-proxyproto"
35 "github.com/quic-go/quic-go/http3"
36 "go.uber.org/zap"
37 "go.uber.org/zap/zapcore"
38 "golang.org/x/net/http2"
39
40 "github.com/caddyserver/caddy/v2"
41 "github.com/caddyserver/caddy/v2/caddyconfig"
42 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
43 "github.com/caddyserver/caddy/v2/modules/caddyhttp/headers"
44 "github.com/caddyserver/caddy/v2/modules/caddytls"
45 "github.com/caddyserver/caddy/v2/modules/internal/network"
46 )
47
48 func init() {
49 caddy.RegisterModule(HTTPTransport{})
50 }
51
52 // HTTPTransport is essentially a configuration wrapper for http.Transport.
53 // It defines a JSON structure useful when configuring the HTTP transport
54 // for Caddy's reverse proxy. It builds its http.Transport at Provision.
55 type HTTPTransport struct {
56 // TODO: It's possible that other transports (like fastcgi) might be
57 // able to borrow/use at least some of these config fields; if so,
58 // maybe move them into a type called CommonTransport and embed it?
59
60 // Configures the DNS resolver used to resolve the IP address of upstream hostnames.
61 Resolver *UpstreamResolver `json:"resolver,omitempty"`
62
63 // Configures TLS to the upstream. Setting this to an empty struct
64 // is sufficient to enable TLS with reasonable defaults.
65 TLS *TLSConfig `json:"tls,omitempty"`
66
67 // Configures HTTP Keep-Alive (enabled by default). Should only be
68 // necessary if rigorous testing has shown that tuning this helps
69 // improve performance.
70 KeepAlive *KeepAlive `json:"keep_alive,omitempty"`
71
72 // Whether to enable compression to upstream. Default: true
73 Compression *bool `json:"compression,omitempty"`
74
75 // Maximum number of connections per host. Default: 0 (no limit)
76 MaxConnsPerHost int `json:"max_conns_per_host,omitempty"`
77
78 // If non-empty, which PROXY protocol version to send when
79 // connecting to an upstream. Default: off.
80 ProxyProtocol string `json:"proxy_protocol,omitempty"`
81
82 // URL to the server that the HTTP transport will use to proxy
83 // requests to the upstream. See http.Transport.Proxy for
84 // information regarding supported protocols. This value takes
85 // precedence over `HTTP_PROXY`, etc.
86 //
87 // Providing a value to this parameter results in
88 // requests flowing through the reverse_proxy in the following
89 // way:
90 //
91 // User Agent ->
92 // reverse_proxy ->
93 // forward_proxy_url -> upstream
94 //
95 // Default: http.ProxyFromEnvironment
96 // DEPRECATED: Use NetworkProxyRaw|`network_proxy` instead. Subject to removal.
97 ForwardProxyURL string `json:"forward_proxy_url,omitempty"`
98
99 // How long to wait before timing out trying to connect to
100 // an upstream. Default: `3s`.
101 DialTimeout caddy.Duration `json:"dial_timeout,omitempty"`
102
103 // How long to wait before spawning an RFC 6555 Fast Fallback
104 // connection. A negative value disables this. Default: `300ms`.
105 FallbackDelay caddy.Duration `json:"dial_fallback_delay,omitempty"`
106
107 // How long to wait for reading response headers from server. Default: No timeout.
108 ResponseHeaderTimeout caddy.Duration `json:"response_header_timeout,omitempty"`
109
110 // The length of time to wait for a server's first response
111 // headers after fully writing the request headers if the
112 // request has a header "Expect: 100-continue". Default: No timeout.
113 ExpectContinueTimeout caddy.Duration `json:"expect_continue_timeout,omitempty"`
114
115 // The maximum bytes to read from response headers. Default: `10MiB`.
116 MaxResponseHeaderSize int64 `json:"max_response_header_size,omitempty"`
117
118 // The size of the write buffer in bytes. Default: `4KiB`.
119 WriteBufferSize int `json:"write_buffer_size,omitempty"`
120
121 // The size of the read buffer in bytes. Default: `4KiB`.
122 ReadBufferSize int `json:"read_buffer_size,omitempty"`
123
124 // The maximum time to wait for next read from backend. Default: no timeout.
125 ReadTimeout caddy.Duration `json:"read_timeout,omitempty"`
126
127 // The maximum time to wait for next write to backend. Default: no timeout.
128 WriteTimeout caddy.Duration `json:"write_timeout,omitempty"`
129
130 // The versions of HTTP to support. As a special case, "h2c"
131 // can be specified to use H2C (HTTP/2 over Cleartext) to the
132 // upstream (this feature is experimental and subject to
133 // change or removal). Default: ["1.1", "2"]
134 //
135 // EXPERIMENTAL: "3" enables HTTP/3, but it must be the only
136 // version specified if enabled. Additionally, HTTPS must be
137 // enabled to the upstream as HTTP/3 requires TLS. Subject
138 // to change or removal while experimental.
139 Versions []string `json:"versions,omitempty"`
140
141 // Specify the address to bind to when connecting to an upstream. In other words,
142 // it is the address the upstream sees as the remote address.
143 LocalAddress string `json:"local_address,omitempty"`
144
145 // The pre-configured underlying HTTP transport.
146 Transport *http.Transport `json:"-"`
147
148 // The module that provides the network (forward) proxy
149 // URL that the HTTP transport will use to proxy
150 // requests to the upstream. See [http.Transport.Proxy](https://pkg.go.dev/net/http#Transport.Proxy)
151 // for information regarding supported protocols.
152 //
153 // Providing a value to this parameter results in requests
154 // flowing through the reverse_proxy in the following way:
155 //
156 // User Agent ->
157 // reverse_proxy ->
158 // [proxy provided by the module] -> upstream
159 //
160 // If nil, defaults to reading the `HTTP_PROXY`,
161 // `HTTPS_PROXY`, and `NO_PROXY` environment variables.
162 NetworkProxyRaw json.RawMessage `json:"network_proxy,omitempty" caddy:"namespace=caddy.network_proxy inline_key=from"`
163
164 h3Transport *http3.Transport // TODO: EXPERIMENTAL (May 2024)
165 }
166
167 // CaddyModule returns the Caddy module information.
168 func (HTTPTransport) CaddyModule() caddy.ModuleInfo {
169 return caddy.ModuleInfo{
170 ID: "http.reverse_proxy.transport.http",
171 New: func() caddy.Module { return new(HTTPTransport) },
172 }
173 }
174
175 var (
176 allowedVersions = []string{"1.1", "2", "h2c", "3"}
177 allowedVersionsString = strings.Join(allowedVersions, ", ")
178 )
179
180 // Provision sets up h.Transport with a *http.Transport
181 // that is ready to use.
182 func (h *HTTPTransport) Provision(ctx caddy.Context) error {
183 if len(h.Versions) == 0 {
184 h.Versions = []string{"1.1", "2"}
185 }
186 // some users may provide http versions not recognized by caddy, instead of trying to
187 // guess the version, we just error out and let the user fix their config
188 // see: https://github.com/caddyserver/caddy/issues/7111
189 for _, v := range h.Versions {
190 if !slices.Contains(allowedVersions, v) {
191 return fmt.Errorf("unsupported HTTP version: %s, supported version: %s", v, allowedVersionsString)
192 }
193 }
194
195 rt, err := h.NewTransport(ctx)
196 if err != nil {
197 return err
198 }
199 h.Transport = rt
200
201 return nil
202 }
203
204 // NewTransport builds a standard-lib-compatible http.Transport value from h.
205 func (h *HTTPTransport) NewTransport(caddyCtx caddy.Context) (*http.Transport, error) {
206 // Set keep-alive defaults if it wasn't otherwise configured
207 if h.KeepAlive == nil {
208 h.KeepAlive = new(KeepAlive)
209 }
210 if h.KeepAlive.ProbeInterval == 0 {
211 h.KeepAlive.ProbeInterval = caddy.Duration(30 * time.Second)
212 }
213 if h.KeepAlive.IdleConnTimeout == 0 {
214 h.KeepAlive.IdleConnTimeout = caddy.Duration(2 * time.Minute)
215 }
216 if h.KeepAlive.MaxIdleConnsPerHost == 0 {
217 h.KeepAlive.MaxIdleConnsPerHost = 32 // seems about optimal, see #2805
218 }
219
220 // Set a relatively short default dial timeout.
221 // This is helpful to make load-balancer retries more speedy.
222 if h.DialTimeout == 0 {
223 h.DialTimeout = caddy.Duration(3 * time.Second)
224 }
225
226 dialer := &net.Dialer{
227 Timeout: time.Duration(h.DialTimeout),
228 FallbackDelay: time.Duration(h.FallbackDelay),
229 }
230
231 if h.LocalAddress != "" {
232 netaddr, err := caddy.ParseNetworkAddressWithDefaults(h.LocalAddress, "tcp", 0)
233 if err != nil {
234 return nil, err
235 }
236 if netaddr.PortRangeSize() > 1 {
237 return nil, fmt.Errorf("local_address must be a single address, not a port range")
238 }
239 switch netaddr.Network {
240 case "tcp", "tcp4", "tcp6":
241 dialer.LocalAddr, err = net.ResolveTCPAddr(netaddr.Network, netaddr.JoinHostPort(0))
242 if err != nil {
243 return nil, err
244 }
245 case "unix", "unixgram", "unixpacket":
246 dialer.LocalAddr, err = net.ResolveUnixAddr(netaddr.Network, netaddr.JoinHostPort(0))
247 if err != nil {
248 return nil, err
249 }
250 case "udp", "udp4", "udp6":
251 return nil, fmt.Errorf("local_address must be a TCP address, not a UDP address")
252 default:
253 return nil, fmt.Errorf("unsupported network")
254 }
255 }
256 if h.Resolver != nil {
257 err := h.Resolver.ParseAddresses()
258 if err != nil {
259 return nil, err
260 }
261 d := &net.Dialer{
262 Timeout: time.Duration(h.DialTimeout),
263 FallbackDelay: time.Duration(h.FallbackDelay),
264 }
265 dialer.Resolver = &net.Resolver{
266 PreferGo: true,
267 Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
268 //nolint:gosec
269 addr := h.Resolver.netAddrs[weakrand.IntN(len(h.Resolver.netAddrs))]
270 return d.DialContext(ctx, addr.Network, addr.JoinHostPort(0))
271 },
272 }
273 }
274
275 dialContext := func(ctx context.Context, network, address string) (net.Conn, error) {
276 // The network is usually tcp, and the address is the host in http.Request.URL.Host
277 // and that's been overwritten in directRequest
278 // However, if proxy is used according to http.ProxyFromEnvironment or proxy providers,
279 // address will be the address of the proxy server.
280
281 // This means we can safely use the address in dialInfo if proxy is not used (the address and network will be same any way)
282 // or if the upstream is unix (because there is no way socks or http proxy can be used for unix address).
283 if dialInfo, ok := GetDialInfo(ctx); ok {
284 if caddyhttp.GetVar(ctx, proxyVarKey) == nil || strings.HasPrefix(dialInfo.Network, "unix") {
285 network = dialInfo.Network
286 address = dialInfo.Address
287 }
288 }
289
290 conn, err := dialer.DialContext(ctx, network, address)
291 if err != nil {
292 // identify this error as one that occurred during
293 // dialing, which can be important when trying to
294 // decide whether to retry a request
295 return nil, DialError{err}
296 }
297
298 if h.ProxyProtocol != "" {
299 proxyProtocolInfo, ok := caddyhttp.GetVar(ctx, proxyProtocolInfoVarKey).(ProxyProtocolInfo)
300 if !ok {
301 return nil, fmt.Errorf("failed to get proxy protocol info from context")
302 }
303 var proxyv byte
304 switch h.ProxyProtocol {
305 case "v1":
306 proxyv = 1
307 case "v2":
308 proxyv = 2
309 default:
310 return nil, fmt.Errorf("unexpected proxy protocol version")
311 }
312
313 // The src and dst have to be of the same address family. As we don't know the original
314 // dst address (it's kind of impossible to know) and this address is generally of very
315 // little interest, we just set it to all zeros.
316 var destAddr net.Addr
317 switch {
318 case proxyProtocolInfo.AddrPort.Addr().Is4():
319 destAddr = &net.TCPAddr{
320 IP: net.IPv4zero,
321 }
322 case proxyProtocolInfo.AddrPort.Addr().Is6():
323 destAddr = &net.TCPAddr{
324 IP: net.IPv6zero,
325 }
326 default:
327 return nil, fmt.Errorf("unexpected remote addr type in proxy protocol info")
328 }
329 sourceAddr := &net.TCPAddr{
330 IP: proxyProtocolInfo.AddrPort.Addr().AsSlice(),
331 Port: int(proxyProtocolInfo.AddrPort.Port()),
332 Zone: proxyProtocolInfo.AddrPort.Addr().Zone(),
333 }
334 header := proxyproto.HeaderProxyFromAddrs(proxyv, sourceAddr, destAddr)
335
336 // retain the log message structure
337 switch h.ProxyProtocol {
338 case "v1":
339 caddyCtx.Logger().Debug("sending proxy protocol header v1", zap.Any("header", header))
340 case "v2":
341 caddyCtx.Logger().Debug("sending proxy protocol header v2", zap.Any("header", header))
342 }
343
344 _, err = header.WriteTo(conn)
345 if err != nil {
346 // identify this error as one that occurred during
347 // dialing, which can be important when trying to
348 // decide whether to retry a request
349 return nil, DialError{err}
350 }
351 }
352
353 // if read/write timeouts are configured and this is a TCP connection,
354 // enforce the timeouts by wrapping the connection with our own type
355 if tcpConn, ok := conn.(*net.TCPConn); ok && (h.ReadTimeout > 0 || h.WriteTimeout > 0) {
356 conn = &tcpRWTimeoutConn{
357 TCPConn: tcpConn,
358 readTimeout: time.Duration(h.ReadTimeout),
359 writeTimeout: time.Duration(h.WriteTimeout),
360 logger: caddyCtx.Logger(),
361 }
362 }
363
364 return conn, nil
365 }
366
367 // negotiate any HTTP/SOCKS proxy for the HTTP transport
368 proxy := http.ProxyFromEnvironment
369 if h.ForwardProxyURL != "" {
370 caddyCtx.Logger().Warn("forward_proxy_url is deprecated; use network_proxy instead")
371 u := network.ProxyFromURL{URL: h.ForwardProxyURL}
372 h.NetworkProxyRaw = caddyconfig.JSONModuleObject(u, "from", "url", nil)
373 }
374 if len(h.NetworkProxyRaw) != 0 {
375 proxyMod, err := caddyCtx.LoadModule(h, "NetworkProxyRaw")
376 if err != nil {
377 return nil, fmt.Errorf("failed to load network_proxy module: %v", err)
378 }
379 if m, ok := proxyMod.(caddy.ProxyFuncProducer); ok {
380 proxy = m.ProxyFunc()
381 } else {
382 return nil, fmt.Errorf("network_proxy module is not `(func(*http.Request) (*url.URL, error))``")
383 }
384 }
385 // we need to keep track if a proxy is used for a request
386 proxyWrapper := func(req *http.Request) (*url.URL, error) {
387 if proxy == nil {
388 return nil, nil
389 }
390 u, err := proxy(req)
391 if u == nil || err != nil {
392 return u, err
393 }
394 // there must be a proxy for this request
395 caddyhttp.SetVar(req.Context(), proxyVarKey, u)
396 return u, nil
397 }
398
399 rt := &http.Transport{
400 Proxy: proxyWrapper,
401 DialContext: dialContext,
402 MaxConnsPerHost: h.MaxConnsPerHost,
403 ResponseHeaderTimeout: time.Duration(h.ResponseHeaderTimeout),
404 ExpectContinueTimeout: time.Duration(h.ExpectContinueTimeout),
405 MaxResponseHeaderBytes: h.MaxResponseHeaderSize,
406 WriteBufferSize: h.WriteBufferSize,
407 ReadBufferSize: h.ReadBufferSize,
408 }
409
410 if h.TLS != nil {
411 rt.TLSHandshakeTimeout = time.Duration(h.TLS.HandshakeTimeout)
412 var err error
413 rt.TLSClientConfig, err = h.TLS.MakeTLSClientConfig(caddyCtx)
414 if err != nil {
415 return nil, fmt.Errorf("making TLS client config: %v", err)
416 }
417
418 serverNameHasPlaceholder := strings.Contains(h.TLS.ServerName, "{")
419
420 // We need to use custom DialTLSContext if:
421 // 1. ServerName has a placeholder that needs to be replaced at request-time, OR
422 // 2. ProxyProtocol is enabled, because req.URL.Host is modified to include
423 // client address info with "->" separator which breaks Go's address parsing
424 if serverNameHasPlaceholder || h.ProxyProtocol != "" {
425 rt.DialTLSContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
426 // reuses the dialer from above to establish a plaintext connection
427 conn, err := dialContext(ctx, network, addr)
428 if err != nil {
429 return nil, err
430 }
431
432 // but add our own handshake logic
433 tlsConfig := rt.TLSClientConfig.Clone()
434 if serverNameHasPlaceholder {
435 repl := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
436 tlsConfig.ServerName = repl.ReplaceAll(tlsConfig.ServerName, "")
437 }
438
439 // h1 only
440 if caddyhttp.GetVar(ctx, tlsH1OnlyVarKey) == true {
441 // stdlib does this
442 // https://github.com/golang/go/blob/4837fbe4145cd47b43eed66fee9eed9c2b988316/src/net/http/transport.go#L1701
443 tlsConfig.NextProtos = nil
444 }
445
446 tlsConn := tls.Client(conn, tlsConfig)
447
448 // complete the handshake before returning the connection
449 if rt.TLSHandshakeTimeout != 0 {
450 var cancel context.CancelFunc
451 ctx, cancel = context.WithTimeoutCause(ctx, rt.TLSHandshakeTimeout, fmt.Errorf("HTTP transport TLS handshake %ds timeout", int(rt.TLSHandshakeTimeout.Seconds())))
452 defer cancel()
453 }
454 err = tlsConn.HandshakeContext(ctx)
455 if err != nil {
456 _ = tlsConn.Close()
457 return nil, err
458 }
459 return tlsConn, nil
460 }
461 }
462 }
463
464 if h.KeepAlive != nil {
465 // according to https://pkg.go.dev/net#Dialer.KeepAliveConfig,
466 // KeepAlive is ignored if KeepAliveConfig.Enable is true.
467 // If configured to 0, a system-dependent default is used.
468 // To disable tcp keepalive, choose a negative value,
469 // so KeepAliveConfig.Enable is false and KeepAlive is negative.
470
471 // This is different from http keepalive where a tcp connection
472 // can transfer multiple http requests/responses.
473 dialer.KeepAlive = time.Duration(h.KeepAlive.ProbeInterval)
474 dialer.KeepAliveConfig = net.KeepAliveConfig{
475 Enable: h.KeepAlive.ProbeInterval > 0,
476 Interval: time.Duration(h.KeepAlive.ProbeInterval),
477 }
478 if h.KeepAlive.Enabled != nil {
479 rt.DisableKeepAlives = !*h.KeepAlive.Enabled
480 }
481 rt.MaxIdleConns = h.KeepAlive.MaxIdleConns
482 rt.MaxIdleConnsPerHost = h.KeepAlive.MaxIdleConnsPerHost
483 rt.IdleConnTimeout = time.Duration(h.KeepAlive.IdleConnTimeout)
484 }
485
486 if h.Compression != nil {
487 rt.DisableCompression = !*h.Compression
488 }
489
490 // configure HTTP/3 transport if enabled; however, this does not
491 // automatically fall back to lower versions like most web browsers
492 // do (that'd add latency and complexity, besides, we expect that
493 // site owners control the backends), so it must be exclusive
494 if len(h.Versions) == 1 && h.Versions[0] == "3" {
495 h.h3Transport = new(http3.Transport)
496 if h.TLS != nil {
497 var err error
498 h.h3Transport.TLSClientConfig, err = h.TLS.MakeTLSClientConfig(caddyCtx)
499 if err != nil {
500 return nil, fmt.Errorf("making TLS client config for HTTP/3 transport: %v", err)
501 }
502 }
503 } else if len(h.Versions) > 1 && slices.Contains(h.Versions, "3") {
504 return nil, fmt.Errorf("if HTTP/3 is enabled to the upstream, no other HTTP versions are supported")
505 }
506
507 // if h2/c is enabled, configure it explicitly
508 if slices.Contains(h.Versions, "2") || slices.Contains(h.Versions, "h2c") {
509 if err := http2.ConfigureTransport(rt); err != nil {
510 return nil, err
511 }
512
513 // DisableCompression from h2 is configured by http2.ConfigureTransport
514 // Likewise, DisableKeepAlives from h1 is used too.
515
516 // Protocols field is only used when the request is not using TLS,
517 // http1/2 over tls is still allowed
518 if slices.Contains(h.Versions, "h2c") {
519 rt.Protocols = new(http.Protocols)
520 rt.Protocols.SetUnencryptedHTTP2(true)
521 rt.Protocols.SetHTTP1(false)
522 }
523 }
524
525 return rt, nil
526 }
527
528 // RequestHeaderOps implements TransportHeaderOpsProvider. It returns header
529 // operations for requests when the transport's configuration indicates they
530 // should be applied. In particular, when TLS is enabled for this transport,
531 // return an operation to set the Host header to the upstream host:port
532 // placeholder so HTTPS upstreams get the proper Host by default.
533 //
534 // Note: this is a provision-time hook; the Handler will call this during
535 // its Provision and cache the resulting HeaderOps. The HeaderOps are
536 // applied per-request (so placeholders are expanded at request time).
537 func (h *HTTPTransport) RequestHeaderOps() *headers.HeaderOps {
538 // If TLS is not configured for this transport, don't inject Host
539 // defaults. TLS being non-nil indicates HTTPS to the upstream.
540 if h.TLS == nil {
541 return nil
542 }
543 return &headers.HeaderOps{
544 Set: http.Header{
545 "Host": []string{"{http.reverse_proxy.upstream.hostport}"},
546 },
547 }
548 }
549
550 // RoundTrip implements http.RoundTripper.
551 func (h *HTTPTransport) RoundTrip(req *http.Request) (*http.Response, error) {
552 h.SetScheme(req)
553
554 // use HTTP/3 if enabled (TODO: This is EXPERIMENTAL)
555 if h.h3Transport != nil {
556 return h.h3Transport.RoundTrip(req)
557 }
558
559 return h.Transport.RoundTrip(req)
560 }
561
562 // SetScheme ensures that the outbound request req
563 // has the scheme set in its URL; the underlying
564 // http.Transport requires a scheme to be set.
565 //
566 // This method may be used by other transport modules
567 // that wrap/use this one.
568 func (h *HTTPTransport) SetScheme(req *http.Request) {
569 if req.URL.Scheme != "" {
570 return
571 }
572 if h.shouldUseTLS(req) {
573 req.URL.Scheme = "https"
574 } else {
575 req.URL.Scheme = "http"
576 }
577 }
578
579 // shouldUseTLS returns true if TLS should be used for req.
580 func (h *HTTPTransport) shouldUseTLS(req *http.Request) bool {
581 if h.TLS == nil {
582 return false
583 }
584
585 port := req.URL.Port()
586 return !slices.Contains(h.TLS.ExceptPorts, port)
587 }
588
589 // TLSEnabled returns true if TLS is enabled.
590 func (h HTTPTransport) TLSEnabled() bool {
591 return h.TLS != nil
592 }
593
594 // EnableTLS enables TLS on the transport.
595 func (h *HTTPTransport) EnableTLS(base *TLSConfig) error {
596 h.TLS = base
597 return nil
598 }
599
600 // EnableH2C enables H2C (HTTP/2 over Cleartext) on the transport.
601 func (h *HTTPTransport) EnableH2C() error {
602 h.Versions = []string{"h2c", "2"}
603 return nil
604 }
605
606 // OverrideHealthCheckScheme overrides the scheme of the given URL
607 // used for health checks.
608 func (h HTTPTransport) OverrideHealthCheckScheme(base *url.URL, port string) {
609 // if tls is enabled and the port isn't in the except list, use HTTPs
610 if h.TLSEnabled() && !slices.Contains(h.TLS.ExceptPorts, port) {
611 base.Scheme = "https"
612 }
613 }
614
615 // ProxyProtocolEnabled returns true if proxy protocol is enabled.
616 func (h HTTPTransport) ProxyProtocolEnabled() bool {
617 return h.ProxyProtocol != ""
618 }
619
620 // Cleanup implements caddy.CleanerUpper and closes any idle connections.
621 func (h HTTPTransport) Cleanup() error {
622 if h.Transport == nil {
623 return nil
624 }
625 h.Transport.CloseIdleConnections()
626 return nil
627 }
628
629 // TLSConfig holds configuration related to the TLS configuration for the
630 // transport/client.
631 type TLSConfig struct {
632 // Certificate authority module which provides the certificate pool of trusted certificates
633 CARaw json.RawMessage `json:"ca,omitempty" caddy:"namespace=tls.ca_pool.source inline_key=provider"`
634
635 // Deprecated: Use the `ca` field with the `tls.ca_pool.source.inline` module instead.
636 // Optional list of base64-encoded DER-encoded CA certificates to trust.
637 RootCAPool []string `json:"root_ca_pool,omitempty"`
638
639 // Deprecated: Use the `ca` field with the `tls.ca_pool.source.file` module instead.
640 // List of PEM-encoded CA certificate files to add to the same trust
641 // store as RootCAPool (or root_ca_pool in the JSON).
642 RootCAPEMFiles []string `json:"root_ca_pem_files,omitempty"`
643
644 // PEM-encoded client certificate filename to present to servers.
645 ClientCertificateFile string `json:"client_certificate_file,omitempty"`
646
647 // PEM-encoded key to use with the client certificate.
648 ClientCertificateKeyFile string `json:"client_certificate_key_file,omitempty"`
649
650 // If specified, Caddy will use and automate a client certificate
651 // with this subject name.
652 ClientCertificateAutomate string `json:"client_certificate_automate,omitempty"`
653
654 // If true, TLS verification of server certificates will be disabled.
655 // This is insecure and may be removed in the future. Do not use this
656 // option except in testing or local development environments.
657 InsecureSkipVerify bool `json:"insecure_skip_verify,omitempty"`
658
659 // The duration to allow a TLS handshake to a server. Default: No timeout.
660 HandshakeTimeout caddy.Duration `json:"handshake_timeout,omitempty"`
661
662 // The server name used when verifying the certificate received in the TLS
663 // handshake. By default, this will use the upstream address' host part.
664 // You only need to override this if your upstream address does not match the
665 // certificate the upstream is likely to use. For example if the upstream
666 // address is an IP address, then you would need to configure this to the
667 // hostname being served by the upstream server. Currently, this does not
668 // support placeholders because the TLS config is not provisioned on each
669 // connection, so a static value must be used.
670 ServerName string `json:"server_name,omitempty"`
671
672 // TLS renegotiation level. TLS renegotiation is the act of performing
673 // subsequent handshakes on a connection after the first.
674 // The level can be:
675 // - "never": (the default) disables renegotiation.
676 // - "once": allows a remote server to request renegotiation once per connection.
677 // - "freely": allows a remote server to repeatedly request renegotiation.
678 Renegotiation string `json:"renegotiation,omitempty"`
679
680 // Skip TLS ports specifies a list of upstream ports on which TLS should not be
681 // attempted even if it is configured. Handy when using dynamic upstreams that
682 // return HTTP and HTTPS endpoints too.
683 // When specified, TLS will automatically be configured on the transport.
684 // The value can be a list of any valid tcp port numbers, default empty.
685 ExceptPorts []string `json:"except_ports,omitempty"`
686
687 // The list of elliptic curves to support. Caddy's
688 // defaults are modern and secure.
689 Curves []string `json:"curves,omitempty"`
690 }
691
692 // MakeTLSClientConfig returns a tls.Config usable by a client to a backend.
693 // If there is no custom TLS configuration, a nil config may be returned.
694 func (t *TLSConfig) MakeTLSClientConfig(ctx caddy.Context) (*tls.Config, error) {
695 cfg := new(tls.Config)
696
697 // client auth
698 if t.ClientCertificateFile != "" && t.ClientCertificateKeyFile == "" {
699 return nil, fmt.Errorf("client_certificate_file specified without client_certificate_key_file")
700 }
701 if t.ClientCertificateFile == "" && t.ClientCertificateKeyFile != "" {
702 return nil, fmt.Errorf("client_certificate_key_file specified without client_certificate_file")
703 }
704 if t.ClientCertificateFile != "" && t.ClientCertificateKeyFile != "" {
705 cert, err := tls.LoadX509KeyPair(t.ClientCertificateFile, t.ClientCertificateKeyFile)
706 if err != nil {
707 return nil, fmt.Errorf("loading client certificate key pair: %v", err)
708 }
709 cfg.Certificates = []tls.Certificate{cert}
710 }
711 if t.ClientCertificateAutomate != "" {
712 // TODO: use or enable ctx.IdentityCredentials() ...
713 tlsAppIface, err := ctx.App("tls")
714 if err != nil {
715 return nil, fmt.Errorf("getting tls app: %v", err)
716 }
717 tlsApp := tlsAppIface.(*caddytls.TLS)
718 err = tlsApp.Manage(map[string]struct{}{t.ClientCertificateAutomate: {}})
719 if err != nil {
720 return nil, fmt.Errorf("managing client certificate: %v", err)
721 }
722 cfg.GetClientCertificate = func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) {
723 certs := caddytls.AllMatchingCertificates(t.ClientCertificateAutomate)
724 var err error
725 for _, cert := range certs {
726 certCertificate := cert.Certificate // avoid taking address of iteration variable (gosec warning)
727 err = cri.SupportsCertificate(&certCertificate)
728 if err == nil {
729 return &cert.Certificate, nil
730 }
731 }
732 if err == nil {
733 err = fmt.Errorf("no client certificate found for automate name: %s", t.ClientCertificateAutomate)
734 }
735 return nil, err
736 }
737 }
738
739 // trusted root CAs
740 if len(t.RootCAPool) > 0 || len(t.RootCAPEMFiles) > 0 {
741 ctx.Logger().Warn("root_ca_pool and root_ca_pem_files are deprecated. Use one of the tls.ca_pool.source modules instead")
742 rootPool := x509.NewCertPool()
743 for _, encodedCACert := range t.RootCAPool {
744 caCert, err := decodeBase64DERCert(encodedCACert)
745 if err != nil {
746 return nil, fmt.Errorf("parsing CA certificate: %v", err)
747 }
748 rootPool.AddCert(caCert)
749 }
750 for _, pemFile := range t.RootCAPEMFiles {
751 pemData, err := os.ReadFile(pemFile)
752 if err != nil {
753 return nil, fmt.Errorf("failed reading ca cert: %v", err)
754 }
755 rootPool.AppendCertsFromPEM(pemData)
756 }
757 cfg.RootCAs = rootPool
758 }
759
760 if t.CARaw != nil {
761 if len(t.RootCAPool) > 0 || len(t.RootCAPEMFiles) > 0 {
762 return nil, fmt.Errorf("conflicting config for Root CA pool")
763 }
764 caRaw, err := ctx.LoadModule(t, "CARaw")
765 if err != nil {
766 return nil, fmt.Errorf("failed to load ca module: %v", err)
767 }
768 ca, ok := caRaw.(caddytls.CA)
769 if !ok {
770 return nil, fmt.Errorf("CA module '%s' is not a certificate pool provider", ca)
771 }
772 cfg.RootCAs = ca.CertPool()
773 }
774
775 // Renegotiation
776 switch t.Renegotiation {
777 case "never", "":
778 cfg.Renegotiation = tls.RenegotiateNever
779 case "once":
780 cfg.Renegotiation = tls.RenegotiateOnceAsClient
781 case "freely":
782 cfg.Renegotiation = tls.RenegotiateFreelyAsClient
783 default:
784 return nil, fmt.Errorf("invalid TLS renegotiation level: %v", t.Renegotiation)
785 }
786
787 // override for the server name used verify the TLS handshake
788 cfg.ServerName = t.ServerName
789
790 // throw all security out the window
791 cfg.InsecureSkipVerify = t.InsecureSkipVerify
792
793 curvesAdded := make(map[tls.CurveID]struct{})
794 for _, curveName := range t.Curves {
795 curveID := caddytls.SupportedCurves[curveName]
796 if _, ok := curvesAdded[curveID]; !ok {
797 curvesAdded[curveID] = struct{}{}
798 cfg.CurvePreferences = append(cfg.CurvePreferences, curveID)
799 }
800 }
801
802 // only return a config if it's not empty
803 if reflect.DeepEqual(cfg, new(tls.Config)) {
804 return nil, nil
805 }
806
807 return cfg, nil
808 }
809
810 // KeepAlive holds configuration pertaining to HTTP Keep-Alive.
811 type KeepAlive struct {
812 // Whether HTTP Keep-Alive is enabled. Default: `true`
813 Enabled *bool `json:"enabled,omitempty"`
814
815 // How often to probe for liveness. Default: `30s`.
816 ProbeInterval caddy.Duration `json:"probe_interval,omitempty"`
817
818 // Maximum number of idle connections. Default: `0`, which means no limit.
819 MaxIdleConns int `json:"max_idle_conns,omitempty"`
820
821 // Maximum number of idle connections per host. Default: `32`.
822 MaxIdleConnsPerHost int `json:"max_idle_conns_per_host,omitempty"`
823
824 // How long connections should be kept alive when idle. Default: `2m`.
825 IdleConnTimeout caddy.Duration `json:"idle_timeout,omitempty"`
826 }
827
828 // tcpRWTimeoutConn enforces read/write timeouts for a TCP connection.
829 // If it fails to set deadlines, the error is logged but does not abort
830 // the read/write attempt (ignoring the error is consistent with what
831 // the standard library does: https://github.com/golang/go/blob/c5da4fb7ac5cb7434b41fc9a1df3bee66c7f1a4d/src/net/http/server.go#L981-L986)
832 type tcpRWTimeoutConn struct {
833 *net.TCPConn
834 readTimeout, writeTimeout time.Duration
835 logger *zap.Logger
836 }
837
838 func (c *tcpRWTimeoutConn) Read(b []byte) (int, error) {
839 if c.readTimeout > 0 {
840 err := c.TCPConn.SetReadDeadline(time.Now().Add(c.readTimeout))
841 if err != nil {
842 if ce := c.logger.Check(zapcore.ErrorLevel, "failed to set read deadline"); ce != nil {
843 ce.Write(zap.Error(err))
844 }
845 }
846 }
847 return c.TCPConn.Read(b)
848 }
849
850 func (c *tcpRWTimeoutConn) Write(b []byte) (int, error) {
851 if c.writeTimeout > 0 {
852 err := c.TCPConn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
853 if err != nil {
854 if ce := c.logger.Check(zapcore.ErrorLevel, "failed to set write deadline"); ce != nil {
855 ce.Write(zap.Error(err))
856 }
857 }
858 }
859 return c.TCPConn.Write(b)
860 }
861
862 // decodeBase64DERCert base64-decodes, then DER-decodes, certStr.
863 func decodeBase64DERCert(certStr string) (*x509.Certificate, error) {
864 // decode base64
865 derBytes, err := base64.StdEncoding.DecodeString(certStr)
866 if err != nil {
867 return nil, err
868 }
869
870 // parse the DER-encoded certificate
871 return x509.ParseCertificate(derBytes)
872 }
873
874 // Interface guards
875 var (
876 _ caddy.Provisioner = (*HTTPTransport)(nil)
877 _ http.RoundTripper = (*HTTPTransport)(nil)
878 _ caddy.CleanerUpper = (*HTTPTransport)(nil)
879 _ TLSTransport = (*HTTPTransport)(nil)
880 _ H2CTransport = (*HTTPTransport)(nil)
881 _ HealthCheckSchemeOverriderTransport = (*HTTPTransport)(nil)
882 _ ProxyProtocolTransport = (*HTTPTransport)(nil)
883 )