github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/safehttp/plugins/hostcheck/hostcheck.go (about)

     1  // Copyright 2020 Google LLC
     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  //	https://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 hostcheck provides a plugin that checks whether the request is
    16  // intended to be sent to a given host.
    17  //
    18  // This is a protection mechanism against
    19  // DNS rebinding attacks (https://en.wikipedia.org/wiki/DNS_rebinding) and HTTP
    20  // request smuggling (https://portswigger.net/web-security/request-smuggling).
    21  package hostcheck
    22  
    23  import (
    24  	"github.com/google/go-safeweb/safehttp"
    25  )
    26  
    27  // Interceptor checks whether the Host header of the incoming request is in an
    28  // allowlist.
    29  type Interceptor struct {
    30  	hosts map[string]bool
    31  }
    32  
    33  var _ safehttp.Interceptor = Interceptor{}
    34  
    35  // New creates an Interceptor.
    36  func New(hosts ...string) Interceptor {
    37  	it := Interceptor{hosts: map[string]bool{}}
    38  	for _, h := range hosts {
    39  		it.hosts[h] = true
    40  	}
    41  	return it
    42  }
    43  
    44  // Before checks whether the request's Host header is in the list of allowed
    45  // hosts. If it's not, it responds with 404 Not Found.
    46  func (it Interceptor) Before(w safehttp.ResponseWriter, r *safehttp.IncomingRequest, _ safehttp.InterceptorConfig) safehttp.Result {
    47  	if !it.hosts[r.Host()] {
    48  		return w.WriteError(safehttp.StatusNotFound)
    49  	}
    50  	return safehttp.NotWritten()
    51  }
    52  
    53  // Commit is a no-op, required to satisfy the safehttp.Interceptor interface.
    54  func (Interceptor) Commit(w safehttp.ResponseHeadersWriter, r *safehttp.IncomingRequest, resp safehttp.Response, _ safehttp.InterceptorConfig) {
    55  }
    56  
    57  // Match returns false since there are no supported configurations.
    58  func (Interceptor) Match(safehttp.InterceptorConfig) bool {
    59  	return false
    60  }