|
1 | 1 | package k8s |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "crypto/x509" |
| 5 | + "encoding/base64" |
| 6 | + "encoding/pem" |
4 | 7 | "fmt" |
5 | 8 | "time" |
6 | 9 |
|
7 | 10 | "github.com/go-logr/logr" |
8 | 11 | "github.com/pmylund/go-cache" |
| 12 | + corev1 "k8s.io/api/core/v1" |
| 13 | + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
9 | 14 | "k8s.io/apimachinery/pkg/types" |
10 | 15 |
|
11 | 16 | "github.com/jetstack/preflight/api" |
@@ -39,9 +44,141 @@ func logCacheUpdateFailure(log logr.Logger, obj interface{}, operation string) { |
39 | 44 | log.Error(err, "Cache update failure", "operation", operation) |
40 | 45 | } |
41 | 46 |
|
| 47 | +// cacheFilterFunction is a function that can be used to filter out objects |
| 48 | +// that should not be added to the cache. If the function returns true, the |
| 49 | +// object is filtered out. |
| 50 | +type cacheFilterFunction func(logr.Logger, interface{}) bool |
| 51 | + |
| 52 | +// excludeTLSSecretsWithoutClientCert filters out all TLS secrets that do not |
| 53 | +// contain a client certificate in the `tls.crt` key. |
| 54 | +// Secrets are obtained by a DynamicClient, so they have type |
| 55 | +// *unstructured.Unstructured. |
| 56 | +func excludeTLSSecretsWithoutClientCert(log logr.Logger, obj interface{}) bool { |
| 57 | + // Fast path: type assertion and kind/type checks |
| 58 | + unstructuredObj, ok := obj.(*unstructured.Unstructured) |
| 59 | + if !ok { |
| 60 | + log.V(4).Info("Object is not a Unstructured", "type", fmt.Sprintf("%T", obj)) |
| 61 | + return false |
| 62 | + } |
| 63 | + if unstructuredObj.GetKind() != "Secret" || unstructuredObj.GetAPIVersion() != "v1" { |
| 64 | + return false |
| 65 | + } |
| 66 | + |
| 67 | + log = log.WithValues("namespace", unstructuredObj.GetNamespace(), "name", unstructuredObj.GetName()) |
| 68 | + |
| 69 | + secretType, found, err := unstructured.NestedString(unstructuredObj.Object, "type") |
| 70 | + if err != nil || !found || secretType != string(corev1.SecretTypeTLS) { |
| 71 | + log.V(4).Info("Object is not a TLS Secret", "type", secretType) |
| 72 | + return false |
| 73 | + } |
| 74 | + |
| 75 | + // Directly extract tls.crt from unstructured data (avoid conversion if possible) |
| 76 | + dataMap, found, err := unstructured.NestedMap(unstructuredObj.Object, "data") |
| 77 | + if err != nil || !found { |
| 78 | + log.V(4).Info("Secret data missing or not a map") |
| 79 | + return true |
| 80 | + } |
| 81 | + tlsCrtRaw, found := dataMap[corev1.TLSCertKey] |
| 82 | + if !found { |
| 83 | + log.V(4).Info("TLS Secret does not contain tls.crt key") |
| 84 | + return true |
| 85 | + } |
| 86 | + |
| 87 | + // Decode base64 if necessary (K8s secrets store data as base64-encoded strings) |
| 88 | + var tlsCrtBytes []byte |
| 89 | + switch v := tlsCrtRaw.(type) { |
| 90 | + case string: |
| 91 | + decoded, err := base64.StdEncoding.DecodeString(v) |
| 92 | + if err != nil { |
| 93 | + log.V(4).Info("Failed to decode tls.crt base64", "error", err.Error()) |
| 94 | + return true |
| 95 | + } |
| 96 | + tlsCrtBytes = decoded |
| 97 | + case []byte: |
| 98 | + tlsCrtBytes = v |
| 99 | + default: |
| 100 | + log.V(4).Info("tls.crt is not a string or byte slice", "type", fmt.Sprintf("%T", v)) |
| 101 | + return true |
| 102 | + } |
| 103 | + |
| 104 | + // Parse PEM certificate chain |
| 105 | + certs, err := parsePEMCertificateChain(tlsCrtBytes) |
| 106 | + if err != nil || len(certs) == 0 { |
| 107 | + log.V(4).Info("Failed to parse tls.crt as PEM encoded X.509 certificate chain", "error", err.Error()) |
| 108 | + return true |
| 109 | + } |
| 110 | + |
| 111 | + // Check if the leaf certificate is a client certificate |
| 112 | + if isClientCertificate(certs[0]) { |
| 113 | + log.V(4).Info("TLS Secret contains a client certificate") |
| 114 | + return false |
| 115 | + } |
| 116 | + |
| 117 | + log.V(4).Info("TLS Secret does not contain a client certificate") |
| 118 | + return true |
| 119 | +} |
| 120 | + |
| 121 | +// isClientCertificate checks if the given certificate is a client certificate |
| 122 | +// by checking if it has the ClientAuth EKU. |
| 123 | +func isClientCertificate(cert *x509.Certificate) bool { |
| 124 | + if cert == nil { |
| 125 | + return false |
| 126 | + } |
| 127 | + // Check if the certificate has the ClientAuth EKU |
| 128 | + for _, eku := range cert.ExtKeyUsage { |
| 129 | + if eku == x509.ExtKeyUsageClientAuth { |
| 130 | + return true |
| 131 | + } |
| 132 | + } |
| 133 | + return false |
| 134 | +} |
| 135 | + |
| 136 | +// parsePEMCertificateChain parses a PEM encoded certificate chain and returns |
| 137 | +// a slice of x509.Certificate pointers. It returns an error if the data cannot |
| 138 | +// be parsed as a certificate chain. |
| 139 | +// The supplied data can contain multiple PEM blocks, the function will parse |
| 140 | +// all of them and return a slice of certificates. |
| 141 | +func parsePEMCertificateChain(data []byte) ([]*x509.Certificate, error) { |
| 142 | + // Parse the PEM encoded certificate chain |
| 143 | + var certs []*x509.Certificate |
| 144 | + var block *pem.Block |
| 145 | + rest := data |
| 146 | + for { |
| 147 | + block, rest = pem.Decode(rest) |
| 148 | + if block == nil { |
| 149 | + break |
| 150 | + } |
| 151 | + if block.Type != "CERTIFICATE" || len(block.Bytes) == 0 { |
| 152 | + continue |
| 153 | + } |
| 154 | + cert, err := x509.ParseCertificate(block.Bytes) |
| 155 | + if err != nil { |
| 156 | + return nil, fmt.Errorf("failed to parse certificate: %w", err) |
| 157 | + } |
| 158 | + certs = append(certs, cert) |
| 159 | + } |
| 160 | + if len(certs) == 0 { |
| 161 | + return nil, fmt.Errorf("no certificates found") |
| 162 | + } |
| 163 | + return certs, nil |
| 164 | +} |
| 165 | + |
42 | 166 | // onAdd handles the informer creation events, adding the created runtime.Object |
43 | 167 | // to the data gatherer's cache. The cache key is the uid of the object |
44 | | -func onAdd(log logr.Logger, obj interface{}, dgCache *cache.Cache) { |
| 168 | +// The object is wrapped in a GatheredResource struct. |
| 169 | +// If the object is already present in the cache, it gets replaced. |
| 170 | +// The cache key is the uid of the object |
| 171 | +// The supplied filter functions can be used to filter out objects that |
| 172 | +// should not be added to the cache. |
| 173 | +// If multiple filter functions are supplied, the object is filtered out |
| 174 | +// if any of the filter functions returns true. |
| 175 | +func onAdd(log logr.Logger, obj interface{}, dgCache *cache.Cache, filters ...cacheFilterFunction) { |
| 176 | + for _, filter := range filters { |
| 177 | + if filter != nil && filter(log, obj) { |
| 178 | + return |
| 179 | + } |
| 180 | + } |
| 181 | + |
45 | 182 | item, ok := obj.(cacheResource) |
46 | 183 | if ok { |
47 | 184 | cacheObject := &api.GatheredResource{ |
|
0 commit comments