/
host_certificate.go
79 lines (66 loc) · 2.21 KB
/
host_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
package collect
import (
"bytes"
"crypto/tls"
"io/ioutil"
"path/filepath"
"strings"
troubleshootv1beta2 "github.com/replicatedhq/troubleshoot/pkg/apis/troubleshoot/v1beta2"
)
const KeyPairMissing = "key-pair-missing"
const KeyPairSwitched = "key-pair-switched"
const KeyPairEncrypted = "key-pair-encrypted"
const KeyPairMismatch = "key-pair-mismatch"
const KeyPairInvalid = "key-pair-invalid"
const KeyPairValid = "key-pair-valid"
type CollectHostCertificate struct {
hostCollector *troubleshootv1beta2.Certificate
BundlePath string
}
func (c *CollectHostCertificate) Title() string {
return hostCollectorTitleOrDefault(c.hostCollector.HostCollectorMeta, "Certificate Key Pair")
}
func (c *CollectHostCertificate) IsExcluded() (bool, error) {
return isExcluded(c.hostCollector.Exclude)
}
func (c *CollectHostCertificate) Collect(progressChan chan<- interface{}) (map[string][]byte, error) {
var result = KeyPairValid
_, err := tls.LoadX509KeyPair(c.hostCollector.CertificatePath, c.hostCollector.KeyPath)
if err != nil {
if strings.Contains(err.Error(), "no such file") {
result = KeyPairMissing
} else if strings.Contains(err.Error(), "PEM inputs may have been switched") {
result = KeyPairSwitched
} else if strings.Contains(err.Error(), "found a certificate rather than a key") {
result = KeyPairSwitched
} else if strings.Contains(err.Error(), "private key does not match public key") {
result = KeyPairMismatch
} else if strings.Contains(err.Error(), "failed to parse private key") {
if encrypted, _ := isEncryptedKey(c.hostCollector.KeyPath); encrypted {
result = KeyPairEncrypted
} else {
result = KeyPairInvalid
}
} else {
result = KeyPairInvalid
}
}
b := []byte(result)
collectorName := c.hostCollector.CollectorName
if collectorName == "" {
collectorName = "certificate"
}
name := filepath.Join("host-collectors/certificate", collectorName+".json")
output := NewResult()
output.SaveResult(c.BundlePath, name, bytes.NewBuffer(b))
return map[string][]byte{
name: b,
}, nil
}
func isEncryptedKey(filename string) (bool, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return false, err
}
return bytes.Contains(data, []byte("ENCRYPTED")), nil
}