#!/bin/bash # Script to audit Dockerfiles for best practices, especially minimal root usage set -e echo "Starting Dockerfile audit for best practices..." if [ -z "$1" ]; then echo "Usage: $0 " echo "Example: $0 Dockerfile" exit 1 fi DOCKERFILE_PATH="$1" if [ ! -f "$DOCKERFILE_PATH" ]; then echo "Error: Dockerfile not found at $DOCKERFILE_PATH" exit 1 fi echo "Auditing Dockerfile: $DOCKERFILE_PATH" echo # Hadolint check echo "1. Running Hadolint (Dockerfile linter)..." if command -v hadolint &> /dev/null; then hadolint --config .hadolint.yaml "$DOCKERFILE_PATH" && echo " ✓ Hadolint passed" || echo " ⚠ Hadolint found issues (as configured to ignore some warnings)" else echo " ⚠ Hadolint not found" fi echo # Dockerlint check echo "2. Running Dockerlint..." if command -v dockerlint &> /dev/null; then dockerlint -f "$DOCKERFILE_PATH" && echo " ✓ Dockerlint passed" || echo " ⚠ Dockerlint found issues" else echo " ⚠ Dockerlint not found" fi echo # Custom check for minimal root usage echo "3. Checking for minimal root usage in Dockerfile..." echo " Looking for operations that should use non-root user..." # Simple check for RUN commands before USER (implying root operations) echo " Checking for potential root usage issues..." BEFORE_USER_SECTION=true while IFS= read -r line; do if [[ $line =~ ^USER[[:space:]] ]]; then BEFORE_USER_SECTION=false elif [[ $line =~ ^RUN[[:space:]] ]] && [ "$BEFORE_USER_SECTION" = true ]; then echo " ROOT RUN: $line" if [[ $line =~ (apt-get|apt|yum|dnf|install|add-apt-repository) ]]; then echo " ⚠ This RUN command executes as root with package management - consider if this is necessary" fi if [[ $line =~ (chmod|chown|useradd|groupadd) ]]; then echo " ⚠ This RUN command executes as root with system modifications - consider if this is necessary" fi fi done < "$DOCKERFILE_PATH" echo " Note: For security, try to limit operations as root to only package installs and system setup" echo " After those operations, switch to a non-root user with USER " echo echo "4. Additional security recommendations:" # Check for non-root user creation if grep -qE "USER [^0][0-9]*|USER [a-zA-Z]" "$DOCKERFILE_PATH"; then echo " ✓ Non-root user found in Dockerfile" else echo " ⚠ Consider adding a non-root user with 'USER ' directive after root operations" fi # Check for minimal packages installation if grep -q "apt-get install\|yum install\|apk add" "$DOCKERFILE_PATH"; then echo " ✓ Package installation found - ensure using --no-install-recommends (apt) or equivalent" else echo " - No package installation found" fi # Check for layer optimization RUN_COUNT=$(grep -c "^RUN " "$DOCKERFILE_PATH") if [ "$RUN_COUNT" -gt 5 ]; then echo " ⚠ Multiple ($RUN_COUNT) RUN commands found - consider combining where possible for fewer layers" fi echo echo "Dockerfile audit completed!" echo echo "For more detailed analysis, you can also build the image and scan it with:" echo " trivy image " echo " dive # if analyzing built images"