Lesson 10 of 10
Practice & Quiz - Cloud Security & DevSecOps
Test your cloud and DevSecOps knowledge: container security, IAM policies, secrets management, SAST/DAST integration, and cloud misconfiguration detection with a practical exercise and 5 quiz questions.
Practical Exercise - Docker Security Hardening & SBOM Generation
# ─── Secure Dockerfile Best Practices ────────────────────────
# Save as: Dockerfile.secure
SECURE_DOCKERFILE = """
# ✅ Use specific image digest instead of mutable tags
# FROM node:20-alpine → mutable, could change any time
FROM node:20.11.0-alpine3.19@sha256:a374c5e8bc... AS builder
# ✅ Create non-root user for application (don't run as root)
RUN addgroup -g 1001 -S appgroup && \
adduser -u 1001 -S appuser -G appgroup
WORKDIR /app
# ✅ Copy only package files first (layer caching optimization)
COPY package*.json ./
# ✅ Install prod deps only (no devDependencies in final image)
RUN npm ci --only=production && \
npm cache clean --force && \
# Remove npm to reduce attack surface
rm -rf /usr/lib/node_modules/npm
# Copy application code
COPY --chown=appuser:appgroup . .
# ✅ Multi-stage build: only copy artifacts, not build tools
FROM node:20.11.0-alpine3.19@sha256:a374c5e8bc... AS production
WORKDIR /app
COPY --from=builder --chown=appuser:appgroup /app .
# ✅ Switch to non-root user before CMD
USER appuser
# ✅ Read-only filesystem (use tmpfs for /tmp in docker-compose)
# docker run --read-only --tmpfs /tmp ...
EXPOSE 3000
# ✅ Use exec form (not shell form) to handle signals correctly
CMD ["node", "server.js"]
"""
print("Secure Dockerfile best practices:")
for line in SECURE_DOCKERFILE.split('\n'):
if line.strip().startswith('#'):
print(f' {line.strip()}')
# ─── Python: Container Security Scanner ───────────────────────
import subprocess, json, re
def analyze_dockerfile(dockerfile_path: str) -> list[dict]:
"""Static analysis of Dockerfile for security issues."""
issues = []
with open(dockerfile_path) as f:
lines = f.readlines()
for i, line in enumerate(lines, 1):
line_stripped = line.strip()
# Check for running as root
if re.match(r'^USER root', line_stripped, re.I):
issues.append({'line': i, 'severity': 'HIGH',
'issue': 'Explicitly running as root',
'fix': 'Use non-root user: USER appuser'})
# Check for mutable base image tags
if re.match(r'^FROM .+:latest', line_stripped, re.I):
issues.append({'line': i, 'severity': 'MEDIUM',
'issue': 'Using :latest tag (mutable, non-reproducible)',
'fix': 'Pin to specific version+digest: FROM image:1.2.3@sha256:...'})
# Check for secrets in ENV
if re.match(r'^ENV.+(PASSWORD|SECRET|KEY|TOKEN|API_KEY)\s*=', line_stripped, re.I):
issues.append({'line': i, 'severity': 'CRITICAL',
'issue': 'Secret/credential stored in ENV instruction',
'fix': 'Use Docker secrets or environment injection at runtime'})
# Check for curl|bash patterns
if 'curl' in line and ('|' in line) and ('bash' in line or 'sh' in line):
issues.append({'line': i, 'severity': 'HIGH',
'issue': 'Piping curl to shell (arbitrary code execution risk)',
'fix': 'Download, verify signature, then execute separately'})
# Privilege escalation risk
if '--privileged' in line_stripped:
issues.append({'line': i, 'severity': 'CRITICAL',
'issue': '--privileged disables all container security',
'fix': 'Use specific capabilities: --cap-add NET_ADMIN'})
return issues
# ─── AWS IAM Policy Analyzer ──────────────────────────────────
def analyze_iam_policy(policy: dict) -> list[dict]:
"""Check IAM policy for overly permissive statements."""
findings = []
for statement in policy.get('Statement', []):
if statement.get('Effect') != 'Allow':
continue
actions = statement.get('Action', [])
resources = statement.get('Resource', [])
if isinstance(actions, str):
actions = [actions]
if isinstance(resources, str):
resources = [resources]
# Wildcard action check
if '*' in actions or 'iam:*' in actions:
findings.append({'severity': 'CRITICAL',
'issue': f'Wildcard action: {actions}',
'fix': 'Enumerate specific required actions'})
# Wildcard resource check
if '*' in resources:
findings.append({'severity': 'HIGH',
'issue': 'Action applies to all resources (*)',
'fix': 'Scope to specific resource ARNs'})
return findings
# Example: overly permissive policy
bad_policy = {
'Statement': [{'Effect': 'Allow', 'Action': '*', 'Resource': '*'}]
}
findings = analyze_iam_policy(bad_policy)
print('\nIAM Policy Issues:')
for f in findings:
print(f' [{f["severity"]}] {f["issue"]} → {f["fix"]}')Module Quiz
What is the shared responsibility model in cloud security?
Tip
Tip
Practice Practice Quiz Cloud Security DevSecOps in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz Cloud Security DevSecOps from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz Cloud Security DevSecOps is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.
Finished this lesson?