github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/utils/addr.go (about)

     1  /*
     2  Copyright 2021 Gravitational, Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package utils
    18  
    19  import (
    20  	"context"
    21  	"net"
    22  	"strings"
    23  )
    24  
    25  // IsLoopback returns 'true' if a given hostname resolves *only* to the
    26  // local host's loopback interface
    27  func IsLoopback(host string) bool {
    28  	return isLoopbackWithResolver(host, net.DefaultResolver)
    29  }
    30  
    31  type nameResolver interface {
    32  	LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error)
    33  }
    34  
    35  // isLoopbackWithResolver provides the inner implementation of IsLoopback(),
    36  // but allows the caller to inject a custom resolver for testing purposes.
    37  func isLoopbackWithResolver(host string, resolver nameResolver) bool {
    38  	if strings.Contains(host, ":") {
    39  		var err error
    40  		host, _, err = net.SplitHostPort(host)
    41  		if err != nil {
    42  			return false
    43  		}
    44  	}
    45  	addrs, err := resolver.LookupIPAddr(context.Background(), host)
    46  	if err != nil {
    47  		return false
    48  	}
    49  
    50  	if len(addrs) == 0 {
    51  		return false
    52  	}
    53  
    54  	for _, addr := range addrs {
    55  		if !addr.IP.IsLoopback() {
    56  			return false
    57  		}
    58  	}
    59  
    60  	return true
    61  }