updates image-mutation conditions

This commit is contained in:
2023-03-24 21:17:17 -05:00
parent bf944cb048
commit 96e606af5b
6 changed files with 331 additions and 14 deletions

View File

@ -4,6 +4,7 @@ import (
"fmt"
"log"
"regexp"
"strings"
admission "k8s.io/api/admission/v1"
core "k8s.io/api/core/v1"
@ -51,7 +52,7 @@ func podMutationCreate() AdmitFunc {
return true
}(cfg.AllowAdminNoMutate, pod) {
for i, p := range pod.Spec.Containers {
img, mutationOccurred, err := customDockerRegistry(p.Image, cfg)
img, mutationOccurred, err := mutateImage(p.Image, cfg)
if err != nil {
return &Result{Msg: err.Error()}, nil
}
@ -59,13 +60,13 @@ func podMutationCreate() AdmitFunc {
mutated = true
path := fmt.Sprintf("/spec/containers/%d/image", i)
operations = append(operations, ReplacePatchOperation(path, img))
log.Printf("[TRACE] Image has been mutated: %s -> %s", p.Image, img)
log.Printf("[INFO] Image has been mutated: %s -> %s", p.Image, img)
} else {
log.Printf("[TRACE] No mutation required for image: %s", p.Image)
log.Printf("[INFO] No mutation required for image: %s", p.Image)
}
}
} else {
log.Printf("[TRACE] Mutations administratively disabled.")
log.Printf("[INFO] Mutations administratively disabled.")
}
if mutated {
@ -88,19 +89,32 @@ func podMutationCreate() AdmitFunc {
}
}
func customDockerRegistry(imgPath string, cfg *config.Config) (string, bool, error) {
func mutateImage(imgPath string, cfg *config.Config) (string, bool, error) {
if len(cfg.DockerhubRegistry) == 0 {
return imgPath, false, nil
}
// regex match official project
reg, err := regexp.Compile(`^([a-z]|\.|_|-)+\:([a-zA-Z0-9]|_|\.|-)+$`)
if err != nil {
return "", false, fmt.Errorf("Unable to parse regex: %v", err)
// Is image on allow-list
for _, i := range cfg.MutateIgnoredImages {
if strings.Contains(strings.ToLower(imgPath), strings.ToLower(i)) {
log.Printf("[DEBUG] Image is on allow-list: %s", imgPath)
return "", false, nil
}
}
if reg.MatchString(imgPath) {
log.Printf("Official docker image detected: %s", imgPath)
switch {
// Is image already using defined registry?
case strings.Contains(strings.ToLower(imgPath), strings.Split(strings.ToLower(cfg.DockerhubRegistry), "/")[0]):
log.Printf("[DEBUG] Image is already using required registry: %s", imgPath)
return "", false, nil
// Is this an official dockerhub image?
case regexp.MustCompile(fmt.Sprintf(`^%s:%s$`, `([a-z0-9]|_|-)+`, `([a-zA-Z0-9]|_|\.|-)+`)).MatchString(imgPath):
log.Printf("[DEBUG] Official dockerhub image detected: %s", imgPath)
return fmt.Sprintf("%s/library/%s", cfg.DockerhubRegistry, imgPath), true, nil
// Is this a normal DockerHub Image?
case regexp.MustCompile(fmt.Sprintf(`^%s\/%s:%s$`, `([a-z0-9]|_|-)+`, `([a-z0-9]|_|-)+`, `([a-zA-Z0-9]|_|\.|-)+`)).MatchString(imgPath):
log.Printf("[DEBUG] Standard dockerhub image detected: %s", imgPath)
return fmt.Sprintf("%s/%s", cfg.DockerhubRegistry, imgPath), true, nil
}
return "", false, nil
}