|
| 1 | +// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved. |
| 2 | +// See the file LICENSE for licensing terms. |
| 3 | + |
| 4 | +package server |
| 5 | + |
| 6 | +import ( |
| 7 | + "net" |
| 8 | + "net/http" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/ava-labs/avalanchego/utils/set" |
| 12 | +) |
| 13 | + |
| 14 | +const wildcard = "*" |
| 15 | + |
| 16 | +var _ http.Handler = (*allowedHostsHandler)(nil) |
| 17 | + |
| 18 | +func filterInvalidHosts( |
| 19 | + handler http.Handler, |
| 20 | + allowed []string, |
| 21 | +) http.Handler { |
| 22 | + s := set.Set[string]{} |
| 23 | + |
| 24 | + for _, host := range allowed { |
| 25 | + if host == wildcard { |
| 26 | + // wildcards match all hostnames, so just return the base handler |
| 27 | + return handler |
| 28 | + } |
| 29 | + s.Add(strings.ToLower(host)) |
| 30 | + } |
| 31 | + |
| 32 | + return &allowedHostsHandler{ |
| 33 | + handler: handler, |
| 34 | + hosts: s, |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +// allowedHostsHandler is an implementation of http.Handler that validates the |
| 39 | +// http host header of incoming requests. This can prevent DNS rebinding attacks |
| 40 | +// which do not utilize CORS-headers. Http request host headers are validated |
| 41 | +// against a whitelist to determine whether the request should be dropped or |
| 42 | +// not. |
| 43 | +type allowedHostsHandler struct { |
| 44 | + handler http.Handler |
| 45 | + hosts set.Set[string] |
| 46 | +} |
| 47 | + |
| 48 | +func (a *allowedHostsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 49 | + // if the host header is missing we can serve this request because dns |
| 50 | + // rebinding attacks rely on this header |
| 51 | + if r.Host == "" { |
| 52 | + a.handler.ServeHTTP(w, r) |
| 53 | + return |
| 54 | + } |
| 55 | + |
| 56 | + host, _, err := net.SplitHostPort(r.Host) |
| 57 | + if err != nil { |
| 58 | + // either invalid (too many colons) or no port specified |
| 59 | + host = r.Host |
| 60 | + } |
| 61 | + |
| 62 | + if ipAddr := net.ParseIP(host); ipAddr != nil { |
| 63 | + // accept requests from ips |
| 64 | + a.handler.ServeHTTP(w, r) |
| 65 | + return |
| 66 | + } |
| 67 | + |
| 68 | + // a specific hostname - we need to check the whitelist to see if we should |
| 69 | + // accept this r |
| 70 | + if a.hosts.Contains(strings.ToLower(host)) { |
| 71 | + a.handler.ServeHTTP(w, r) |
| 72 | + return |
| 73 | + } |
| 74 | + |
| 75 | + http.Error(w, "invalid host specified", http.StatusForbidden) |
| 76 | +} |
0 commit comments