Debian Codegraph @

modules/caddyhttp/rewrite/rewrite.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 rewrite
16
17 import (
18 "fmt"
19 "net/http"
20 "net/url"
21 "regexp"
22 "strconv"
23 "strings"
24
25 "go.uber.org/zap"
26
27 "github.com/caddyserver/caddy/v2"
28 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
29 )
30
31 func init() {
32 caddy.RegisterModule(Rewrite{})
33 }
34
35 // Rewrite is a middleware which can rewrite/mutate HTTP requests.
36 //
37 // The Method and URI properties are "setters" (the request URI
38 // will be overwritten with the given values). Other properties are
39 // "modifiers" (they modify existing values in a differentiable
40 // way). It is atypical to combine the use of setters and
41 // modifiers in a single rewrite.
42 //
43 // To ensure consistent behavior, prefix and suffix stripping is
44 // performed in the URL-decoded (unescaped, normalized) space by
45 // default except for the specific bytes where an escape sequence
46 // is used in the prefix or suffix pattern.
47 //
48 // For all modifiers, paths are cleaned before being modified so that
49 // multiple, consecutive slashes are collapsed into a single slash,
50 // and dot elements are resolved and removed. In the special case
51 // of a prefix, suffix, or substring containing "//" (repeated slashes),
52 // slashes will not be merged while cleaning the path so that
53 // the rewrite can be interpreted literally.
54 type Rewrite struct {
55 // Changes the request's HTTP verb.
56 Method string `json:"method,omitempty"`
57
58 // Changes the request's URI, which consists of path and query string.
59 // Only components of the URI that are specified will be changed.
60 // For example, a value of "/foo.html" or "foo.html" will only change
61 // the path and will preserve any existing query string. Similarly, a
62 // value of "?a=b" will only change the query string and will not affect
63 // the path. Both can also be changed: "/foo?a=b" - this sets both the
64 // path and query string at the same time.
65 //
66 // You can also use placeholders. For example, to preserve the existing
67 // query string, you might use: "?{http.request.uri.query}&a=b". Any
68 // key-value pairs you add to the query string will not overwrite
69 // existing values (individual pairs are append-only).
70 //
71 // To clear the query string, explicitly set an empty one: "?"
72 URI string `json:"uri,omitempty"`
73
74 // Strips the given prefix from the beginning of the URI path.
75 // The prefix should be written in normalized (unescaped) form,
76 // but if an escaping (`%xx`) is used, the path will be required
77 // to have that same escape at that position in order to match.
78 StripPathPrefix string `json:"strip_path_prefix,omitempty"`
79
80 // Strips the given suffix from the end of the URI path.
81 // The suffix should be written in normalized (unescaped) form,
82 // but if an escaping (`%xx`) is used, the path will be required
83 // to have that same escape at that position in order to match.
84 StripPathSuffix string `json:"strip_path_suffix,omitempty"`
85
86 // Performs substring replacements on the URI.
87 URISubstring []substrReplacer `json:"uri_substring,omitempty"`
88
89 // Performs regular expression replacements on the URI path.
90 PathRegexp []*regexReplacer `json:"path_regexp,omitempty"`
91
92 // Mutates the query string of the URI.
93 Query *queryOps `json:"query,omitempty"`
94
95 logger *zap.Logger
96 }
97
98 // CaddyModule returns the Caddy module information.
99 func (Rewrite) CaddyModule() caddy.ModuleInfo {
100 return caddy.ModuleInfo{
101 ID: "http.handlers.rewrite",
102 New: func() caddy.Module { return new(Rewrite) },
103 }
104 }
105
106 // Provision sets up rewr.
107 func (rewr *Rewrite) Provision(ctx caddy.Context) error {
108 rewr.logger = ctx.Logger()
109
110 for i, rep := range rewr.PathRegexp {
111 if rep.Find == "" {
112 return fmt.Errorf("path_regexp find cannot be empty")
113 }
114 re, err := regexp.Compile(rep.Find)
115 if err != nil {
116 return fmt.Errorf("compiling regular expression %d: %v", i, err)
117 }
118 rep.re = re
119 }
120 if rewr.Query != nil {
121 for _, replacementOp := range rewr.Query.Replace {
122 err := replacementOp.Provision(ctx)
123 if err != nil {
124 return fmt.Errorf("compiling regular expression %s in query rewrite replace operation: %v", replacementOp.SearchRegexp, err)
125 }
126 }
127 }
128
129 return nil
130 }
131
132 func (rewr Rewrite) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
133 repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
134 const message = "rewrote request"
135
136 c := rewr.logger.Check(zap.DebugLevel, message)
137 if c == nil {
138 rewr.Rewrite(r, repl)
139 return next.ServeHTTP(w, r)
140 }
141
142 changed := rewr.Rewrite(r, repl)
143
144 if changed {
145 c.Write(
146 zap.Object("request", caddyhttp.LoggableHTTPRequest{Request: r}),
147 zap.String("method", r.Method),
148 zap.String("uri", r.RequestURI),
149 )
150 }
151
152 return next.ServeHTTP(w, r)
153 }
154
155 // rewrite performs the rewrites on r using repl, which should
156 // have been obtained from r, but is passed in for efficiency.
157 // It returns true if any changes were made to r.
158 func (rewr Rewrite) Rewrite(r *http.Request, repl *caddy.Replacer) bool {
159 oldMethod := r.Method
160 oldURI := r.RequestURI
161
162 // method
163 if rewr.Method != "" {
164 r.Method = strings.ToUpper(repl.ReplaceAll(rewr.Method, ""))
165 }
166
167 // uri (path, query string and... fragment, because why not)
168 if uri := rewr.URI; uri != "" {
169 // find the bounds of each part of the URI that exist
170 pathStart, qsStart, fragStart := -1, -1, -1
171 pathEnd, qsEnd := -1, -1
172 loop:
173 for i, ch := range uri {
174 switch {
175 case ch == '?' && qsStart < 0:
176 pathEnd, qsStart = i, i+1
177 case ch == '#' && fragStart < 0: // everything after fragment is fragment (very clear in RFC 3986 section 4.2)
178 if qsStart < 0 {
179 pathEnd = i
180 } else {
181 qsEnd = i
182 }
183 fragStart = i + 1
184 break loop
185 case pathStart < 0 && qsStart < 0:
186 pathStart = i
187 }
188 }
189 if pathStart >= 0 && pathEnd < 0 {
190 pathEnd = len(uri)
191 }
192 if qsStart >= 0 && qsEnd < 0 {
193 qsEnd = len(uri)
194 }
195
196 // isolate the three main components of the URI
197 var path, query, frag string
198 if pathStart > -1 {
199 path = uri[pathStart:pathEnd]
200 }
201 if qsStart > -1 {
202 query = uri[qsStart:qsEnd]
203 }
204 if fragStart > -1 {
205 frag = uri[fragStart:]
206 }
207
208 // build components which are specified, and store them
209 // in a temporary variable so that they all read the
210 // same version of the URI
211 var newPath, newQuery, newFrag string
212
213 if path != "" {
214 path = escapePathPlaceholders(path, r, repl)
215 newPath = repl.ReplaceAll(path, "")
216 }
217
218 // before continuing, we need to check if a query string
219 // snuck into the path component during replacements
220 if before, after, found := strings.Cut(newPath, "?"); found {
221 // recompute; new path contains a query string
222 var injectedQuery string
223 newPath, injectedQuery = before, after
224 // don't overwrite explicitly-configured query string
225 if query == "" {
226 // the injected query came from the first-pass placeholder
227 // expansion above, which means any '{' or '}' bytes in it
228 // must have come from replacement values (e.g. a request
229 // header), not from operator-written placeholder syntax.
230 // escape them so buildQueryString does not re-expand them,
231 // which would allow attacker input like {env.SECRET} to be
232 // evaluated (see GHSA-j8px-rmrx-76h9).
233 injectedQuery = strings.ReplaceAll(injectedQuery, "{", "%7B")
234 injectedQuery = strings.ReplaceAll(injectedQuery, "}", "%7D")
235 query = injectedQuery
236 }
237 }
238
239 if query != "" {
240 newQuery = buildQueryString(query, repl)
241 }
242 if frag != "" {
243 newFrag = repl.ReplaceAll(frag, "")
244 }
245
246 // update the URI with the new components
247 // only after building them
248 if pathStart >= 0 {
249 if path, err := url.PathUnescape(newPath); err != nil {
250 r.URL.Path = newPath
251 } else {
252 r.URL.Path = path
253 }
254 r.URL.RawPath = "" // force recomputing when EscapedPath() is called
255 }
256 if qsStart >= 0 {
257 r.URL.RawQuery = newQuery
258 }
259 if fragStart >= 0 {
260 r.URL.Fragment = newFrag
261 }
262 }
263
264 // strip path prefix or suffix
265 if rewr.StripPathPrefix != "" {
266 prefix := repl.ReplaceAll(rewr.StripPathPrefix, "")
267 if !strings.HasPrefix(prefix, "/") {
268 prefix = "/" + prefix
269 }
270 mergeSlashes := !strings.Contains(prefix, "//")
271 changePath(r, func(escapedPath string) string {
272 escapedPath = caddyhttp.CleanPath(escapedPath, mergeSlashes)
273 return trimPathPrefix(escapedPath, prefix)
274 })
275 }
276 if rewr.StripPathSuffix != "" {
277 suffix := repl.ReplaceAll(rewr.StripPathSuffix, "")
278 mergeSlashes := !strings.Contains(suffix, "//")
279 changePath(r, func(escapedPath string) string {
280 escapedPath = caddyhttp.CleanPath(escapedPath, mergeSlashes)
281 return reverse(trimPathPrefix(reverse(escapedPath), reverse(suffix)))
282 })
283 }
284
285 // substring replacements in URI
286 for _, rep := range rewr.URISubstring {
287 rep.do(r, repl)
288 }
289
290 // regular expression replacements on the path
291 for _, rep := range rewr.PathRegexp {
292 rep.do(r, repl)
293 }
294
295 // apply query operations
296 if rewr.Query != nil {
297 rewr.Query.do(r, repl)
298 }
299
300 // update the encoded copy of the URI
301 r.RequestURI = r.URL.RequestURI()
302
303 // return true if anything changed
304 return r.Method != oldMethod || r.RequestURI != oldURI
305 }
306
307 func escapePathPlaceholders(path string, r *http.Request, repl *caddy.Replacer) string {
308 // Replace path-valued placeholders in escaped form before the URI is parsed,
309 // otherwise literal '?' and '%' bytes from the path can be interpreted as URI
310 // delimiters or percent-escape sequences during the rewrite.
311 pathPlaceholder := "{http.request.uri.path}"
312 if strings.Contains(path, pathPlaceholder) {
313 path = strings.ReplaceAll(path, pathPlaceholder, r.URL.EscapedPath())
314 }
315
316 fileMatchRelativePlaceholder := "{http.matchers.file.relative}"
317 if strings.Contains(path, fileMatchRelativePlaceholder) {
318 if val, ok := repl.Get("http.matchers.file.relative"); ok {
319 if relativePath, ok := val.(string); ok {
320 path = strings.ReplaceAll(path, fileMatchRelativePlaceholder, escapePathPreservingSlashes(relativePath))
321 }
322 }
323 }
324
325 return path
326 }
327
328 func escapePathPreservingSlashes(path string) string {
329 return strings.ReplaceAll(url.PathEscape(path), "%2F", "/")
330 }
331
332 // buildQueryString takes an input query string and
333 // performs replacements on each component, returning
334 // the resulting query string. This function appends
335 // duplicate keys rather than replaces.
336 func buildQueryString(qs string, repl *caddy.Replacer) string {
337 var sb strings.Builder
338
339 // first component must be key, which is the same
340 // as if we just wrote a value in previous iteration
341 wroteVal := true
342
343 for len(qs) > 0 {
344 // determine the end of this component, which will be at
345 // the next equal sign or ampersand, whichever comes first
346 nextEq, nextAmp := strings.Index(qs, "="), strings.Index(qs, "&")
347 ampIsNext := nextAmp >= 0 && (nextAmp < nextEq || nextEq < 0)
348 end := len(qs) // assume no delimiter remains...
349 if ampIsNext {
350 end = nextAmp // ...unless ampersand is first...
351 } else if nextEq >= 0 && (nextEq < nextAmp || nextAmp < 0) {
352 end = nextEq // ...or unless equal is first.
353 }
354
355 // consume the component and write the result
356 comp := qs[:end]
357 comp, _ = repl.ReplaceFunc(comp, func(name string, val any) (any, error) {
358 if name == "http.request.uri.query" && wroteVal {
359 return val, nil // already escaped
360 }
361 var valStr string
362 switch v := val.(type) {
363 case string:
364 valStr = v
365 case fmt.Stringer:
366 valStr = v.String()
367 case int:
368 valStr = strconv.Itoa(v)
369 default:
370 valStr = fmt.Sprintf("%+v", v)
371 }
372 return url.QueryEscape(valStr), nil
373 })
374 if end < len(qs) {
375 end++ // consume delimiter
376 }
377 qs = qs[end:]
378
379 // if previous iteration wrote a value,
380 // that means we are writing a key
381 if wroteVal {
382 if sb.Len() > 0 && len(comp) > 0 {
383 sb.WriteRune('&')
384 }
385 } else {
386 sb.WriteRune('=')
387 }
388 sb.WriteString(comp)
389
390 // remember for the next iteration that we just wrote a value,
391 // which means the next iteration MUST write a key
392 wroteVal = ampIsNext
393 }
394
395 return sb.String()
396 }
397
398 // trimPathPrefix is like strings.TrimPrefix, but customized for advanced URI
399 // path prefix matching. The string prefix will be trimmed from the beginning
400 // of escapedPath if escapedPath starts with prefix. Rather than a naive 1:1
401 // comparison of each byte to determine if escapedPath starts with prefix,
402 // both strings are iterated in lock-step, and if prefix has a '%' encoding
403 // at a particular position, escapedPath must also have the same encoding
404 // representation for that character. In other words, if the prefix string
405 // uses the escaped form for a character, escapedPath must literally use the
406 // same escape at that position. Otherwise, all character comparisons are
407 // performed in normalized/unescaped space.
408 func trimPathPrefix(escapedPath, prefix string) string {
409 var iPath, iPrefix int
410 for iPath < len(escapedPath) && iPrefix < len(prefix) {
411 prefixCh := prefix[iPrefix]
412 ch := string(escapedPath[iPath])
413
414 if ch == "%" && prefixCh != '%' && len(escapedPath) >= iPath+3 {
415 var err error
416 ch, err = url.PathUnescape(escapedPath[iPath : iPath+3])
417 if err != nil {
418 // should be impossible unless EscapedPath() is returning invalid values!
419 return escapedPath
420 }
421 iPath += 2
422 }
423
424 // prefix comparisons are case-insensitive to consistency with
425 // path matcher, which is case-insensitive for good reasons
426 if !strings.EqualFold(ch, string(prefixCh)) {
427 return escapedPath
428 }
429
430 iPath++
431 iPrefix++
432 }
433
434 // if we iterated through the entire prefix, we found it, so trim it
435 if iPath >= len(prefix) {
436 return escapedPath[iPath:]
437 }
438
439 // otherwise we did not find the prefix
440 return escapedPath
441 }
442
443 func reverse(s string) string {
444 r := []rune(s)
445 for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 {
446 r[i], r[j] = r[j], r[i]
447 }
448 return string(r)
449 }
450
451 // substrReplacer describes either a simple and fast substring replacement.
452 type substrReplacer struct {
453 // A substring to find. Supports placeholders.
454 Find string `json:"find,omitempty"`
455
456 // The substring to replace with. Supports placeholders.
457 Replace string `json:"replace,omitempty"`
458
459 // Maximum number of replacements per string.
460 // Set to <= 0 for no limit (default).
461 Limit int `json:"limit,omitempty"`
462 }
463
464 // do performs the substring replacement on r.
465 func (rep substrReplacer) do(r *http.Request, repl *caddy.Replacer) {
466 if rep.Find == "" {
467 return
468 }
469
470 lim := rep.Limit
471 if lim == 0 {
472 lim = -1
473 }
474
475 find := repl.ReplaceAll(rep.Find, "")
476 replace := repl.ReplaceAll(rep.Replace, "")
477
478 mergeSlashes := !strings.Contains(rep.Find, "//")
479
480 changePath(r, func(pathOrRawPath string) string {
481 return strings.Replace(caddyhttp.CleanPath(pathOrRawPath, mergeSlashes), find, replace, lim)
482 })
483
484 r.URL.RawQuery = strings.Replace(r.URL.RawQuery, find, replace, lim)
485 }
486
487 // regexReplacer describes a replacement using a regular expression.
488 type regexReplacer struct {
489 // The regular expression to find.
490 Find string `json:"find,omitempty"`
491
492 // The substring to replace with. Supports placeholders and
493 // regular expression capture groups.
494 Replace string `json:"replace,omitempty"`
495
496 re *regexp.Regexp
497 }
498
499 func (rep regexReplacer) do(r *http.Request, repl *caddy.Replacer) {
500 if rep.Find == "" || rep.re == nil {
501 return
502 }
503 replace := repl.ReplaceAll(rep.Replace, "")
504 changePath(r, func(pathOrRawPath string) string {
505 return rep.re.ReplaceAllString(pathOrRawPath, replace)
506 })
507 }
508
509 func changePath(req *http.Request, newVal func(pathOrRawPath string) string) {
510 req.URL.RawPath = newVal(req.URL.EscapedPath())
511 if p, err := url.PathUnescape(req.URL.RawPath); err == nil && p != "" {
512 req.URL.Path = p
513 } else {
514 req.URL.Path = newVal(req.URL.Path)
515 }
516 // RawPath is only set if it's different from the normalized Path (std lib)
517 if req.URL.RawPath == req.URL.Path {
518 req.URL.RawPath = ""
519 }
520 }
521
522 // queryOps describes the operations to perform on query keys: add, set, rename and delete.
523 type queryOps struct {
524 // Renames a query key from Key to Val, without affecting the value.
525 Rename []queryOpsArguments `json:"rename,omitempty"`
526
527 // Sets query parameters; overwrites a query key with the given value.
528 Set []queryOpsArguments `json:"set,omitempty"`
529
530 // Adds query parameters; does not overwrite an existing query field,
531 // and only appends an additional value for that key if any already exist.
532 Add []queryOpsArguments `json:"add,omitempty"`
533
534 // Replaces query parameters.
535 Replace []*queryOpsReplacement `json:"replace,omitempty"`
536
537 // Deletes a given query key by name.
538 Delete []string `json:"delete,omitempty"`
539 }
540
541 // Provision compiles the query replace operation regex.
542 func (replacement *queryOpsReplacement) Provision(_ caddy.Context) error {
543 if replacement.SearchRegexp != "" {
544 re, err := regexp.Compile(replacement.SearchRegexp)
545 if err != nil {
546 return fmt.Errorf("replacement for query field '%s': %v", replacement.Key, err)
547 }
548 replacement.re = re
549 }
550 return nil
551 }
552
553 func (q *queryOps) do(r *http.Request, repl *caddy.Replacer) {
554 query := r.URL.Query()
555 for _, renameParam := range q.Rename {
556 key := repl.ReplaceAll(renameParam.Key, "")
557 val := repl.ReplaceAll(renameParam.Val, "")
558 if key == "" || val == "" {
559 continue
560 }
561 if key == val {
562 continue
563 }
564 originalValues, ok := query[key]
565 if !ok {
566 continue
567 }
568 query[val] = originalValues
569 delete(query, key)
570 }
571
572 for _, setParam := range q.Set {
573 key := repl.ReplaceAll(setParam.Key, "")
574 if key == "" {
575 continue
576 }
577 val := repl.ReplaceAll(setParam.Val, "")
578 query[key] = []string{val}
579 }
580
581 for _, addParam := range q.Add {
582 key := repl.ReplaceAll(addParam.Key, "")
583 if key == "" {
584 continue
585 }
586 val := repl.ReplaceAll(addParam.Val, "")
587 query[key] = append(query[key], val)
588 }
589
590 for _, replaceParam := range q.Replace {
591 key := repl.ReplaceAll(replaceParam.Key, "")
592 search := repl.ReplaceKnown(replaceParam.Search, "")
593 replace := repl.ReplaceKnown(replaceParam.Replace, "")
594
595 // replace all query keys...
596 if key == "*" {
597 for fieldName, vals := range query {
598 for i := range vals {
599 if replaceParam.re != nil {
600 query[fieldName][i] = replaceParam.re.ReplaceAllString(query[fieldName][i], replace)
601 } else {
602 query[fieldName][i] = strings.ReplaceAll(query[fieldName][i], search, replace)
603 }
604 }
605 }
606 continue
607 }
608
609 for fieldName, vals := range query {
610 for i := range vals {
611 if replaceParam.re != nil {
612 query[fieldName][i] = replaceParam.re.ReplaceAllString(query[fieldName][i], replace)
613 } else {
614 query[fieldName][i] = strings.ReplaceAll(query[fieldName][i], search, replace)
615 }
616 }
617 }
618 }
619
620 for _, deleteParam := range q.Delete {
621 param := repl.ReplaceAll(deleteParam, "")
622 if param == "" {
623 continue
624 }
625 delete(query, param)
626 }
627
628 r.URL.RawQuery = query.Encode()
629 }
630
631 type queryOpsArguments struct {
632 // A key in the query string. Note that query string keys may appear multiple times.
633 Key string `json:"key,omitempty"`
634
635 // The value for the given operation; for add and set, this is
636 // simply the value of the query, and for rename this is the
637 // query key to rename to.
638 Val string `json:"val,omitempty"`
639 }
640
641 type queryOpsReplacement struct {
642 // The key to replace in the query string.
643 Key string `json:"key,omitempty"`
644
645 // The substring to search for.
646 Search string `json:"search,omitempty"`
647
648 // The regular expression to search with.
649 SearchRegexp string `json:"search_regexp,omitempty"`
650
651 // The string with which to replace matches.
652 Replace string `json:"replace,omitempty"`
653
654 re *regexp.Regexp
655 }
656
657 // Interface guard
658 var _ caddyhttp.MiddlewareHandler = (*Rewrite)(nil)