Implementing Container Image Vulnerability Scanning in Git Pre-Commit Hooks
This advanced guide details how to integrate automated container image vulnerability scanning (using tools like Trivy or Clair) directly into a Git pre-commit hook, ensuring that no vulnerable images are committed to the repository.
Direct Diagnostic & Remediation Summary
- Install Scanner: Ensure your chosen scanner (e.g., Trivy) is installed locally:
docker pull trivy/trivy. - Create Hook Script: Develop a shell script that checks for Dockerfiles and runs the scan before allowing the commit:
#!/bin/sh if docker build --tag vulnerable_image . && trivy image --exit-code 1 vulnerable_image; then echo "Scan Passed."; else echo "Vulnerability Detected!"; exit 1; fi. - Activate Hook: Place the script in the
.git/hooks/pre-commitdirectory and make it executable:chmod +x .git/hooks/pre-commit.
Prerequisite Setup: Scanner Installation & Testing
Before touching Git hooks, ensure your chosen vulnerability scanner works reliably on a test image. We recommend Trivy for its simplicity and effectiveness.
- Install Docker Image: Ensure the base scan tool is available locally via Docker or direct binary installation.
docker pull aquasec/trivy - Create Test Dockerfile: In a dedicated test directory, create a minimal Dockerfile that uses an intentionally vulnerable base image for testing purposes (e.g., one known to have old libraries).
- Execute Baseline Scan: Build the image and run the scanner against it manually to confirm exit code handling.
docker build -t test_vuln:latest .aquasec/trivy image --exit-code 1 test_vuln:latest
Note: The --exit-code 1 flag is critical; it forces the scanner to exit with a non-zero status if vulnerabilities are found, which we will leverage in the hook.
Creating the Pre-Commit Hook Script
The hook must check for Dockerfiles, build an image contextually, and then execute the scan. This script needs to be robust enough to fail the commit if the exit code is non-zero.
- Navigate to Hooks Directory: Change into your local repository's hooks directory:
cd .git/hooks. - Create Script File: Create a new file named
pre-commit(no extension):touch pre-commit - Populate Script Content: Open
pre-commitin your preferred editor and paste the following logic. This example assumes you want to scan any image built from Dockerfiles found in staged changes.#!/bin/sh # Check if a Dockerfile exists among staged files (a simplification for demonstration) if ! git diff --cached --name-only | grep -q "Dockerfile"; then exit 0 # No Dockerfile staged, skip scanning. fi echo "[SECURITY SCAN] Initiating container vulnerability scan..." # In a real scenario, you would pass the specific image tag/context here. # For this example, we assume the build context is the root of the repo. IMAGE_TAG="temp_scan_image" # 1. Build the image (This step must succeed for scanning to occur) docker build -t ${IMAGE_TAG} . || { echo "Error: Docker build failed. Aborting commit."; exit 1; } # 2. Run the vulnerability scan, expecting an exit code of 0 on success if aquasec/trivy image --exit-code 1 ${IMAGE_TAG}; then echo "[SECURITY SCAN] Success: Image passed all configured security checks." else echo "[SECURITY SCAN] FAILURE: Vulnerabilities detected in the container image. Commit aborted for remediation." docker rmi ${IMAGE_TAG} # Clean up the temporary image exit 1 # Exit with non-zero code to fail the commit fi # Cleanup temp image regardless of success/failure if needed, though exit handles failure cleanup above docker rmi ${IMAGE_TAG} exit 0 - Set Permissions: Make the script executable:
chmod +x .git/hooks/pre-commit
Testing and Integration Workflow
Test the hook in isolation to ensure it correctly fails commits when vulnerabilities are present, and passes when clean.
- Stage Files: Stage a Dockerfile and any related source code changes:
git add Dockerfile . - Simulate Vulnerability (Failure Test): Modify the test image to include a known CVE, then attempt to commit:
Expected Result: The terminal must display the custom failure message and refuse the commit.git commit -m "Testing vulnerability hook failure" - Simulate Clean State (Success Test): Revert changes, ensure all base images are clean, and attempt to commit again:
Expected Result: The terminal must display the custom success message and allow the commit.git commit -m "Testing vulnerability hook success"
pre-commit Python library) for enforcement across the board.Common Pitfalls & Advanced Diagnostics
If the hook fails unexpectedly, check these common pitfalls:
- Hook Overwrite: If you run
rm pre-commitand then re-add it later, ensure you are still runningchmod +x .git/hooks/pre-commit. - Docker Context Issues: The hook assumes the build context is the repository root (
.). If your Dockerfile requires a specific subdirectory context (e.g.,./backend), you must change both thebuild -t ... .and potentially adjust file path checks in the script. - Permission Inheritance: Sometimes, running Git hooks within IDEs or CI runners can strip execution permissions. Always verify ownership and permissions using
ls -l .git/hooks/pre-commit. - Resource Exhaustion: Scanning large images can be CPU/Memory intensive. If the hook times out, consider adding a timeout mechanism (e.g., using
timeout 60s ...) to prevent indefinite hanging.
Verification, Results & Long-Term Stability Validation
To validate long-term stability, do not rely solely on the local hook. The ultimate source of truth must remain in CI/CD.
- CI Integration: Implement an identical scan step (using the same scanner and exit code logic) in your primary Continuous Integration pipeline (e.g., GitHub Actions, GitLab CI). This prevents developers from bypassing local hooks by committing directly to a runner environment that doesn't respect local setups.
- Dependency Management: If using Python/Pip environments for scanning tools, manage dependencies via
requirements.txtand use the officialpre-commitframework wrapper instead of raw shell scripts. This centralizes hook management.pip install pre-commit pre-commit install - Monitoring: Monitor commit failure rates initially. A sudden spike in failures indicates a change in the base image or dependency that requires updating the allowed vulnerability threshold.
The goal is for the local hook to act as an immediate guardrail, while the CI/CD pipeline acts as the non-negotiable gatekeeper.
Frequently Asked Questions
Q: Does this hook run if I use a different local machine? A: No. Git hooks are local to the repository clone. You must instruct all team members to install the hook or, preferably, adopt the pre-commit framework for centralized enforcement.
Q: How do I scan multiple Dockerfiles in one repo? A: The pre-commit script needs logic (using find . -name "Dockerfile"*) to identify all relevant build contexts and iterate through them, running the build/scan cycle for each context found.
Q: What if the vulnerability scanner itself is unavailable? A: The hook must be wrapped in a try/catch or shell conditional block that handles non-zero exit codes from the scanner tool gracefully, but it should fail the commit if the tool execution fails (e.g., Docker daemon down).
docker pull aquasec/trivy
chmod +x .git/hooks/pre-commit
git add Dockerfile .
docker build -t temp_scan_image .
git commit -m "Test"
pip install pre-commit
Frequently Asked Questions
Does this hook run if I use a different local machine?A: No. Git hooks are local to the repository clone. You must instruct all team members to install the hook or, preferably, adopt the <code>pre-commit</code> framework for centralized enforcement.
Refer to the verified triage steps detailed above.
How do I scan multiple Dockerfiles in one repo?A: The pre-commit script needs logic (using <code>find . -name "Dockerfile"</code>) to identify all relevant build contexts and iterate through them, running the build/scan cycle for each context found.
Refer to the verified triage steps detailed above.
What if the vulnerability scanner itself is unavailable?A: The hook must be wrapped in a try/catch or shell conditional block that handles non-zero exit codes from the scanner tool gracefully, but it should fail the commit if the tool execution fails (e.g., Docker daemon down).
Refer to the verified triage steps detailed above.
Need help implementing this solution?
Our cybersecurity and infrastructure engineers can audit, harden, or configure your systems directly.
Community Discussion & Confirmations (0)
Technical questions, hardware findings, and verified fix reports.
No reader questions posted yet. Have you tried this solution or experienced an edge case? Post below.