hastebin/scripts/scan-trivy-image.sh

80 lines
2.0 KiB
Bash
Executable File

#!/bin/bash
# Run Trivy image security scan
# Builds the Docker image locally and scans it for vulnerabilities
#
# Usage:
# ./scan-trivy-image.sh [image-name]
#
# Exit codes:
# 0 - No HIGH/CRITICAL vulnerabilities found
# 1 - Vulnerabilities found or error occurred
set -e
IMAGE_NAME="${1:-hastebin:local-scan}"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color
# Cleanup function to remove temporary image
cleanup() {
if docker image inspect "$IMAGE_NAME" &> /dev/null; then
echo -e "${YELLOW}Cleaning up temporary image: $IMAGE_NAME${NC}"
docker rmi "$IMAGE_NAME" --force &> /dev/null || true
fi
}
# Set trap to cleanup on exit (success or failure)
trap cleanup EXIT
# Check dependencies BEFORE building
if ! command -v docker &> /dev/null; then
echo -e "${RED}Docker not found. Please install Docker.${NC}"
exit 1
fi
if ! command -v trivy &> /dev/null; then
echo -e "${RED}Trivy not found. Please install it:${NC}"
echo " brew install trivy"
echo " or visit: https://aquasecurity.github.io/trivy/latest/getting-started/installation/"
exit 1
fi
# Build the Docker image (always clean build, no cache)
echo -e "${YELLOW}Building Docker image: $IMAGE_NAME${NC}"
docker build -t "$IMAGE_NAME" --no-cache .
echo ""
echo -e "${YELLOW}Running Trivy image security scan...${NC}"
# Show version
trivy --version
echo ""
echo -e "${YELLOW}Scanning Docker image for vulnerabilities...${NC}"
echo ""
# Scan image with exit code 1 (fail on HIGH/CRITICAL vulnerabilities)
# Store result to allow cleanup even on failure
SCAN_RESULT=0
trivy image \
--timeout 10m \
--scanners vuln \
--severity HIGH,CRITICAL \
--ignore-unfixed \
--exit-code 1 \
--format table \
"$IMAGE_NAME" || SCAN_RESULT=$?
echo ""
if [ $SCAN_RESULT -eq 0 ]; then
echo -e "${GREEN}Trivy image scan completed - no HIGH/CRITICAL vulnerabilities found!${NC}"
else
echo -e "${RED}Trivy image scan found HIGH/CRITICAL vulnerabilities!${NC}"
exit $SCAN_RESULT
fi