-
Notifications
You must be signed in to change notification settings - Fork 28
Refine CVE check in check script for k8s version policy #779
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
piobig2871
wants to merge
22
commits into
main
Choose a base branch
from
526-refine-cve-check-in-scs-0210-v2-test-script
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 19 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
d96edd7
adding functions for getting more information & debug
piobig2871 0caf99d
Merge branch 'main' into 526-refine-cve-check-in-scs-0210-v2-test-script
piobig2871 ebfe951
solving conflicts
piobig2871 e635411
fixing git inset
piobig2871 a298678
Merge branch 'main' into 526-refine-cve-check-in-scs-0210-v2-test-script
piobig2871 cfc3dc6
Merge branch 'main' into 526-refine-cve-check-in-scs-0210-v2-test-script
piobig2871 54ee694
feat: Add Kubernetes pod image scanning and improve error handling
piobig2871 cc87097
Merge branch 'main' into 526-refine-cve-check-in-scs-0210-v2-test-script
piobig2871 38921f1
Merge branch 'main' into 526-refine-cve-check-in-scs-0210-v2-test-script
piobig2871 12987e5
removing comments
piobig2871 1d332ae
reseting standard to it's original form
piobig2871 11daeac
reverting ClusterInfo to its original shape, removing kubeconfig fiel…
piobig2871 e62b347
removing unused kubeconfig variable
piobig2871 5ab2bd0
fixing pylint and docstring formatting
piobig2871 5e2b764
Update Tests/kaas/k8s-version-policy/k8s_version_policy.py
piobig2871 3348960
fixing pylint and resolving conflict which appeard after review
piobig2871 4a59878
fixing the script with providing proper images list to check out
piobig2871 cea9840
femoving unused lines
piobig2871 c676f5f
Merge branch 'main' into 526-refine-cve-check-in-scs-0210-v2-test-script
piobig2871 f1674fe
Update Tests/kaas/k8s-version-policy/k8s_version_policy.py
piobig2871 f51a46c
Merge branch 'main' into 526-refine-cve-check-in-scs-0210-v2-test-script
piobig2871 48ba4d7
Merge branch 'main' into 526-refine-cve-check-in-scs-0210-v2-test-script
piobig2871 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,9 +24,9 @@ | |
| (c) Hannes Baum <[email protected]>, 6/2023 | ||
| (c) Martin Morgenstern <[email protected]>, 2/2024 | ||
| (c) Matthias Büchse <[email protected]>, 3/2024 | ||
| (c) Piotr Bigos <[email protected]> | ||
| SPDX-License-Identifier: CC-BY-SA-4.0 | ||
| """ | ||
|
|
||
| from collections import Counter | ||
| from dataclasses import dataclass | ||
| from datetime import datetime, timedelta | ||
|
|
@@ -35,11 +35,13 @@ | |
| import asyncio | ||
| import contextlib | ||
| import getopt | ||
| import json | ||
| import kubernetes_asyncio | ||
| import logging | ||
| import logging.config | ||
| import re | ||
| import requests | ||
| import subprocess | ||
| import sys | ||
| import yaml | ||
|
|
||
|
|
@@ -93,6 +95,10 @@ class HelpException(BaseException): | |
| """Exception raised if the help functionality is called""" | ||
|
|
||
|
|
||
| class CriticalException(BaseException): | ||
| """Exception raised if the critical CVE are found""" | ||
|
|
||
|
|
||
| class Config: | ||
| kubeconfig = None | ||
| context = None | ||
|
|
@@ -381,6 +387,82 @@ async def collect_cve_versions(session: aiohttp.ClientSession) -> set: | |
| return cfvs | ||
|
|
||
|
|
||
| async def run_trivy_scan(image: str) -> dict: | ||
| """Run Trivy scan on the specified image and return the results as a dictionary. | ||
|
|
||
| Args: | ||
| image (str): The Docker image to scan. | ||
|
|
||
| Returns: | ||
| dict: Parsed JSON results from Trivy. | ||
| """ | ||
| try: | ||
| # Run the Trivy scan command | ||
| result = await asyncio.create_subprocess_exec( | ||
| 'trivy', | ||
| 'image', | ||
| '--format', 'json', | ||
| '--no-progress', | ||
| image, | ||
| stdout=subprocess.PIPE, | ||
| stderr=subprocess.PIPE | ||
| ) | ||
|
|
||
| stdout, stderr = await result.communicate() | ||
|
|
||
| if result.returncode != 0: | ||
| logger.error("Trivy scan failed: %s", stderr.decode().strip()) | ||
| return {} | ||
|
|
||
| # Parse the JSON output from Trivy | ||
| return json.loads(stdout.decode()) | ||
|
|
||
| except Exception as e: | ||
| logger.error("Error running Trivy scan: %s", e) | ||
| return {} | ||
|
|
||
|
|
||
| async def get_k8s_pod_images(kubeconfig, context=None) -> list[str]: | ||
| """Get the list of container images used by all the pods in the Kubernetes cluster.""" | ||
|
|
||
| async with kubernetes_asyncio.client.ApiClient() as api: | ||
| v1 = kubernetes_asyncio.client.CoreV1Api(api) | ||
| pods = await v1.list_pod_for_all_namespaces(watch=False) | ||
|
|
||
| images = set() | ||
| for pod in pods.items: | ||
| for container in pod.spec.containers: | ||
| images.add(container.image) | ||
|
|
||
| if pod.spec.init_containers: | ||
| for container in pod.spec.init_containers: | ||
| images.add(container.image) | ||
|
|
||
| return list(images) | ||
|
|
||
|
|
||
| async def scan_k8s_images(images_to_scan) -> None: | ||
| """Scan the images used in the Kubernetes cluster for vulnerabilities.""" | ||
|
|
||
| for image in images_to_scan: | ||
| logger.info(f"Scanning image: {image}") | ||
| scan_results = await run_trivy_scan(image) | ||
|
|
||
| if scan_results: | ||
| for result in scan_results.get('Results', []): | ||
| for vulnerability in result.get('Vulnerabilities', []): | ||
| logger.warning( | ||
| f"""Vulnerability found in image {image}: | ||
| {vulnerability['VulnerabilityID']} " | ||
| (Severity: {vulnerability['Severity']})""" | ||
| ) | ||
|
|
||
|
|
||
| async def get_images_and_scan(kubeconfig, context=None) -> None: | ||
| images_to_scan = await get_k8s_pod_images(kubeconfig, context) | ||
| await scan_k8s_images(images_to_scan) | ||
|
|
||
|
|
||
| async def get_k8s_cluster_info(kubeconfig, context=None) -> ClusterInfo: | ||
| """Get the k8s version of the cluster under test.""" | ||
| cluster_config = await kubernetes_asyncio.config.load_kube_config(kubeconfig, context) | ||
|
|
@@ -479,6 +561,19 @@ async def main(argv): | |
| cve_affected_ranges = await collect_cve_versions(session) | ||
| releases_data = fetch_k8s_releases_data() | ||
|
|
||
| try: | ||
| logger.info( | ||
| f"""Initiating scan on the Kubernetes cluster specified by kubeconfig at {config.kubeconfig} | ||
| with context {config.context if config.context else ''}. | ||
| Fetching cluster information and verifying access.""") | ||
| await get_k8s_cluster_info(config.kubeconfig, config.context) | ||
| await get_images_and_scan(config.kubeconfig, config.context) | ||
|
|
||
| except CriticalException as e: | ||
| logger.critical(e) | ||
| logger.debug("Exception info", exc_info=True) | ||
| return 1 | ||
|
|
||
| try: | ||
| context_desc = f"context '{config.context}'" if config.context else "default context" | ||
| logger.info("Checking cluster specified by %s in %s.", context_desc, config.kubeconfig) | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.