COMP-222 · Lesson 5 of 12 · 20 min

Container, cloud and infrastructure-as-code scanning

▶ Video coming soon A video version of this lesson is on the way.

The member portal staging environment did not live on a server in Prairiefold's head office. It ran in the credit union's Azure subscription as a set of containers on a managed Kubernetes cluster, with a storage account for documents, a managed database, and networking defined in Terraform files in the development team's repository. When Priyanka listed what she would test, half the items were not hosts at all. They were images, templates, policies and secrets. Tobias asked how you scan something that is not running. Priyanka said that was the point: many of the most serious cloud weaknesses can be found before anything runs, if you know where to look.

Objective 3.1 names container scans, including sidecar scans, static analysis of infrastructure as code, and secrets scanning, along with the tools TruffleHog, Grype, Trivy and Kube-hunter. This lesson covers each, plus the read-only cloud configuration review that ties them together. The cloud attacks that follow from these findings belong to objective 4.6 and PenTest+: Attacks and Exploits.

Why containers change discovery

A container image is a packaged file system and configuration from which containers are started. Images are built in layers: a base image, usually a minimal operating system distribution, then layers that add language runtimes, libraries and the application itself. Images are stored in a registry and pulled by hosts or orchestrators such as Kubernetes when containers start. Running containers are meant to be short-lived and replaceable; when an image is fixed, the fix is deployed by building a new image and replacing the containers, not by patching them in place.

Those properties change how vulnerabilities are found. A traditional scanner logging in to a running container would find the same packages every container from that image has, and any fix it suggested would vanish when the container was replaced. The effective place to look is the image itself, in the registry or the build pipeline, and the effective fix is in the image definition. At the same time, what is actually running matters, because old images can keep running long after a fixed version is published.

A container image drawn as stacked layers: base operating system at the bottom, then language runtime, then libraries, then application code at the top. Arrows show where scanning happens: in the build pipeline, in the registry on a schedule, and at runtime either periodically or through a sidecar container in the same pod as the application container.
Image layers and the points where container scanning happens.

Image scanners: Trivy and Grype

Trivy, an open-source scanner from Aqua Security, and Grype, an open-source scanner from Anchore, both scan container images for known vulnerabilities. They identify the operating system packages and language libraries in each layer, compare them with vulnerability data, and report each affected package, its installed version, the fixed version if one exists, and the CVE and severity. Both can also scan a directory or file system and read a software bill of materials. Trivy goes further, scanning infrastructure-as-code files and Kubernetes clusters for misconfigurations and finding secrets. Anchore's companion tool Syft generates the SBOMs that Grype can scan.

Abridged and anonymized Trivy output for a portal image. CVE numbers are placeholders.
trivy image --severity HIGH,CRITICAL registry.prairiefold.example/portal-api:1.8.2

portal-api:1.8.2 (debian 12.5)
Total: 7 (HIGH: 5, CRITICAL: 2)

Library      Vulnerability   Severity  Installed  Fixed     Title
libexpat1    CVE-2024-XXXXX  CRITICAL  2.5.0-1    2.5.0-1+  XML parser integer overflow
openssl      CVE-2024-YYYYY  HIGH      3.0.11-1   3.0.13-1  Denial of service in ...

Node.js (package-lock.json)
Library      Vulnerability   Severity  Installed  Fixed     Title
jsonparse    CVE-2025-ZZZZZ  HIGH      4.1.0      4.1.3     Prototype pollution

Reading the output is straightforward once you know the columns. The scan found two kinds of components: operating system packages from the Debian base image, and JavaScript libraries from the application's lock file. Each row shows what is installed and what version fixes it. The practical questions are the same as for any scan. Is a fixed version available? Is the vulnerable component used at runtime, or only present? Would rebuilding on a newer base image fix most of the rows at once? In the portal's case, five of the seven findings disappeared when Priyanka rebuilt the image locally on the current base image, which made the remediation advice simple: rebuild regularly and pin to a maintained base.

Priyanka compared Trivy's results with Grype's for the same image. They agreed on six findings and differed on one, because the two tools use different data sources and matching logic. Differences like this are normal and a reason not to treat any single scanner as the truth. For the report, she recorded both tool versions and database dates, so that anyone rerunning the scans later could explain differences.

Where container scans run: pipeline, registry, periodic and sidecar

Container scanning can happen at several points, and the objectives call out two runtime patterns.

Points at which container scanning runs.
WhereHowWhat it catches
Build pipelineThe scanner runs after each image build and can fail the build on serious findingsNew vulnerabilities before they ship
RegistryImages in the registry are rescanned on a schedule against updated vulnerability dataNewly disclosed vulnerabilities in images already built
Periodic runtime scanA scheduled job lists running workloads and scans the images they useOld images still running after fixes were published
Sidecar scanA scanning container runs alongside the application container in the same pod, sharing its contextThe live state of a specific workload, including files added at runtime

