-
Notifications
You must be signed in to change notification settings - Fork 202
/
mtls.go
178 lines (154 loc) · 4.73 KB
/
mtls.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
/*
Copyright 2021 The Dapr Authors
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 kubernetes
import (
"context"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"time"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/dapr/cli/pkg/print"
"github.com/dapr/dapr/pkg/apis/configuration/v1alpha1"
)
const (
systemConfigName = "daprsystem"
trustBundleSecretName = "dapr-trust-bundle" // nolint:gosec
warningDaysForCertExpiry = 30 // in days.
)
func IsMTLSEnabled() (bool, error) {
c, err := getSystemConfig()
if err != nil {
return false, err
}
return c.Spec.MTLSSpec.Enabled, nil
}
func getSystemConfig() (*v1alpha1.Configuration, error) {
client, err := DaprClient()
if err != nil {
return nil, err
}
configs, err := client.ConfigurationV1alpha1().Configurations(meta_v1.NamespaceAll).List(meta_v1.ListOptions{})
// This means that the Dapr Configurations CRD is not installed and
// therefore no configuration items exist.
if apierrors.IsNotFound(err) {
configs = &v1alpha1.ConfigurationList{
Items: []v1alpha1.Configuration{},
}
} else if err != nil {
return nil, err
}
for _, c := range configs.Items {
if c.GetName() == systemConfigName {
return &c, nil
}
}
return nil, errors.New("system configuration not found")
}
// ExportTrustChain takes the root cert, issuer cert and issuer key from a k8s cluster and saves them in a given directory.
func ExportTrustChain(outputDir string) error {
_, err := os.Stat(outputDir)
if os.IsNotExist(err) {
errDir := os.MkdirAll(outputDir, 0o755)
if errDir != nil {
return err
}
}
secret, err := getTrustChainSecret()
if err != nil {
return err
}
ca := secret.Data["ca.crt"]
issuerCert := secret.Data["issuer.crt"]
issuerKey := secret.Data["issuer.key"]
err = ioutil.WriteFile(filepath.Join(outputDir, "ca.crt"), ca, 0o600)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(outputDir, "issuer.crt"), issuerCert, 0o600)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(outputDir, "issuer.key"), issuerKey, 0o600)
if err != nil {
return err
}
return nil
}
// Check and warn if cert expiry is less than `warningDaysForCertExpiry` days.
func CheckForCertExpiry() {
expiry, err := Expiry()
// The intent is to warn for certificate expiry, only when it can be fetched.
// Do not show any kind of errors with normal command flow.
if err != nil {
return
}
daysRemaining := int(expiry.Sub(time.Now().UTC()).Hours() / 24)
if daysRemaining < warningDaysForCertExpiry {
warningMessage := ""
switch {
case daysRemaining == 0:
warningMessage = "Dapr root certificate of your Kubernetes cluster expires today."
case daysRemaining < 0:
warningMessage = "Dapr root certificate of your Kubernetes cluster has expired."
default:
warningMessage = fmt.Sprintf("Dapr root certificate of your Kubernetes cluster expires in %v days.", daysRemaining)
}
helpMessage := "Please see docs.dapr.io for certificate renewal instructions to avoid service interruptions."
print.WarningStatusEvent(os.Stdout,
fmt.Sprintf("%s Expiry date: %s. \n %s", warningMessage, expiry.Format(time.RFC1123), helpMessage))
}
}
func getTrustChainSecret() (*corev1.Secret, error) {
_, client, err := GetKubeConfigClient()
if err != nil {
return nil, err
}
c, err := getSystemConfig()
if err != nil {
return nil, err
}
res, err := client.CoreV1().Secrets(c.GetNamespace()).List(context.TODO(), meta_v1.ListOptions{})
if err != nil {
return nil, err
}
for _, i := range res.Items {
if i.GetName() == trustBundleSecretName {
return &i, nil
}
}
return nil, fmt.Errorf("could not find trust chain secret named %s in namespace %s", trustBundleSecretName, c.GetNamespace())
}
// Expiry returns the expiry time for the root cert.
func Expiry() (*time.Time, error) {
secret, err := getTrustChainSecret()
if err != nil {
return nil, err
}
caCrt, ok := secret.Data["ca.crt"]
if !ok {
return nil, errors.New("root certificate not loaded yet, please try again in few minutes")
}
block, _ := pem.Decode(caCrt)
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
return &cert.NotAfter, nil
}