/
certificate.go
284 lines (237 loc) · 6.39 KB
/
certificate.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
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
package internal
import (
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"github.com/yalp/jsonpath"
"gopkg.in/yaml.v3"
v1 "k8s.io/api/core/v1"
)
// YAMLCertRef : Contains information to access certificates in yaml files
type YAMLCertRef struct {
BasePathMatchExpr string
CertMatchSubExpr string
IDMatchSubExpr string
Format YAMLCertFormat
}
// YAMLCertFormat : Type of cert encoding in YAML files
type YAMLCertFormat int
// YAMLCertFormat : Impl
const (
YAMLCertFormatFile YAMLCertFormat = iota
YAMLCertFormatBase64 = iota
)
// DefaultYamlPaths : Pre-written paths for some k8s config files
var DefaultYamlPaths = []YAMLCertRef{
{
BasePathMatchExpr: "$.clusters",
CertMatchSubExpr: "$.cluster[\"certificate-authority-data\"]",
IDMatchSubExpr: "$.name",
Format: YAMLCertFormatBase64,
},
{
BasePathMatchExpr: "$.clusters",
CertMatchSubExpr: "$.cluster[\"certificate-authority\"]",
IDMatchSubExpr: "$.name",
Format: YAMLCertFormatFile,
},
{
BasePathMatchExpr: "$.users",
CertMatchSubExpr: "$.user[\"client-certificate-data\"]",
IDMatchSubExpr: "$.name",
Format: YAMLCertFormatBase64,
},
{
BasePathMatchExpr: "$.users",
CertMatchSubExpr: "$.user[\"client-certificate\"]",
IDMatchSubExpr: "$.name",
Format: YAMLCertFormatFile,
},
}
type certificateRef struct {
path string
format certificateFormat
certificates []*parsedCertificate
yamlPaths []YAMLCertRef
kubeSecret v1.Secret
kubeSecretKey string
}
type parsedCertificate struct {
cert *x509.Certificate
userID string
yqMatchExpr string
}
type certificateError struct {
err error
ref *certificateRef
}
type certificateFormat int
const (
certificateFormatPEM certificateFormat = iota
certificateFormatYAML = iota
certificateFormatKubeSecret = iota
)
func (cert *certificateRef) parse() error {
var err error
switch cert.format {
case certificateFormatPEM:
cert.certificates, err = readAndParsePEMFile(cert.path)
case certificateFormatYAML:
cert.certificates, err = readAndParseYAMLFile(cert.path, cert.yamlPaths)
case certificateFormatKubeSecret:
cert.certificates, err = readAndParseKubeSecret(&cert.kubeSecret, cert.kubeSecretKey)
}
return err
}
func readAndParsePEMFile(path string) ([]*parsedCertificate, error) {
contents, err := readFile(path)
if err != nil {
return nil, err
}
output := []*parsedCertificate{}
certs, err := parsePEM(contents)
if err != nil {
return nil, err
}
for _, cert := range certs {
output = append(output, &parsedCertificate{cert: cert})
}
return output, nil
}
func readAndParseYAMLFile(filePath string, yamlPaths []YAMLCertRef) ([]*parsedCertificate, error) {
output := []*parsedCertificate{}
for _, exprs := range yamlPaths {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
var raw interface{}
err = yaml.NewDecoder(file).Decode(&raw)
if err != nil {
return nil, err
}
entries, err := jsonpath.Read(raw, exprs.BasePathMatchExpr)
if err != nil {
return nil, err
}
for _, entry := range entries.([]interface{}) {
line, err := jsonpath.Read(entry, exprs.CertMatchSubExpr)
if err != nil {
continue
}
id, err := jsonpath.Read(entry, exprs.IDMatchSubExpr)
if err != nil {
continue
}
rawCerts, ok := line.(string)
if !ok {
return nil, err
}
var decodedCerts []byte
if exprs.Format == YAMLCertFormatBase64 {
decodedCerts = []byte{}
encodedCerts := strings.Split(rawCerts, "\n")
for _, encodedCert := range encodedCerts {
decodedCert, err := base64.StdEncoding.DecodeString(encodedCert)
if err != nil {
return nil, err
}
decodedCerts = append(decodedCerts, decodedCert...)
decodedCerts = append(decodedCerts, '\n')
}
} else if exprs.Format == YAMLCertFormatFile {
rawCertPaths := strings.TrimRight(string(rawCerts), "\n")
for _, certPath := range strings.Split(rawCertPaths, "\n") {
if !path.IsAbs(certPath) {
certPath = path.Join(filepath.Dir(filePath), rawCertPaths)
}
data, err := readFile(certPath)
if err != nil {
return nil, err
}
decodedCerts = append(decodedCerts, data...)
}
}
certs, err := parsePEM(decodedCerts)
if err != nil {
return nil, err
}
for index, cert := range certs {
displayName := id.(string)
if len(certs) > 1 {
displayName = fmt.Sprintf("%s(%d)", id, index)
}
output = append(output, &parsedCertificate{
cert: cert,
userID: displayName,
yqMatchExpr: fmt.Sprintf("%s[:]%s", exprs.BasePathMatchExpr, exprs.CertMatchSubExpr[1:]),
})
}
}
}
return output, nil
}
func readAndParseKubeSecret(secret *v1.Secret, key string) ([]*parsedCertificate, error) {
certs, err := parsePEM(secret.Data[key])
if err != nil {
return nil, err
}
output := []*parsedCertificate{}
for _, cert := range certs {
output = append(output, &parsedCertificate{
cert: cert,
})
}
return output, nil
}
func readFile(file string) ([]byte, error) {
contents, err := os.ReadFile(file)
if err == nil || !os.IsNotExist(err) {
return contents, err
}
fsys := os.DirFS(".")
if filepath.IsAbs(file) {
fsys = os.DirFS("/")
}
realPath, err := resolveSymlink(fsys, file)
if err != nil {
return nil, err
}
return os.ReadFile(realPath)
}
func resolveSymlink(fsys fs.FS, link string) (string, error) {
directory := fmt.Sprintf("%v", fsys)
symlink, err := os.Readlink(fmt.Sprintf("%s/%s", directory, link))
if err != nil {
return "", err
}
// only resolve the symlink filename, and not its full path, to stay compatible with k8s volume mounts
// see https://github.com/enix/x509-certificate-exporter/tree/main/deploy/charts/x509-certificate-exporter#watching-symbolic-links
return path.Join(path.Dir(link), path.Base(string(symlink))), nil
}
func parsePEM(data []byte) ([]*x509.Certificate, error) {
output := []*x509.Certificate{}
for {
block, rest := pem.Decode(data)
if block == nil {
break
}
data = rest
if block.Type != "CERTIFICATE" {
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, fmt.Errorf("tried to parse malformed x509 data, %s", err.Error())
}
output = append(output, cert)
}
return output, nil
}