Debian Codegraph @

modules/caddyhttp/replacer.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 caddyhttp
16
17 import (
18 "bytes"
19 "context"
20 "crypto/ecdsa"
21 "crypto/ed25519"
22 "crypto/rsa"
23 "crypto/sha256"
24 "crypto/tls"
25 "crypto/x509"
26 "encoding/asn1"
27 "encoding/base64"
28 "encoding/pem"
29 "fmt"
30 "io"
31 "net"
32 "net/http"
33 "net/netip"
34 "net/textproto"
35 "net/url"
36 "path"
37 "strconv"
38 "strings"
39 "time"
40
41 "github.com/google/uuid"
42 "go.uber.org/zap"
43
44 "github.com/caddyserver/caddy/v2"
45 "github.com/caddyserver/caddy/v2/modules/caddytls"
46 )
47
48 // NewTestReplacer creates a replacer for an http.Request
49 // for use in tests that are not in this package
50 func NewTestReplacer(req *http.Request) *caddy.Replacer {
51 repl := caddy.NewReplacer()
52 ctx := context.WithValue(req.Context(), caddy.ReplacerCtxKey, repl)
53 *req = *req.WithContext(ctx)
54 addHTTPVarsToReplacer(repl, req, nil)
55 return repl
56 }
57
58 func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.ResponseWriter) {
59 SetVar(req.Context(), "start_time", time.Now())
60 SetVar(req.Context(), "uuid", new(requestID))
61
62 httpVars := func(key string) (any, bool) {
63 if req != nil {
64 // query string parameters
65 if strings.HasPrefix(key, reqURIQueryReplPrefix) {
66 vals := req.URL.Query()[key[len(reqURIQueryReplPrefix):]]
67 // always return true, since the query param might
68 // be present only in some requests
69 return strings.Join(vals, ","), true
70 }
71
72 // request header fields
73 if strings.HasPrefix(key, reqHeaderReplPrefix) {
74 field := key[len(reqHeaderReplPrefix):]
75 vals := req.Header[textproto.CanonicalMIMEHeaderKey(field)]
76 // always return true, since the header field might
77 // be present only in some requests
78 return strings.Join(vals, ","), true
79 }
80
81 // cookies
82 if strings.HasPrefix(key, reqCookieReplPrefix) {
83 name := key[len(reqCookieReplPrefix):]
84 for _, cookie := range req.Cookies() {
85 if strings.EqualFold(name, cookie.Name) {
86 // always return true, since the cookie might
87 // be present only in some requests
88 return cookie.Value, true
89 }
90 }
91 }
92
93 // http.request.tls.*
94 if strings.HasPrefix(key, reqTLSReplPrefix) {
95 return getReqTLSReplacement(req, key)
96 }
97
98 switch key {
99 case "http.request.method":
100 return req.Method, true
101 case "http.request.scheme":
102 if req.TLS != nil {
103 return "https", true
104 }
105 return "http", true
106 case "http.request.proto":
107 return req.Proto, true
108 case "http.request.host":
109 host, _, err := net.SplitHostPort(req.Host)
110 if err != nil {
111 return req.Host, true // OK; there probably was no port
112 }
113 return host, true
114 case "http.request.port":
115 _, port, _ := net.SplitHostPort(req.Host)
116 if portNum, err := strconv.Atoi(port); err == nil {
117 return portNum, true
118 }
119 return port, true
120 case "http.request.hostport":
121 return req.Host, true
122 case "http.request.local":
123 localAddr, _ := req.Context().Value(http.LocalAddrContextKey).(net.Addr)
124 return localAddr.String(), true
125 case "http.request.local.host":
126 localAddr, _ := req.Context().Value(http.LocalAddrContextKey).(net.Addr)
127 host, _, err := net.SplitHostPort(localAddr.String())
128 if err != nil {
129 // localAddr is host:port for tcp and udp sockets and /unix/socket.path
130 // for unix sockets. net.SplitHostPort only operates on tcp and udp sockets,
131 // not unix sockets and will fail with the latter.
132 // We assume when net.SplitHostPort fails, localAddr is a unix socket and thus
133 // already "split" and save to return.
134 return localAddr, true
135 }
136 return host, true
137 case "http.request.local.port":
138 localAddr, _ := req.Context().Value(http.LocalAddrContextKey).(net.Addr)
139 _, port, _ := net.SplitHostPort(localAddr.String())
140 if portNum, err := strconv.Atoi(port); err == nil {
141 return portNum, true
142 }
143 return port, true
144 case "http.request.remote":
145 if req.TLS != nil && !req.TLS.HandshakeComplete {
146 // without a complete handshake (QUIC "early data") we can't trust the remote IP address to not be spoofed
147 return nil, true
148 }
149 return req.RemoteAddr, true
150 case "http.request.remote.host":
151 if req.TLS != nil && !req.TLS.HandshakeComplete {
152 // without a complete handshake (QUIC "early data") we can't trust the remote IP address to not be spoofed
153 return nil, true
154 }
155 host, _, err := net.SplitHostPort(req.RemoteAddr)
156 if err != nil {
157 // req.RemoteAddr is host:port for tcp and udp sockets and /unix/socket.path
158 // for unix sockets. net.SplitHostPort only operates on tcp and udp sockets,
159 // not unix sockets and will fail with the latter.
160 // We assume when net.SplitHostPort fails, req.RemoteAddr is a unix socket
161 // and thus already "split" and save to return.
162 return req.RemoteAddr, true
163 }
164 return host, true
165 case "http.request.remote.port":
166 _, port, _ := net.SplitHostPort(req.RemoteAddr)
167 if portNum, err := strconv.Atoi(port); err == nil {
168 return portNum, true
169 }
170 return port, true
171
172 // current URI, including any internal rewrites
173 case "http.request.uri":
174 return req.URL.RequestURI(), true
175 case "http.request.uri_escaped":
176 return url.QueryEscape(req.URL.RequestURI()), true
177 case "http.request.uri.path":
178 return req.URL.Path, true
179 case "http.request.uri.path_escaped":
180 return url.QueryEscape(req.URL.Path), true
181 case "http.request.uri.path.file":
182 _, file := path.Split(req.URL.Path)
183 return file, true
184 case "http.request.uri.path.dir":
185 dir, _ := path.Split(req.URL.Path)
186 return dir, true
187 case "http.request.uri.path.file.base":
188 return strings.TrimSuffix(path.Base(req.URL.Path), path.Ext(req.URL.Path)), true
189 case "http.request.uri.path.file.ext":
190 return path.Ext(req.URL.Path), true
191 case "http.request.uri.query":
192 return req.URL.RawQuery, true
193 case "http.request.uri.query_escaped":
194 return url.QueryEscape(req.URL.RawQuery), true
195 case "http.request.uri.prefixed_query":
196 if req.URL.RawQuery == "" {
197 return "", true
198 }
199 return "?" + req.URL.RawQuery, true
200 case "http.request.duration":
201 start := GetVar(req.Context(), "start_time").(time.Time)
202 return time.Since(start), true
203 case "http.request.duration_ms":
204 start := GetVar(req.Context(), "start_time").(time.Time)
205 return time.Since(start).Seconds() * 1e3, true // multiply seconds to preserve decimal (see #4666)
206
207 case "http.request.uuid":
208 // fetch the UUID for this request
209 id := GetVar(req.Context(), "uuid").(*requestID)
210
211 // set it to this request's access log
212 extra := req.Context().Value(ExtraLogFieldsCtxKey).(*ExtraLogFields)
213 extra.Set(zap.String("uuid", id.String()))
214
215 return id.String(), true
216
217 case "http.request.body":
218 if req.Body == nil {
219 return "", true
220 }
221 // normally net/http will close the body for us, but since we
222 // are replacing it with a fake one, we have to ensure we close
223 // the real body ourselves when we're done
224 defer req.Body.Close()
225 // read the request body into a buffer (can't pool because we
226 // don't know its lifetime and would have to make a copy anyway)
227 buf := new(bytes.Buffer)
228 _, _ = io.Copy(buf, req.Body) // can't handle error, so just ignore it
229 req.Body = io.NopCloser(buf) // replace real body with buffered data
230 return buf.String(), true
231
232 case "http.request.body_base64":
233 if req.Body == nil {
234 return "", true
235 }
236 // normally net/http will close the body for us, but since we
237 // are replacing it with a fake one, we have to ensure we close
238 // the real body ourselves when we're done
239 defer req.Body.Close()
240 // read the request body into a buffer (can't pool because we
241 // don't know its lifetime and would have to make a copy anyway)
242 buf := new(bytes.Buffer)
243 _, _ = io.Copy(buf, req.Body) // can't handle error, so just ignore it
244 req.Body = io.NopCloser(buf) // replace real body with buffered data
245 return base64.StdEncoding.EncodeToString(buf.Bytes()), true
246
247 // original request, before any internal changes
248 case "http.request.orig_method":
249 or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request)
250 return or.Method, true
251 case "http.request.orig_uri":
252 or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request)
253 return or.RequestURI, true
254 case "http.request.orig_uri.path":
255 or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request)
256 return or.URL.Path, true
257 case "http.request.orig_uri.path.file":
258 or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request)
259 _, file := path.Split(or.URL.Path)
260 return file, true
261 case "http.request.orig_uri.path.dir":
262 or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request)
263 dir, _ := path.Split(or.URL.Path)
264 return dir, true
265 case "http.request.orig_uri.query":
266 or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request)
267 return or.URL.RawQuery, true
268 case "http.request.orig_uri.prefixed_query":
269 or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request)
270 if or.URL.RawQuery == "" {
271 return "", true
272 }
273 return "?" + or.URL.RawQuery, true
274 }
275
276 // remote IP range/prefix (e.g. keep top 24 bits of 1.2.3.4 => "1.2.3.0/24")
277 // syntax: "/V4,V6" where V4 = IPv4 bits, and V6 = IPv6 bits; if no comma, then same bit length used for both
278 // (EXPERIMENTAL)
279 if strings.HasPrefix(key, "http.request.remote.host/") {
280 host, _, err := net.SplitHostPort(req.RemoteAddr)
281 if err != nil {
282 host = req.RemoteAddr // assume no port, I guess?
283 }
284 addr, err := netip.ParseAddr(host)
285 if err != nil {
286 return host, true // not an IP address
287 }
288 // extract the bits from the end of the placeholder (start after "/") then split on ","
289 bitsBoth := key[strings.Index(key, "/")+1:]
290 ipv4BitsStr, ipv6BitsStr, cutOK := strings.Cut(bitsBoth, ",")
291 bitsStr := ipv4BitsStr
292 if addr.Is6() && cutOK {
293 bitsStr = ipv6BitsStr
294 }
295 // convert to integer then compute prefix
296 bits, err := strconv.Atoi(bitsStr)
297 if err != nil {
298 return "", true
299 }
300 prefix, err := addr.Prefix(bits)
301 if err != nil {
302 return "", true
303 }
304 return prefix.String(), true
305 }
306
307 // hostname labels (case insensitive, so normalize to lowercase)
308 if strings.HasPrefix(key, reqHostLabelsReplPrefix) {
309 idxStr := key[len(reqHostLabelsReplPrefix):]
310 idx, err := strconv.Atoi(idxStr)
311 if err != nil || idx < 0 {
312 return "", false
313 }
314 reqHost, _, err := net.SplitHostPort(req.Host)
315 if err != nil {
316 reqHost = req.Host // OK; assume there was no port
317 }
318 hostLabels := strings.Split(reqHost, ".")
319 if idx >= len(hostLabels) {
320 return "", true
321 }
322 return strings.ToLower(hostLabels[len(hostLabels)-idx-1]), true
323 }
324
325 // path parts
326 if strings.HasPrefix(key, reqURIPathReplPrefix) {
327 idxStr := key[len(reqURIPathReplPrefix):]
328 idx, err := strconv.Atoi(idxStr)
329 if err != nil {
330 return "", false
331 }
332 pathParts := strings.Split(req.URL.Path, "/")
333 if len(pathParts) > 0 && pathParts[0] == "" {
334 pathParts = pathParts[1:]
335 }
336 if idx < 0 {
337 return "", false
338 }
339 if idx >= len(pathParts) {
340 return "", true
341 }
342 return pathParts[idx], true
343 }
344
345 // orig uri path parts
346 if strings.HasPrefix(key, reqOrigURIPathReplPrefix) {
347 idxStr := key[len(reqOrigURIPathReplPrefix):]
348 idx, err := strconv.Atoi(idxStr)
349 if err != nil {
350 return "", false
351 }
352 or, _ := req.Context().Value(OriginalRequestCtxKey).(http.Request)
353 pathParts := strings.Split(or.URL.Path, "/")
354 if len(pathParts) > 0 && pathParts[0] == "" {
355 pathParts = pathParts[1:]
356 }
357 if idx < 0 {
358 return "", false
359 }
360 if idx >= len(pathParts) {
361 return "", true
362 }
363 return pathParts[idx], true
364 }
365
366 // middleware variables
367 if strings.HasPrefix(key, varsReplPrefix) {
368 varName := key[len(varsReplPrefix):]
369 raw := GetVar(req.Context(), varName)
370 // variables can be dynamic, so always return true
371 // even when it may not be set; treat as empty then
372 return raw, true
373 }
374 }
375
376 if w != nil {
377 // response header fields
378 if strings.HasPrefix(key, respHeaderReplPrefix) {
379 field := key[len(respHeaderReplPrefix):]
380 vals := w.Header()[textproto.CanonicalMIMEHeaderKey(field)]
381 // always return true, since the header field might
382 // be present only in some responses
383 return strings.Join(vals, ","), true
384 }
385 }
386
387 switch key {
388 case "http.shutting_down":
389 server := req.Context().Value(ServerCtxKey).(*Server)
390 return server.shutdownAt.Load() != nil, true
391 case "http.time_until_shutdown":
392 server := req.Context().Value(ServerCtxKey).(*Server)
393 t := server.shutdownAt.Load()
394 if t == nil {
395 return nil, true
396 }
397 return time.Until(*t), true
398 }
399
400 return nil, false
401 }
402
403 repl.Map(httpVars)
404 }
405
406 func getReqTLSReplacement(req *http.Request, key string) (any, bool) {
407 if req == nil || req.TLS == nil {
408 return nil, false
409 }
410
411 if len(key) < len(reqTLSReplPrefix) {
412 return nil, false
413 }
414
415 field := strings.ToLower(key[len(reqTLSReplPrefix):])
416
417 if strings.HasPrefix(field, "client.") {
418 cert := getTLSPeerCert(req.TLS)
419 if cert == nil {
420 // Instead of returning (nil, false) here, we set it to a dummy
421 // value to fix #7530. This way, even if there is no client cert,
422 // evaluating placeholders with ReplaceKnown() will still remove
423 // the placeholder, which would be expected. It is not expected
424 // for the placeholder to sometimes get removed based on whether
425 // the client presented a cert. We also do not return true here
426 // because we probably should remain accurate about whether a
427 // placeholder is, in fact, known or not.
428 // (This allocation may be slightly inefficient.)
429 cert = new(x509.Certificate)
430 }
431
432 // subject alternate names (SANs)
433 if strings.HasPrefix(field, "client.san.") {
434 field = field[len("client.san."):]
435 var fieldName string
436 var fieldValue any
437 switch {
438 case strings.HasPrefix(field, "dns_names"):
439 fieldName = "dns_names"
440 fieldValue = cert.DNSNames
441 case strings.HasPrefix(field, "emails"):
442 fieldName = "emails"
443 fieldValue = cert.EmailAddresses
444 case strings.HasPrefix(field, "ips"):
445 fieldName = "ips"
446 fieldValue = cert.IPAddresses
447 case strings.HasPrefix(field, "uris"):
448 fieldName = "uris"
449 fieldValue = cert.URIs
450 default:
451 return nil, false
452 }
453 field = field[len(fieldName):]
454
455 // if no index was specified, return the whole list
456 if field == "" {
457 return fieldValue, true
458 }
459 if len(field) < 2 || field[0] != '.' {
460 return nil, false
461 }
462 field = field[1:] // trim '.' between field name and index
463
464 // get the numeric index
465 idx, err := strconv.Atoi(field)
466 if err != nil || idx < 0 {
467 return nil, false
468 }
469
470 // access the indexed element and return it
471 switch v := fieldValue.(type) {
472 case []string:
473 if idx >= len(v) {
474 return nil, true
475 }
476 return v[idx], true
477 case []net.IP:
478 if idx >= len(v) {
479 return nil, true
480 }
481 return v[idx], true
482 case []*url.URL:
483 if idx >= len(v) {
484 return nil, true
485 }
486 return v[idx], true
487 }
488 }
489
490 switch field {
491 case "client.fingerprint":
492 return fmt.Sprintf("%x", sha256.Sum256(cert.Raw)), true
493 case "client.public_key", "client.public_key_sha256":
494 if cert.PublicKey == nil {
495 return nil, true
496 }
497 pubKeyBytes, err := marshalPublicKey(cert.PublicKey)
498 if err != nil {
499 return nil, true
500 }
501 if strings.HasSuffix(field, "_sha256") {
502 return fmt.Sprintf("%x", sha256.Sum256(pubKeyBytes)), true
503 }
504 return fmt.Sprintf("%x", pubKeyBytes), true
505 case "client.issuer":
506 return cert.Issuer, true
507 case "client.serial":
508 return cert.SerialNumber, true
509 case "client.subject":
510 return cert.Subject, true
511 case "client.certificate_pem":
512 block := pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}
513 return pem.EncodeToMemory(&block), true
514 case "client.certificate_der_base64":
515 return base64.StdEncoding.EncodeToString(cert.Raw), true
516 default:
517 return nil, false
518 }
519 }
520
521 switch field {
522 case "version":
523 return caddytls.ProtocolName(req.TLS.Version), true
524 case "cipher_suite":
525 return tls.CipherSuiteName(req.TLS.CipherSuite), true
526 case "resumed":
527 return req.TLS.DidResume, true
528 case "proto":
529 return req.TLS.NegotiatedProtocol, true
530 case "proto_mutual":
531 // req.TLS.NegotiatedProtocolIsMutual is deprecated - it's always true.
532 return true, true
533 case "server_name":
534 return req.TLS.ServerName, true
535 case "ech":
536 return req.TLS.ECHAccepted, true
537 }
538 return nil, false
539 }
540
541 // marshalPublicKey returns the byte encoding of pubKey.
542 func marshalPublicKey(pubKey any) ([]byte, error) {
543 switch key := pubKey.(type) {
544 case *rsa.PublicKey:
545 return asn1.Marshal(key)
546 case *ecdsa.PublicKey:
547 e, err := key.ECDH()
548 if err != nil {
549 return nil, err
550 }
551 return e.Bytes(), nil
552 case ed25519.PublicKey:
553 return key, nil
554 }
555 return nil, fmt.Errorf("unrecognized public key type: %T", pubKey)
556 }
557
558 // getTLSPeerCert retrieves the first peer certificate from a TLS session.
559 // Returns nil if no peer cert is in use.
560 func getTLSPeerCert(cs *tls.ConnectionState) *x509.Certificate {
561 if len(cs.PeerCertificates) == 0 {
562 return nil
563 }
564 return cs.PeerCertificates[0]
565 }
566
567 type requestID struct {
568 value string
569 }
570
571 // Lazy generates UUID string or return cached value if present
572 func (rid *requestID) String() string {
573 if rid.value == "" {
574 if id, err := uuid.NewRandom(); err == nil {
575 rid.value = id.String()
576 }
577 }
578 return rid.value
579 }
580
581 const (
582 reqCookieReplPrefix = "http.request.cookie."
583 reqHeaderReplPrefix = "http.request.header."
584 reqHostLabelsReplPrefix = "http.request.host.labels."
585 reqTLSReplPrefix = "http.request.tls."
586 reqURIPathReplPrefix = "http.request.uri.path."
587 reqURIQueryReplPrefix = "http.request.uri.query."
588 respHeaderReplPrefix = "http.response.header."
589 varsReplPrefix = "http.vars."
590 reqOrigURIPathReplPrefix = "http.request.orig_uri.path."
591 )