A sidecar is a helper container deployed in the same Kubernetes pod as the main application container. Sidecars commonly handle logging, proxies and service mesh traffic. A sidecar scan uses this pattern for security: the scanning container can see the application's file system or process space, depending on how the pod is configured, and inspect what is actually present while the workload runs. Its advantage is precision: it sees the live workload rather than the image it started from. Its costs are resources in every pod, added configuration, and the extra privilege the sidecar may need, which itself must be secured. A periodic scan is lighter: a job wakes up on a schedule, finds what is running and checks it. Many organizations use registry and periodic scanning broadly and reserve sidecars for sensitive workloads.

Kubernetes: Kube-hunter and configuration benchmarks

Kube-hunter, also from Aqua Security, hunts for security weaknesses in Kubernetes clusters. It can run remotely against a cluster address, scan the machine's network interfaces, scan a range of addresses, or run as a pod inside the cluster to show what an attacker who compromised an application pod could reach. By default it performs passive hunting that does not change cluster state; an active option attempts to exploit what it finds and can change the cluster, so it should be used only with explicit permission. The project's page now states that it is not under active development and recommends Trivy's Kubernetes scanning instead, but it remains on the exam objectives.

Configuration checks complement hunting. The CIS Kubernetes Benchmark sets out recommended settings for cluster components, and tools such as kube-bench check a cluster against it. Trivy's Kubernetes mode reports misconfigurations in workloads, such as containers running as root, missing resource limits, host path mounts and privileged containers, along with vulnerabilities in the images in use. Managed Kubernetes services, including Prairiefold's, handle the control plane themselves, so many benchmark items become the provider's responsibility and the tester focuses on workload and access configuration.

Priyanka ran Trivy's Kubernetes scan with a read-only account that Prairiefold created for the purpose. It found that two staging workloads ran as root and one mounted a host directory, which would make escaping the container easier if the application were compromised. It also found that the Kubernetes dashboard had been deployed in staging with a service account that could read secrets across namespaces. These were configuration findings, not CVEs, and they would never have shown up in an image scan.

Infrastructure as code

Infrastructure as code (IaC) describes infrastructure in files that tools apply automatically: Terraform, Azure Bicep and Resource Manager templates, AWS CloudFormation, Kubernetes manifests and Helm charts. Because the files define what will be built, scanning them finds misconfigurations before deployment. IaC scanning is a form of static analysis, and the objective lists it under SAST. Tools such as Checkov, KICS and Trivy's configuration scanner check IaC files against hundreds of rules: storage that allows public access, databases without encryption, network rules open to the whole internet, logging disabled, and identities with broad permissions.

Simplified IaC-style pseudocode. A scanner flags the first rule because it opens remote desktop to any source.
// Risky pattern in a network rule definition
rule "allow-admin" {
  direction  = inbound
  port       = 3389
  source     = any
  action     = allow
}

// Safer pattern: restrict to the management network
rule "allow-admin" {
  direction  = inbound
  port       = 3389
  source     = management_subnet
  action     = allow
}

Priyanka scanned the portal's Terraform directory. Most findings were minor, but two stood out: the storage account allowed public access to blobs at the account level, the same setting that had let a public events container, found during reconnaissance and closed within the hour on October 20, expose member event registrations; and a network rule opened remote desktop to any source on a jump host used by developers. She then checked the live environment through a read-only role and found that the deployed resources matched the templates. That last step matters. IaC scanning shows what the code says; the deployed environment may differ because someone changed it by hand, a pattern called configuration drift. A finding is stronger when both the code and the live state confirm it.

Cloud configuration review

Cloud environments expose their configuration through management APIs. With a read-only role, a tester can list every resource, its settings and its access policies far more completely than any network scan. Cloud security posture management tools, built into the major providers or available separately, compare that configuration with benchmarks such as the CIS Foundations Benchmarks. Open-source tools such as ScoutSuite and Prowler do similar work for testers. In Azure, Microsoft Defender for Cloud provides recommendations and a secure score; Prairiefold's team already used it, and Priyanka compared her findings with its recommendations.

The tester's value over the built-in tools lies in context and combination. Defender for Cloud correctly flagged the public storage setting. It did not know that the staging application wrote copies of uploaded member documents, synthetic in staging but real in production, to that same storage account. Combined with a predictable naming pattern for document containers, the public setting would expose files to anyone who guessed a name. That combination, and its production implication, was what made the finding high severity.

Secrets scanning and TruffleHog

Secrets scanning looks for credentials, keys and tokens in places they should not be: source code, commit history, configuration files, container images, logs, tickets and chat exports. Secrets in code are one of the most common causes of cloud compromise, because a repository that is copied, leaked or made public by mistake hands the credentials to anyone who finds it. Deleting a secret from the latest version does not remove it from the repository's history.

