Debian Codegraph @

pkg/util/net.go

raw
1 /*
2 Copyright 2020 The Kubernetes Authors.
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 util //nolint:revive
18
19 import (
20 "crypto/tls"
21 "fmt"
22 "strings"
23 )
24
25 // containIPv6Addr checks if the given host identity contains an
26 // IPv6 address
27 func containIPv6Addr(host string) bool {
28 // the shortest IPv6 address is ::
29 return len(strings.Split(host, ":")) > 2
30 }
31
32 // containPortIPv6 checks if the host that contains an IPv6 address
33 // also contains a port number
34 func containPortIPv6(host string) bool {
35 // based on to RFC 3986, section 3.2.2, host identified by an
36 // IPv6 is distinguished by enclosing the IP literal within square
37 // brackets ("[" and "]")
38 return strings.ContainsRune(host, '[')
39 }
40
41 // RemovePortFromHost removes port number from the host address that
42 // may be of the form "<host>:<port>" where the <host> can be an either
43 // an IPv4/6 address or a domain name
44 func RemovePortFromHost(host string) string {
45 if !containIPv6Addr(host) {
46 return strings.Split(host, ":")[0]
47 }
48 if containPortIPv6(host) {
49 host = host[:strings.LastIndexByte(host, ':')]
50 }
51 return strings.Trim(host, "[]")
52 }
53
54 // GetAcceptedCiphers returns all the ciphers supported by the crypto/tls package
55 func GetAcceptedCiphers() map[string]uint16 {
56 acceptedCiphers := make(map[string]uint16, len(tls.CipherSuites()))
57 for _, v := range tls.CipherSuites() {
58 acceptedCiphers[v.Name] = v.ID
59 }
60 return acceptedCiphers
61 }
62
63 // tlsVersions maps TLS version name strings to their crypto/tls constant values.
64 var tlsVersions = map[string]uint16{
65 "VersionTLS10": tls.VersionTLS10,
66 "VersionTLS11": tls.VersionTLS11,
67 "VersionTLS12": tls.VersionTLS12,
68 "VersionTLS13": tls.VersionTLS13,
69 }
70
71 // GetTLSVersion returns the TLS version ID for the given version name.
72 // If the name is empty, it returns the default (TLS 1.2).
73 // Returns an error if the name is not recognized.
74 func GetTLSVersion(versionName string) (uint16, error) {
75 if versionName == "" {
76 return tls.VersionTLS12, nil
77 }
78 version, ok := tlsVersions[versionName]
79 if !ok {
80 return 0, fmt.Errorf("unsupported TLS version %q, supported values are: VersionTLS10, VersionTLS11, VersionTLS12, VersionTLS13", versionName)
81 }
82 return version, nil
83 }