-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathutil.go
More file actions
435 lines (375 loc) · 16.1 KB
/
util.go
File metadata and controls
435 lines (375 loc) · 16.1 KB
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/*
*
* * OCI Native Ingress Controller
* *
* * Copyright (c) 2023 Oracle America, Inc. and its affiliates.
* * Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
*
*/
package ingress
import (
"context"
"crypto/tls"
"encoding/pem"
"errors"
"fmt"
"reflect"
"strings"
"time"
"github.com/oracle/oci-go-sdk/v65/certificates"
"github.com/oracle/oci-go-sdk/v65/certificatesmanagement"
ociloadbalancer "github.com/oracle/oci-go-sdk/v65/loadbalancer"
"github.com/oracle/oci-native-ingress-controller/pkg/certificate"
"github.com/oracle/oci-native-ingress-controller/pkg/client"
"github.com/oracle/oci-native-ingress-controller/pkg/state"
"github.com/oracle/oci-native-ingress-controller/pkg/util"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/klog/v2"
)
func compareHealthCheckers(healthCheckerDetails *ociloadbalancer.HealthCheckerDetails, healthChecker *ociloadbalancer.HealthChecker) bool {
if reflect.DeepEqual(healthCheckerDetails.Protocol, healthChecker.Protocol) {
if *healthChecker.Protocol == util.ProtocolTCP {
return compareTcpHealthCheckerAttributes(healthCheckerDetails, healthChecker)
} else if *healthChecker.Protocol == util.ProtocolHTTP {
return compareHttpHealthCheckerAttributes(healthCheckerDetails, healthChecker)
}
}
return false
}
func compareTcpHealthCheckerAttributes(healthCheckerDetails *ociloadbalancer.HealthCheckerDetails, healthChecker *ociloadbalancer.HealthChecker) bool {
return reflect.DeepEqual(healthCheckerDetails.Port, healthChecker.Port) &&
reflect.DeepEqual(healthCheckerDetails.IntervalInMillis, healthChecker.IntervalInMillis) &&
reflect.DeepEqual(healthCheckerDetails.TimeoutInMillis, healthChecker.TimeoutInMillis) &&
reflect.DeepEqual(healthCheckerDetails.Retries, healthChecker.Retries)
}
func compareHttpHealthCheckerAttributes(healthCheckerDetails *ociloadbalancer.HealthCheckerDetails, healthChecker *ociloadbalancer.HealthChecker) bool {
return compareTcpHealthCheckerAttributes(healthCheckerDetails, healthChecker) &&
reflect.DeepEqual(healthCheckerDetails.UrlPath, healthChecker.UrlPath) &&
reflect.DeepEqual(healthCheckerDetails.ReturnCode, healthChecker.ReturnCode) &&
reflect.DeepEqual(healthCheckerDetails.ResponseBodyRegex, healthChecker.ResponseBodyRegex) &&
reflect.DeepEqual(healthCheckerDetails.IsForcePlainText, healthChecker.IsForcePlainText)
}
// SSL UTILS
func CreateImportedTypeCertificate(caCertificatesChain *string, serverCertificate *string, privateKey *string, certificateName string, compartmentId string,
certificatesClient *certificate.CertificatesClient) (*certificatesmanagement.Certificate, error) {
configDetails := certificatesmanagement.CreateCertificateByImportingConfigDetails{
CertChainPem: caCertificatesChain,
CertificatePem: serverCertificate,
PrivateKeyPem: privateKey,
}
certificateDetails := certificatesmanagement.CreateCertificateDetails{
Name: &certificateName,
CertificateConfig: configDetails,
CompartmentId: &compartmentId,
}
createCertificateRequest := certificatesmanagement.CreateCertificateRequest{
CreateCertificateDetails: certificateDetails,
OpcRetryToken: &certificateName,
}
createCertificate, err := certificatesClient.CreateCertificate(context.TODO(), createCertificateRequest)
if err != nil {
return nil, err
}
certificatesClient.SetCertCache(createCertificate)
klog.Infof("Created a certificate with ocid %s", *createCertificate.Id)
return createCertificate, nil
}
func GetCertificate(certificateId *string, certificatesClient *certificate.CertificatesClient) (*certificatesmanagement.Certificate, error) {
certCacheObj := certificatesClient.GetFromCertCache(*certificateId)
if certCacheObj != nil {
now := time.Now()
if now.Sub(certCacheObj.Age).Minutes() < util.CertificateCacheMaxAgeInMinutes {
return certCacheObj.Cert, nil
}
klog.Infof("Refreshing certificate %s", *certificateId)
}
getCertificateRequest := certificatesmanagement.GetCertificateRequest{
CertificateId: certificateId,
}
cert, err := certificatesClient.GetCertificate(context.TODO(), getCertificateRequest)
if err == nil {
certificatesClient.SetCertCache(cert)
}
return cert, err
}
func FindCertificateWithName(certificateName string, compartmentId string,
certificatesClient *certificate.CertificatesClient) (*string, error) {
listCertificatesRequest := certificatesmanagement.ListCertificatesRequest{
Name: &certificateName,
CompartmentId: &compartmentId,
LifecycleState: certificatesmanagement.ListCertificatesLifecycleStateActive,
}
klog.Infof("Searching for certificates with name %s in compartment %s.", certificateName, compartmentId)
listCertificates, _, err := certificatesClient.ListCertificates(context.TODO(), listCertificatesRequest)
if err != nil {
return nil, err
}
if listCertificates.Items != nil {
numberOfCertificates := len(listCertificates.Items)
klog.Infof("Found %d certificates with name %s in compartment %s.", numberOfCertificates, certificateName, compartmentId)
if numberOfCertificates > 0 {
return listCertificates.Items[0].Id, nil
}
}
klog.Infof("Found no certificates with name %s in compartment %s.", certificateName, compartmentId)
return nil, nil
}
func FindCaBundleWithName(certificateName string, compartmentId string,
certificatesClient *certificate.CertificatesClient) (*string, error) {
listCaBundlesRequest := certificatesmanagement.ListCaBundlesRequest{
Name: &certificateName,
CompartmentId: &compartmentId,
LifecycleState: certificatesmanagement.ListCaBundlesLifecycleStateActive,
}
klog.Infof("Searching for ca bundles with name %s in compartment %s.", certificateName, compartmentId)
listCaBundles, err := certificatesClient.ListCaBundles(context.TODO(), listCaBundlesRequest)
if err != nil {
return nil, err
}
if listCaBundles.Items != nil {
numberOfCertificates := len(listCaBundles.Items)
klog.Infof("Found %d bundles with name %s in compartment %s.", numberOfCertificates, certificateName, compartmentId)
if numberOfCertificates > 0 {
return listCaBundles.Items[0].Id, nil
}
}
klog.Infof("Found no bundles with name %s in compartment %s.", certificateName, compartmentId)
return nil, nil
}
func GetCaBundle(caBundleId string, certificatesClient *certificate.CertificatesClient) (*certificatesmanagement.CaBundle, error) {
caBundleCacheObj := certificatesClient.GetFromCaBundleCache(caBundleId)
if caBundleCacheObj != nil {
return caBundleCacheObj.CaBundle, nil
}
klog.Infof("Getting ca bundle for id %s.", caBundleId)
getCaBundleRequest := certificatesmanagement.GetCaBundleRequest{
CaBundleId: &caBundleId,
}
caBundle, err := certificatesClient.GetCaBundle(context.TODO(), getCaBundleRequest)
if err == nil {
certificatesClient.SetCaBundleCache(caBundle)
}
return caBundle, err
}
func CreateCaBundle(certificateName string, compartmentId string, certificatesClient *certificate.CertificatesClient,
certificateContents *string) (*certificatesmanagement.CaBundle, error) {
caBundleDetails := certificatesmanagement.CreateCaBundleDetails{
Name: &certificateName,
CompartmentId: &compartmentId,
CaBundlePem: certificateContents,
}
createCaBundleRequest := certificatesmanagement.CreateCaBundleRequest{
CreateCaBundleDetails: caBundleDetails,
OpcRetryToken: &certificateName,
}
klog.Infof(" createCaBundleRequest ********** certificateName %s createCaBundleRequest : %s ", certificateName, util.PrettyPrint(createCaBundleRequest))
createCaBundle, err := certificatesClient.CreateCaBundle(context.TODO(), createCaBundleRequest)
if err != nil {
return nil, err
}
certificatesClient.SetCaBundleCache(createCaBundle)
return createCaBundle, nil
}
type TLSSecretData struct {
// This would hold server certificate and any chain of trust.
CaCertificateChain *string
ServerCertificate *string
PrivateKey *string
}
func getTlsSecretContent(namespace string, secretName string, client kubernetes.Interface) (*TLSSecretData, error) {
secret, err := client.CoreV1().Secrets(namespace).Get(context.TODO(), secretName, metav1.GetOptions{})
if err != nil {
return nil, err
}
var serverCertificate string
privateKey := string(secret.Data["tls.key"])
caCertificateChain := string(secret.Data["ca.crt"])
if caCertificateChain != "" {
serverCertificate = string(secret.Data["tls.crt"])
} else {
// If ca.crt is not available, we will assume tls.crt has the entire chain, leaf first
serverCertificate, caCertificateChain, err = splitLeafAndCaCertChain(secret.Data["tls.crt"], secret.Data["tls.key"])
if err != nil {
return nil, err
}
}
return &TLSSecretData{CaCertificateChain: &caCertificateChain, ServerCertificate: &serverCertificate, PrivateKey: &privateKey}, nil
}
func splitLeafAndCaCertChain(certChainPEMBlock []byte, keyPEMBlock []byte) (string, string, error) {
certs, err := tls.X509KeyPair(certChainPEMBlock, keyPEMBlock)
if err != nil {
return "", "", fmt.Errorf("unable to parse cert chain, %w", err)
}
if len(certs.Certificate) <= 1 {
return "", "", errors.New("tls.crt chain has less than two certificates")
}
leafCertString := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certs.Certificate[0]}))
caCertChainString := ""
for _, cert := range certs.Certificate[1:] {
caCertString := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert}))
caCertChainString += caCertString
}
return leafCertString, caCertChainString, nil
}
func getCertificateNameFromSecret(secretName string) string {
if secretName == "" {
return ""
}
return fmt.Sprintf("ic-%s", secretName)
}
func GetSSLConfigForBackendSet(namespace string, artifactType string, artifact string, lb *ociloadbalancer.LoadBalancer, bsName string, compartmentId string, client *client.ClientProvider) (*ociloadbalancer.SslConfigurationDetails, error) {
var backendSetSslConfig *ociloadbalancer.SslConfigurationDetails
createCaBundle := false
var caBundleId *string
bs, ok := lb.BackendSets[bsName]
if artifactType == state.ArtifactTypeSecret && artifact != "" {
klog.Infof("Secret name for backend set %s is %s", bsName, artifact)
if ok && bs.SslConfiguration != nil && isTrustAuthorityCaBundle(bs.SslConfiguration.TrustedCertificateAuthorityIds[0]) {
newCertificateName := getCertificateNameFromSecret(artifact)
caBundle, err := GetCaBundle(bs.SslConfiguration.TrustedCertificateAuthorityIds[0], client.GetCertClient())
if err != nil {
return nil, err
}
klog.Infof("Ca bundle name is %s, new certificate name is %s", *caBundle.Name, newCertificateName)
if *caBundle.Name != newCertificateName {
klog.Infof("Ca bundle for backend set %s needs update. Old name %s, New name %s", *bs.Name, *caBundle.Name, newCertificateName)
createCaBundle = true
}
} else {
createCaBundle = true
}
if createCaBundle {
cId, err := CreateOrGetCaBundleForBackendSet(namespace, artifact, compartmentId, client)
if err != nil {
return nil, err
}
caBundleId = cId
}
if caBundleId != nil {
caBundleIds := []string{*caBundleId}
backendSetSslConfig = &ociloadbalancer.SslConfigurationDetails{TrustedCertificateAuthorityIds: caBundleIds}
}
}
if artifactType == state.ArtifactTypeCertificate && artifact != "" {
cert, err := GetCertificate(&artifact, client.GetCertClient())
if err != nil {
return nil, err
}
klog.Infof("Found a certificate %s with type %s and id %s", *cert.Name, cert.ConfigType, *cert.Id)
if cert.ConfigType == certificatesmanagement.CertificateConfigTypeIssuedByInternalCa ||
cert.ConfigType == certificatesmanagement.CertificateConfigTypeManagedExternallyIssuedByInternalCa {
caAuthorityIds := []string{*cert.IssuerCertificateAuthorityId}
backendSetSslConfig = &ociloadbalancer.SslConfigurationDetails{TrustedCertificateAuthorityIds: caAuthorityIds}
}
if cert.ConfigType == certificatesmanagement.CertificateConfigTypeImported {
caBundleId, _ := FindCaBundleWithName(*cert.Name, compartmentId, client.GetCertClient())
if caBundleId == nil {
versionNumber := cert.CurrentVersion.VersionNumber
getCertificateBundleRequest := certificates.GetCertificateBundleRequest{
CertificateId: &artifact,
VersionNumber: versionNumber,
}
certificateBundle, err := client.GetCertClient().GetCertificateBundle(context.TODO(), getCertificateBundleRequest)
if err != nil {
return nil, err
}
createCaBundle, err := CreateCaBundle(*cert.Name, compartmentId, client.GetCertClient(), certificateBundle.GetCertChainPem())
if err != nil {
return nil, err
}
caBundleId = createCaBundle.Id
}
if caBundleId != nil {
caBundleIds := []string{*caBundleId}
backendSetSslConfig = &ociloadbalancer.SslConfigurationDetails{TrustedCertificateAuthorityIds: caBundleIds}
}
}
}
return backendSetSslConfig, nil
}
func GetSSLConfigForListener(namespace string, listener *ociloadbalancer.Listener, artifactType string, artifact string, compartmentId string, client *client.ClientProvider) (*ociloadbalancer.SslConfigurationDetails, error) {
var currentCertificateId string
var newCertificateId string
createCertificate := false
var listenerSslConfig *ociloadbalancer.SslConfigurationDetails
if listener != nil && listener.SslConfiguration != nil {
currentCertificateId = listener.SslConfiguration.CertificateIds[0]
if state.ArtifactTypeCertificate == artifactType && currentCertificateId != artifact {
newCertificateId = artifact
} else if state.ArtifactTypeSecret == artifactType {
cert, err := GetCertificate(¤tCertificateId, client.GetCertClient())
if err != nil {
return nil, err
}
certificateName := getCertificateNameFromSecret(artifact)
if certificateName != "" && *cert.Name != certificateName {
createCertificate = true
}
}
} else {
if state.ArtifactTypeSecret == artifactType {
createCertificate = true
}
if state.ArtifactTypeCertificate == artifactType {
newCertificateId = artifact
}
}
if createCertificate {
cId, err := CreateOrGetCertificateForListener(namespace, artifact, compartmentId, client)
if err != nil {
return nil, err
}
newCertificateId = *cId
}
// //TODO add VerifyPeerCertificate here
// https://github.com/oracle/oci-go-sdk/blob/master/example/example_loadbalancer_test.go
// listenerSslConfig.VerifyPeerCertificate(common.Bool(true))
if newCertificateId != "" {
certificateIds := []string{newCertificateId}
listenerSslConfig = &ociloadbalancer.SslConfigurationDetails{CertificateIds: certificateIds}
}
return listenerSslConfig, nil
}
func CreateOrGetCertificateForListener(namespace string, secretName string, compartmentId string, client *client.ClientProvider) (*string, error) {
certificateName := getCertificateNameFromSecret(secretName)
certificateId, err := FindCertificateWithName(certificateName, compartmentId, client.GetCertClient())
if err != nil {
return nil, err
}
if certificateId == nil {
tlsSecretData, err := getTlsSecretContent(namespace, secretName, client.GetK8Client())
if err != nil {
return nil, err
}
createCertificate, err := CreateImportedTypeCertificate(tlsSecretData.CaCertificateChain, tlsSecretData.ServerCertificate,
tlsSecretData.PrivateKey, certificateName, compartmentId, client.GetCertClient())
if err != nil {
return nil, err
}
certificateId = createCertificate.Id
}
return certificateId, nil
}
func CreateOrGetCaBundleForBackendSet(namespace string, secretName string, compartmentId string, client *client.ClientProvider) (*string, error) {
certificateName := getCertificateNameFromSecret(secretName)
caBundleId, err := FindCaBundleWithName(certificateName, compartmentId, client.GetCertClient())
if err != nil {
return nil, err
}
if caBundleId == nil {
tlsSecretData, err := getTlsSecretContent(namespace, secretName, client.GetK8Client())
if err != nil {
return nil, err
}
createCaBundle, err := CreateCaBundle(certificateName, compartmentId, client.GetCertClient(), tlsSecretData.CaCertificateChain)
if err != nil {
return nil, err
}
caBundleId = createCaBundle.Id
}
return caBundleId, nil
}
func isTrustAuthorityCaBundle(id string) bool {
return strings.Contains(id, "cabundle")
}