TruffleHog, from Truffle Security, scans git repositories, including their full history, along with file systems, cloud storage buckets and other sources. It uses hundreds of detectors that recognize the formats of specific credential types. Its distinctive feature is verification: for many detectors it can check whether a found credential is live by making a harmless authentication request to the relevant service. An option limits output to verified results only, which cuts noise dramatically.

Abridged TruffleHog output from the portal repository; the secret value is redacted.
trufflehog git file://./portal-repo --only-verified

Found verified result
Detector Type: AzureStorage
File: deploy/old/settings.json
Commit: 3f2c9a1 (2025-04-18)
Line: 12

Verification has a legal and ethical dimension. Checking a credential means using it against a service, which may belong to a third party or to an environment outside scope. Prairiefold's rules of engagement allowed verification only for credentials belonging to Prairiefold's own Azure tenant. Priyanka ran TruffleHog first without verification, reviewed what it found, and then verified only the in-scope candidates. One verified result, a storage account key committed in April 2025 and later removed from the file, was still valid. She notified Gwendolyn Tran the same day under the stop-and-report rule for live credentials. Prairiefold rotated the key within the hour, and the finding recommended adding secrets scanning to the repository so that commits containing credentials were blocked before they were pushed.

Detection and defence

Defenders can see most of this activity. Cloud audit logs record every API call a tester makes with a read-only role, including the listing of resources and reading of configuration. Kubernetes audit logs record requests to the cluster API. Registry logs record image pulls. Secrets verification requests appear in the logs of the service being called. A mature client watches for unusual enumeration from unexpected identities and alerts on any use of credentials that should have been revoked.

The remediations for this lesson's findings are mostly process changes: scan images and IaC in the pipeline and fail builds on serious issues; rebuild images regularly on maintained base images; run workloads as non-root with minimal privileges; use policy enforcement in the cluster to block risky configurations; prevent public storage by policy at the subscription level; store secrets in a managed vault rather than in code; and enable secrets scanning with push protection on every repository.

Worked problem

Rating a cloud finding with context

A posture tool flags a storage account that allows public blob access as medium. Priyanka finds that the portal stores uploaded member documents there and that container names follow a predictable pattern. In production, the documents are real. How should the finding be rated and described?

Show solution
  1. Confirm the setting in the live environment, not just the template.
  2. Describe the combination: public access plus predictable names plus sensitive content.
  3. Note the production implication, since staging mirrors production design.
  4. Rate higher than the tool's default because impact on confidentiality is high and exploitation needs only guessing.
  5. Recommend disabling public access by policy and using signed, time-limited access for legitimate downloads.

Answer: High, with the combination of factors and the production implication stated as the reason.

Common mistakes

  • MistakePatching packages inside running containers.

    InsteadFix the image definition, rebuild and redeploy.

  • MistakeRunning Kube-hunter's active mode without permission.

    InsteadUse passive hunting unless active testing is explicitly authorized.

  • MistakeTrusting IaC scan results as the deployed state.

    InsteadCheck the live environment for drift through a read-only role.

  • MistakeVerifying every secret a scanner finds.

    InsteadVerify only credentials for in-scope systems, as the rules allow.

  • MistakeAssuming a secret deleted from the latest commit is gone.

    InsteadScan the full history and rotate any exposed secret.

Summary and key terms

  • Container images are layered and immutable; scan them in the pipeline and registry and fix them by rebuilding.
  • Trivy and Grype report vulnerable packages with installed and fixed versions; Trivy also scans IaC, Kubernetes and secrets.
  • Sidecar scans run beside a workload in the same pod; periodic scans check running workloads on a schedule.
  • Kube-hunter hunts for Kubernetes weaknesses; active mode can change the cluster, and the project is no longer actively developed.
  • IaC scanning is static analysis of infrastructure definitions; confirm findings against the live state to catch drift.
  • Read-only cloud configuration review finds what network scans cannot; testers add context and combinations.
  • TruffleHog finds secrets in repositories and history and can verify whether they are live, within agreed limits.
Container image
A layered, packaged file system and configuration from which containers start.
Registry
A service that stores and distributes container images.
Sidecar scan
A scan performed by a helper container running in the same pod as the workload.
Infrastructure as code
Infrastructure defined in files that tools apply automatically.
Configuration drift
Differences between the defined configuration and what is actually deployed.
Cloud security posture management
Tools that compare cloud configuration with security benchmarks.
Secrets scanning
Searching code, history and artifacts for exposed credentials and keys.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why do container scanners often recommend rebuilding on a newer base image?

    Show answer

    Many findings come from base image packages, so one rebuild fixes many at once.

  2. What is the risk of TruffleHog's verification feature in an engagement?

    Show answer

    It uses found credentials against services that may be out of scope or owned by third parties.

  3. An IaC scan is clean, but the deployed storage account is public. What explains this?

    Show answer

    Configuration drift: someone changed the live resource outside the code.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz