From 69d2eed8089de579ef8113d6177641f05dbe3f89 Mon Sep 17 00:00:00 2001 From: Adrian Todorov Date: Thu, 11 Jul 2024 18:36:57 +0200 Subject: [PATCH] Improve the restrict-images Sentinel policy template to only apply to Docker/Podman tasks and to handle version numbers starting with v (#23530) --- .../restrict-images.js | 56 ++++++++++++++++--- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/ui/app/utils/sentinel_policy_templates/restrict-images.js b/ui/app/utils/sentinel_policy_templates/restrict-images.js index d8e8dfbc7..34f139c3a 100644 --- a/ui/app/utils/sentinel_policy_templates/restrict-images.js +++ b/ui/app/utils/sentinel_policy_templates/restrict-images.js @@ -3,29 +3,67 @@ * SPDX-License-Identifier: BUSL-1.1 */ -export default `# This policy restricts which Docker images are allowed and also prevents use of -# the "latest" tag since the image must specify a tag that starts with a number. +export default `# This policy restricts which Docker images from which Docker registries are +allowed and also prevents use of the "latest" tag to ensure predictability + +import "strings" + +allowed_registries = [ + "https://hub.docker.internal", +] # Allowed Docker images allowed_images = [ - "https://hub.docker.internal", "nginx", "mongo", ] +check_task_config = func(task) { + status = true + registry = "hub.docker.io" + image = "" + if task.driver in ["docker", "podman"] { + registry_and_image = strings.split(task.config.image, ("/")) + if length(registry_and_image) > 1 { + registry = registry_and_image[0] + image = registry_and_image[1] + } else { + image = task.config.image + } + # Checking the image + for allowed_images as allowed { + # Check for allowed images + if (!strings.has_prefix(image, allowed + ":")) { + print(task.config.image, "in task", task.name, "does not conform to policy, not in allowed images", allowed_images) + status = false + } else { + status = true + break + } + } + # Check for latest + if (strings.has_suffix(image, ":latest")) { + print(task.config.image, "in task", task.name, "does not conform to policy, using :latest instead of a specific version") + status = false + } + # Check registry + if registry not in allowed_registries { + print(task.config.image, "in task", task.name, "does not conform to policy, not from an allowed registry", allowed_registries) + status = false + } + return status + } +} + # Restrict allowed Docker images restrict_images = rule { all job.task_groups as tg { all tg.tasks as task { - any allowed_images as allowed { - # Note that we require ":" and a tag after it - # which must start with a number, preventing "latest" - task.config.image matches allowed + ":[0-9](.*)" - } + check_task_config(task) } } } - + # Main rule main = rule { restrict_images