Docker Hub Automated Scanning
Docker Hub Automated Scanning
Implement automated scanning for Docker Hub repositories:
#!/bin/bash
# dockerhub-scanner.sh
DOCKER_USERNAME="${DOCKER_USERNAME}"
DOCKER_PASSWORD="${DOCKER_PASSWORD}"
ORG_NAME="${DOCKER_ORG}"
# Get Docker Hub token
TOKEN=$(curl -s -X POST \
-H "Content-Type: application/json" \
-d '{"username": "'${DOCKER_USERNAME}'", "password": "'${DOCKER_PASSWORD}'"}' \
https://hub.docker.com/v2/users/login/ | jq -r .token)
# Function to get all repositories
get_repositories() {
curl -s -H "Authorization: Bearer ${TOKEN}" \
"https://hub.docker.com/v2/repositories/${ORG_NAME}/?page_size=100" | \
jq -r '.results[].name'
}
# Function to get all tags for a repository
get_tags() {
local repo=$1
curl -s -H "Authorization: Bearer ${TOKEN}" \
"https://hub.docker.com/v2/repositories/${ORG_NAME}/${repo}/tags/?page_size=100" | \
jq -r '.results[].name'
}
# Scan all images
scan_all_images() {
for repo in $(get_repositories); do
echo "Scanning repository: ${repo}"
for tag in $(get_tags $repo); do
IMAGE="${ORG_NAME}/${repo}:${tag}"
echo " Scanning ${IMAGE}"
# Pull and scan with Trivy
docker pull "${IMAGE}" > /dev/null 2>&1
# Run Trivy scan and save results
trivy image --format json \
--output "reports/${ORG_NAME}-${repo}-${tag}.json" \
"${IMAGE}"
# Check for critical vulnerabilities
CRITICAL=$(cat "reports/${ORG_NAME}-${repo}-${tag}.json" | \
jq '[.Results[]?.Vulnerabilities[]? | select(.Severity=="CRITICAL")] | length')
if [ "$CRITICAL" -gt "0" ]; then
echo " ⚠️ Found ${CRITICAL} CRITICAL vulnerabilities"
# Send alert
send_alert "${IMAGE}" "${CRITICAL}"
fi
# Clean up pulled image
docker rmi "${IMAGE}" > /dev/null 2>&1
done
done
}
# Alert function
send_alert() {
local image=$1
local critical_count=$2
# Send to Slack
curl -X POST "${SLACK_WEBHOOK}" \
-H 'Content-Type: application/json' \
-d "{
\"text\": \"🚨 Security Alert\",
\"blocks\": [{
\"type\": \"section\",
\"text\": {
\"type\": \"mrkdwn\",
\"text\": \"*Critical vulnerabilities found*\n\nImage: \`${image}\`\nCount: ${critical_count}\"
}
}]
}"
}
# Main execution
mkdir -p reports
scan_all_images