-
Notifications
You must be signed in to change notification settings - Fork 189
/
cert.go
190 lines (159 loc) · 5.12 KB
/
cert.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
/*
Copyright © 2021 MicroShift Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
tcpnet "net"
"os"
"strings"
"k8s.io/client-go/util/keyutil"
"k8s.io/klog/v2"
)
const keySize = 2048
func EnsureKeyPair(pubKeyPath, privKeyPath string) error {
if _, err := getKeyPair(pubKeyPath, privKeyPath); err == nil {
return nil
}
return GenKeys(pubKeyPath, privKeyPath)
}
// GenKeys generates and save rsa keys
func GenKeys(pubPath, keyPath string) error {
rsaKey, err := rsa.GenerateKey(rand.Reader, keySize)
if err != nil {
return fmt.Errorf("failed to generate RSA private key: %w", err)
}
keyPEM, err := keyutil.MarshalPrivateKeyToPEM(rsaKey)
if err != nil {
return fmt.Errorf("failed to encode private key to PEM: %w", err)
}
pubPEM, err := PublicKeyToPem(&rsaKey.PublicKey)
if err != nil {
return err
}
if err := keyutil.WriteKey(keyPath, keyPEM); err != nil {
return fmt.Errorf("failed to write the private key to %s: %w", keyPath, err)
}
if err := os.WriteFile(pubPath, pubPEM, 0400); err != nil {
return fmt.Errorf("failed to write public key to %s: %w", pubPath, err)
}
return nil
}
// PublicKeyToPem converts an rsa.PublicKey object to pem string
func PublicKeyToPem(key *rsa.PublicKey) ([]byte, error) {
keyInBytes, err := x509.MarshalPKIXPublicKey(key)
if err != nil {
return nil, fmt.Errorf("failed to MarshalPKIXPublicKey: %w", err)
}
keyinPem := pem.EncodeToMemory(
&pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: keyInBytes,
},
)
return keyinPem, nil
}
func getKeyPair(pubKeyPath, privKeyPath string) (*rsa.PrivateKey, error) {
pubKeys, err := keyutil.PublicKeysFromFile(pubKeyPath)
if err != nil {
return nil, fmt.Errorf("failed to read public key: %w", err)
}
if len(pubKeys) > 1 {
return nil, fmt.Errorf("too many pub keys in file %s", pubKeyPath)
}
privKey, err := keyutil.PrivateKeyFromFile(privKeyPath)
if err != nil {
return nil, fmt.Errorf("failed to read private key: %w", err)
}
rsaPrivKey, ok := privKey.(*rsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("only RSA private keys are currently supported")
}
if !rsaPrivKey.PublicKey.Equal(pubKeys[0].(*rsa.PublicKey)) {
return nil, fmt.Errorf("public and private keys don't match")
}
return rsaPrivKey, nil
}
func IsCertAllowed(advertiseAddress string, clusterNetwork []string, serviceNetwork []string, certPath string, extraNames []string) (bool, error) {
certsSNIs, err := GetSNIsFromCert(certPath, extraNames)
if err != nil {
return false, err
}
// iterate over the Cert SNIs and make sure that all are allowed
for _, dns := range certsSNIs {
// check if SNI is allowed (non local or wildcard)
if !VerifyAllowedSNI(advertiseAddress, clusterNetwork, serviceNetwork, dns) {
klog.Infof("Certificate SNI is not allowed for %s", dns)
return false, nil
}
}
return true, nil
}
// GetSNIsFromCert - get list of unique SNIs from certificate
func GetSNIsFromCert(certPath string, extraNames []string) ([]string, error) {
pemByte, err := os.ReadFile(certPath)
if err != nil {
return nil, err
}
block, _ := pem.Decode(pemByte)
if block == nil {
return nil, fmt.Errorf("failed to decode the certificate %s", certPath)
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
// create one list to hold all the SNIs
certsSNIs := append(cert.DNSNames, cert.Subject.CommonName)
// add Certificate SAN ipaddress
for _, ipaddress := range cert.IPAddresses {
certsSNIs = append(certsSNIs, ipaddress.String())
}
// add Configuration names
if len(extraNames) > 0 {
certsSNIs = append(certsSNIs, extraNames...)
}
return certsSNIs, nil
}
// IsWildcardDNS - check if DNS is a wildcard
func IsWildcardDNS(val string) bool {
return strings.HasPrefix(val, "*.")
}
// verifyAllowedSNI checks if sni is allowed
// return bool: true, false
func VerifyAllowedSNI(advertiseAddress string, clusterNetwork []string, serviceNetwork []string, sni string) bool {
forbiddenSuffixValues := []string{"svc.cluster.local", "openshift", "openshift.default", "openshift.default.svc", "kubernetes", "kubernetes.default", "kubernetes.default.svc"}
ipAddress := tcpnet.ParseIP(sni)
//check if IPAddress or DNS record
if ipAddress == nil {
if sni == "localhost" {
return false
}
for _, val := range forbiddenSuffixValues {
if strings.HasSuffix(sni, val) {
return false
}
}
} else {
if ContainIPANetwork(ipAddress, clusterNetwork) ||
ContainIPANetwork(ipAddress, serviceNetwork) ||
ContainIPANetwork(ipAddress, []string{"127.0.0.1/8", "169.254.169.2/29"}) ||
advertiseAddress == ipAddress.String() {
return false
}
}
return true
}