Scan OS packages automatically

In this document you will learn how to enable the Container Scanning API, push an image to Artifact Registry, and see the list of vulnerabilities found in the image.

Artifact Analysis provides vulnerability information for the container images in Artifact Registry and Container Registry (Deprecated). The metadata is stored as notes. An occurrence is created for each instance of a note associated with an image. See the overview and pricing documents for more information.

Enabling this API also enables language package scanning in Artifact Registry. See supported package types.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Artifact Registry and Container Scanning APIs.

    Enable the APIs

  5. Install the Google Cloud CLI.
  6. To initialize the gcloud CLI, run the following command:

    gcloud init
  7. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  8. Make sure that billing is enabled for your Google Cloud project.

  9. Enable the Artifact Registry and Container Scanning APIs.

    Enable the APIs

  10. Install the Google Cloud CLI.
  11. To initialize the gcloud CLI, run the following command:

    gcloud init
  12. Create a Docker repository in Artifact Registry and push a container image to the repository. If you are not familiar with Artifact Registry, see the Docker quickstart.

Artifact Analysis does not automatically scan existing images. To scan an existing image, you must push it again.

View the image vulnerabilities

Artifact Analysis scans new images when they're uploaded to Artifact Registry. This scan extracts information about the system packages in the container.

You can view vulnerability occurrences for your images in the registry using Google Cloud console, Google Cloud CLI, or the Container Analysis API. If an image has vulnerabilities, you can then obtain the details.

Artifact Analysis only updates the metadata for images that were pushed or pulled in the last 30 days. Artifact Analysis archives metadata that is older than 30 days.To re-scan an image with archived metadata, pull that image. Refreshing metadata can take up to 24 hours.

View occurrences in Google Cloud console

To see the vulnerabilities in an image:

  1. Get the list of repositories.

    Open the Repositories page

  2. In the repositories list, click a repository.

  3. In the images list, click an image name.

    Vulnerability totals for each image digest are displayed in the Vulnerabilities column.

    Screenshot of an image with vulnerabilities

  4. To view the list of vulnerabilities for an image, click the link in the Vulnerabilities column.

    The Scan results section displays a summary of the package types scanned, total vulnerabilities, vulnerabilities with fixes available, vulnerabilities without fixes, and effective severity.

    Screenshot of the Scan Results section with vulnerabilities, fixes, and effective severity

    The table of vulnerabilities lists the Common Vulnerabilities and Exposures (CVE) name for each vulnerability found, the effective severity, Common Vulnerability Scoring System (CVSS) score, fixes (when available), the name of the package that contains the vulnerability, and the package type.

    You can filter and sort these files to check a specific file, directory, or type of file by file extension.

    Google Cloud console displays up to 1200 vulnerabilities in this table. If your image has more than 1200 vulnerabilities, you must use gcloud or the API to view the full list.

  5. For details about a specific CVE, click the CVE name.

  6. To view vulnerability occurrence details such as version number and affected location, click View or View Fixed in the row with the name of the vulnerability. The link text is View for vulnerabilities without a fix, and View Fixed for vulnerabilities where a fix has been applied.

View occurrences using gcloud

To view occurrences for an image:

Artifact Registry

gcloud artifacts docker images list --show-occurrences \
LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_ID

Where:

  • LOCATION is the regional or multi-regional location of the repository.
  • PROJECT_ID is your Google Cloud project ID.
  • REPOSITORY is the name of the repository where the image is stored.
  • IMAGE_ID is the name of the image in the repository. You cannot specify an image tag with this command.

By default, the command returns the 10 most recent images. To show a different number of images, use the --show-occurrences-from flag. For example, the following command returns the 25 most recent images.

gcloud artifacts docker images list --show-occurrences-from=25 \
us-central1-docker.pkg.dev/my-project/my-repo/my-image

Container Registry

gcloud beta container images list-tags \
HOSTNAME/PROJECT_ID/IMAGE_ID

Where:

  • HOSTNAME is the multi-regional hostname:
    • gcr.io
    • asia.gcr.io
    • eu.gcr.io
    • us.gcr.io
  • PROJECT_ID is the ID of the project containing the images.
  • IMAGE_ID is the ID of the image for which you want to view vulnerabilities. You cannot specify an image tag with this command.

By default, the command returns the 10 most recent images. To show a different number of images, use the --show-occurrences-from flag. For example, this command returns the 25 most recent images.

gcloud beta container images list-tags --show-occurrences-from=25 \
gcr.io/my-project/my-image

To view vulnerabilities for an image tag or a layer:

Artifact Registry

gcloud artifacts docker images describe \
LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_ID:TAG \
--show-package-vulnerability

or

gcloud artifacts docker images describe \
LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_ID@sha256:HASH \
--show-package-vulnerability

Where:

  • LOCATION is the regional or multi-regional location of the repository.
  • PROJECT_ID is your Google Cloud project ID.
  • REPOSITORY is the name of the repository where the image is stored.
  • IMAGE_ID is the name of the image in the repository.
  • TAG is the image tag about which you want to get information.
  • HASH is the image digest.

Container Registry

gcloud beta container images describe HOSTNAME/PROJECT_ID/IMAGE_ID@sha256:HASH \
--show-package-vulnerability

Where:

  • HOSTNAME is the multi-regional hostname:
    • gcr.io
    • asia.gcr.io
    • eu.gcr.io
    • us.gcr.io
  • PROJECT_ID is the ID of the project containing the images.
  • IMAGE_ID is the ID of the image for which you want to view vulnerabilities.
  • HASH is the image digest.

To filter the vulnerability occurrences:

Artifact Registry

gcloud artifacts docker images list --show-occurrences \
LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_ID --occurrence-filter=FILTER_EXPRESSION

Where:

  • LOCATION is the regional or multi-regional location of the repository.
  • PROJECT_ID is your Google Cloud project ID.
  • REPOSITORY is the name of the repository where the image is stored.
  • IMAGE_ID is the name of the image in the repository.
  • FILTER_EXPRESSION is a sample filter expression in the format explained in Filtering vulnerability occurrences.

Container Registry

gcloud beta container images list-tags \
HOSTNAME/PROJECT_ID/IMAGE_ID --occurrence-filter=FILTER_EXPRESSION

Where:

  • HOSTNAME is the multi-regional hostname:
    • gcr.io
    • asia.gcr.io
    • eu.gcr.io
    • us.gcr.io
  • PROJECT_ID is the ID of the project containing the images.
  • IMAGE_ID is the ID of the image for which you want to view vulnerability occurrences.
  • FILTER_EXPRESSION is a sample filter expression in the format explained in Filtering vulnerability occurrences.

View occurrences using the API or code

To view occurrences for an image, use the appropriate snippet. The code snippets specify URLs for images in Container Registry. If you are using Artifact Registry, specify images with a URL in the format:

LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_ID

API

Using cURL

To get a list of occurrences in your project:

 curl -X GET -H "Content-Type: application/json" -H \
    "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://containeranalysis.googleapis.com/v1/projects/PROJECT_ID/occurrences

To get a summary of vulnerabilities in your project:

 curl -X GET -H "Content-Type: application/json" -H \
    "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://containeranalysis.googleapis.com/v1/projects/PROJECT_ID/occurrences:vulnerabilitySummary

To get details on a specific occurrence:

 curl -X GET -H "Content-Type: application/json" -H \
    "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://containeranalysis.googleapis.com/v1/projects/PROJECT_ID/occurrences/OCCURRENCE_ID

Java

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Java API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.devtools.containeranalysis.v1.ContainerAnalysisClient;
import io.grafeas.v1.GrafeasClient;
import io.grafeas.v1.Occurrence;
import io.grafeas.v1.ProjectName;
import java.io.IOException;
import java.lang.InterruptedException;

public class OccurrencesForImage {
  // Retrieves all the Occurrences associated with a specified image
  // Here, all Occurrences are simply printed and counted
  public static int getOccurrencesForImage(String resourceUrl, String projectId)
      throws IOException, InterruptedException {
    // String resourceUrl = "https://gcr.io/project/image@sha256:123";
    // String projectId = "my-project-id";
    final String projectName = ProjectName.format(projectId);
    final String filterStr = String.format("resourceUrl=\"%s\"", resourceUrl);

    // Initialize client that will be used to send requests. After completing all of your requests, 
    // call the "close" method on the client to safely clean up any remaining background resources.
    GrafeasClient client = ContainerAnalysisClient.create().getGrafeasClient();
    int i = 0;
    for (Occurrence o : client.listOccurrences(projectName, filterStr).iterateAll()) {
      // Write custom code to process each Occurrence here
      System.out.println(o.getName());
      i = i + 1;
    }
    return i;
  }
}

Go

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Go API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import (
	"context"
	"fmt"
	"io"

	containeranalysis "cloud.google.com/go/containeranalysis/apiv1"
	"google.golang.org/api/iterator"
	grafeaspb "google.golang.org/genproto/googleapis/grafeas/v1"
)

// getOccurrencesForImage retrieves all the Occurrences associated with a specified image.
// Here, all Occurrences are simply printed and counted.
func getOccurrencesForImage(w io.Writer, resourceURL, projectID string) (int, error) {
	// Use this style of URL when you use Google Container Registry.
	// resourceURL := "https://gcr.io/my-project/my-repo/my-image"
	// Use this style of URL when you use Google Artifact Registry.
	// resourceURL := "https://LOCATION-docker.pkg.dev/my-project/my-repo/my-image"
	ctx := context.Background()
	client, err := containeranalysis.NewClient(ctx)
	if err != nil {
		return -1, fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &grafeaspb.ListOccurrencesRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		Filter: fmt.Sprintf("resourceUrl=%q", resourceURL),
	}
	it := client.GetGrafeasClient().ListOccurrences(ctx, req)
	count := 0
	for {
		occ, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return -1, fmt.Errorf("occurrence iteration error: %w", err)
		}
		// Write custom code to process each Occurrence here.
		fmt.Fprintln(w, occ)
		count = count + 1
	}
	return count, nil
}

Node.js

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Node.js API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * TODO(developer): Uncomment these variables before running the sample
 */
// const projectId = 'your-project-id', // Your GCP Project ID
// If you are using Google Container Registry
// const imageUrl = 'https://gcr.io/my-project/my-repo/my-image@sha256:123' // Image to attach metadata to
// If you are using Google Artifact Registry
// const imageUrl = 'https://LOCATION-docker.pkg.dev/my-project/my-repo/my-image@sha256:123' // Image to attach metadata to

// Import the library and create a client
const {ContainerAnalysisClient} = require('@google-cloud/containeranalysis');
const client = new ContainerAnalysisClient();

const formattedParent = client.getGrafeasClient().projectPath(projectId);

// Retrieves all the Occurrences associated with a specified image
const [occurrences] = await client.getGrafeasClient().listOccurrences({
  parent: formattedParent,
  filter: `resourceUrl = "${imageUrl}"`,
});

if (occurrences.length) {
  console.log(`Occurrences for ${imageUrl}`);
  occurrences.forEach(occurrence => {
    console.log(`${occurrence.name}:`);
  });
} else {
  console.log('No occurrences found.');
}

Ruby

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Ruby API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# resource_url = "The URL of the resource associated with the occurrence."
#                # e.g. https://gcr.io/project/image@sha256:123"
# project_id   = "The Google Cloud project ID of the occurrences to retrieve"

require "google/cloud/container_analysis"

# Initialize the client
client = Google::Cloud::ContainerAnalysis.container_analysis.grafeas_client

parent = client.project_path project: project_id
filter = "resourceUrl = \"#{resource_url}\""
count = 0
client.list_occurrences(parent: parent, filter: filter).each do |occurrence|
  # Process occurrence here
  puts occurrence
  count += 1
end
puts "Found #{count} occurrences"

Python

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Python API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud.devtools import containeranalysis_v1


def get_occurrences_for_image(resource_url: str, project_id: str) -> int:
    """Retrieves all the occurrences associated with a specified image.
    Here, all occurrences are simply printed and counted."""
    # resource_url = 'https://gcr.io/my-project/my-image@sha256:123'
    # project_id = 'my-gcp-project'

    filter_str = f'resourceUrl="{resource_url}"'
    client = containeranalysis_v1.ContainerAnalysisClient()
    grafeas_client = client.get_grafeas_client()
    project_name = f"projects/{project_id}"

    response = grafeas_client.list_occurrences(parent=project_name, filter=filter_str)
    count = 0
    for o in response:
        # do something with the retrieved occurrence
        # in this sample, we will simply count each one
        count += 1
    return count

View occurrences in Cloud Build

If you're using Cloud Build, you can also view image vulnerabilities in the Security insights side panel within the Google Cloud console.

The Security insights side panel provides a high-level overview of build security information for artifacts stored in Artifact Registry. To learn more about the side panel and how you can use Cloud Build to help protect your software supply chain, see View build security insights.

Filter occurrences

You can use filter strings in the gcloud commands and the Artifact Analysis API to filter occurrences before viewing them. The following sections describe the supported search filters.

View discovery occurrences

When an image is initially pushed to the Container Registry, it creates a discovery occurrence, which contains information about the initial scan of the container image.

To retrieve the discovery occurrence for an image, use the following filter expression:

kind="DISCOVERY" AND resourceUrl="RESOURCE_URL"

The following snippet shows how to use a filter expression to view discovery occurrences for an image. The code snippets specify URLs for images in Container Registry. If you are using Artifact Registry, specify images with a URL in the format:

LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_ID

gcloud

To view discovery occurrences for an image:

In this case the expression is not used directly in the command, but the same information is passed as arguments:

Artifact Registry:

gcloud artifacts docker images list --show-occurrences \
--occurrence-filter='kind="DISCOVERY"' --format=json \
LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_ID

Container Registry:

gcloud beta container images list-tags \
--occurrence-filter='kind="DISCOVERY"' --format=json HOSTNAME/PROJECT_ID/IMAGE_ID

API

To retrieve the discovery occurrence, your filter expression must be URL encoded and embedded in a GET request as follows:

GET https://containeranalysis.googleapis.com/v1/projects/PROJECT_ID/occurrences?filter=kind%3D%22DISCOVERY%22%20AND%20resourceUrl%3D%22ENCODED_RESOURCE_URL%22

See projects.occurrences.get API endpoint for more details.

Java

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Java API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.devtools.containeranalysis.v1.ContainerAnalysisClient;
import io.grafeas.v1.GrafeasClient;
import io.grafeas.v1.Occurrence;
import io.grafeas.v1.ProjectName;
import java.io.IOException;
import java.lang.InterruptedException;

public class GetDiscoveryInfo {
  // Retrieves and prints the Discovery Occurrence created for a specified image
  // The Discovery Occurrence contains information about the initial scan on the image
  public static void getDiscoveryInfo(String resourceUrl, String projectId) 
      throws IOException, InterruptedException {
    // String resourceUrl = "https://gcr.io/project/image@sha256:123";
    // String projectId = "my-project-id";
    String filterStr = "kind=\"DISCOVERY\" AND resourceUrl=\"" + resourceUrl + "\"";
    final String projectName = ProjectName.format(projectId);

    // Initialize client that will be used to send requests. After completing all of your requests, 
    // call the "close" method on the client to safely clean up any remaining background resources.
    GrafeasClient client = ContainerAnalysisClient.create().getGrafeasClient();
    for (Occurrence o : client.listOccurrences(projectName, filterStr).iterateAll()) {
      System.out.println(o);
    }
  }
}

Go

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Go API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import (
	"context"
	"fmt"
	"io"

	containeranalysis "cloud.google.com/go/containeranalysis/apiv1"
	"google.golang.org/api/iterator"
	grafeaspb "google.golang.org/genproto/googleapis/grafeas/v1"
)

// getDiscoveryInfo retrieves and prints the Discovery Occurrence created for a specified image.
// The Discovery Occurrence contains information about the initial scan on the image.
func getDiscoveryInfo(w io.Writer, resourceURL, projectID string) error {
	// Use this style of URL when you use Google Container Registry.
	// resourceURL := "https://gcr.io/my-project/my-repo/my-image"
	// Use this style of URL when you use Google Artifact Registry.
	// resourceURL := "https://LOCATION-docker.pkg.dev/my-project/my-repo/my-image"
	ctx := context.Background()
	client, err := containeranalysis.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &grafeaspb.ListOccurrencesRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		Filter: fmt.Sprintf(`kind="DISCOVERY" AND resourceUrl=%q`, resourceURL),
	}
	it := client.GetGrafeasClient().ListOccurrences(ctx, req)
	for {
		occ, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("occurrence iteration error: %w", err)
		}
		fmt.Fprintln(w, occ)
	}
	return nil
}

Node.js

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Node.js API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * TODO(developer): Uncomment these variables before running the sample
 */
// const projectId = 'your-project-id', // Your GCP Project ID
// If you are using Google Container Registry
// const imageUrl = 'https://gcr.io/my-project/my-repo/my-image:123' // Image to attach metadata to
// If you are using Google Artifact Registry
// const imageUrl = 'https://LOCATION-docker.pkg.dev/my-project/my-repo/my-image:123' // Image to attach metadata to

// Import the library and create a client
const {ContainerAnalysisClient} = require('@google-cloud/containeranalysis');
const client = new ContainerAnalysisClient();

const formattedParent = client.getGrafeasClient().projectPath(projectId);
// Retrieves and prints the Discovery Occurrence created for a specified image
// The Discovery Occurrence contains information about the initial scan on the image
const [occurrences] = await client.getGrafeasClient().listOccurrences({
  parent: formattedParent,
  filter: `kind = "DISCOVERY" AND resourceUrl = "${imageUrl}"`,
});

if (occurrences.length > 0) {
  console.log(`Discovery Occurrences for ${imageUrl}`);
  occurrences.forEach(occurrence => {
    console.log(`${occurrence.name}:`);
  });
} else {
  console.log('No occurrences found.');
}

Ruby

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Ruby API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# resource_url = "The URL of the resource associated with the occurrence."
#                # e.g. https://gcr.io/project/image@sha256:123
# project_id   = "The Google Cloud project ID of the occurrences to retrieve"

require "google/cloud/container_analysis"

# Initialize the client
client = Google::Cloud::ContainerAnalysis.container_analysis.grafeas_client

parent = client.project_path project: project_id
filter = "kind = \"DISCOVERY\" AND resourceUrl = \"#{resource_url}\""
client.list_occurrences(parent: parent, filter: filter).each do |occurrence|
  # Process discovery occurrence here
  puts occurrence
end

Python

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Python API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud.devtools import containeranalysis_v1


def get_discovery_info(resource_url: str, project_id: str) -> None:
    """Retrieves and prints the discovery occurrence created for a specified
    image. The discovery occurrence contains information about the initial
    scan on the image."""
    # resource_url = 'https://gcr.io/my-project/my-image@sha256:123'
    # project_id = 'my-gcp-project'

    filter_str = f'kind="DISCOVERY" AND resourceUrl="{resource_url}"'
    client = containeranalysis_v1.ContainerAnalysisClient()
    grafeas_client = client.get_grafeas_client()
    project_name = f"projects/{project_id}"
    response = grafeas_client.list_occurrences(parent=project_name, filter_=filter_str)
    for occ in response:
        print(occ)

View vulnerability occurrences

To view vulnerability occurrences for a specific image, create a query with a filter expression:

kind="VULNERABILITY" AND resourceUrl="RESOURCE_URL"

The following snippet shows how to retrieve a list of vulnerability occurrences for an image. The code snippets specify URLs for images in Container Registry. If you are using Artifact Registry, specify images with a URL in the format:

LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_ID

gcloud

To view vulnerability occurrences for an image:

In this case the expression is not used directly in the command, but the same information is passed as arguments:

Artifact Registry

gcloud artifacts docker images list --show-occurrences \
--occurrence-filter='kind="VULNERABILITY"' --format=json \
LOCATION-docker.pkg.dev/PROJECT_ID/REPOSITORY/IMAGE_ID

Container Registry

gcloud beta container images list-tags \
--occurrence-filter='kind="VULNERABILITY"' --format=json HOSTNAME/PROJECT_ID/IMAGE_ID

API

The resource URL must be URL encoded, and embedded in a GET request as follows:

GET https://containeranalysis.googleapis.com/v1/projects/PROJECT_ID/occurrences?filter=kind%3D%22VULNERABILITY%22%20AND%20resourceUrl%3D%22ENCODED_RESOURCE_URL%22

See projects.occurrences.get API endpoint for more details.

Java

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Java API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.devtools.containeranalysis.v1.ContainerAnalysisClient;
import io.grafeas.v1.GrafeasClient;
import io.grafeas.v1.Occurrence;
import io.grafeas.v1.ProjectName;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class VulnerabilityOccurrencesForImage {
  // Retrieve a list of vulnerability occurrences assoviated with a resource
  public static List<Occurrence> findVulnerabilityOccurrencesForImage(String resourceUrl, 
      String projectId) throws IOException {
    // String resourceUrl = "https://gcr.io/project/image@sha256:123";
    // String projectId = "my-project-id";
    final String projectName = ProjectName.format(projectId);
    String filterStr = String.format("kind=\"VULNERABILITY\" AND resourceUrl=\"%s\"", resourceUrl);

    // Initialize client that will be used to send requests. After completing all of your requests, 
    // call the "close" method on the client to safely clean up any remaining background resources.
    GrafeasClient client = ContainerAnalysisClient.create().getGrafeasClient();
    LinkedList<Occurrence> vulnerabilitylist = new LinkedList<Occurrence>();
    for (Occurrence o : client.listOccurrences(projectName, filterStr).iterateAll()) {
      vulnerabilitylist.add(o);
    }
    return vulnerabilitylist;
  }
}

Go

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Go API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


import (
	"context"
	"fmt"

	containeranalysis "cloud.google.com/go/containeranalysis/apiv1"
	"google.golang.org/api/iterator"
	grafeaspb "google.golang.org/genproto/googleapis/grafeas/v1"
)

// findVulnerabilityOccurrencesForImage retrieves all vulnerability Occurrences associated with a resource.
func findVulnerabilityOccurrencesForImage(resourceURL, projectID string) ([]*grafeaspb.Occurrence, error) {
	// Use this style of URL when you use Google Container Registry.
	// resourceURL := "https://gcr.io/my-project/my-repo/my-image"
	// Use this style of URL when you use Google Artifact Registry.
	// resourceURL := "https://LOCATION-docker.pkg.dev/my-project/my-repo/my-image"
	ctx := context.Background()
	client, err := containeranalysis.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewClient: %w", err)
	}
	defer client.Close()

	req := &grafeaspb.ListOccurrencesRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		Filter: fmt.Sprintf("resourceUrl = %q kind = %q", resourceURL, "VULNERABILITY"),
	}

	var occurrenceList []*grafeaspb.Occurrence
	it := client.GetGrafeasClient().ListOccurrences(ctx, req)
	for {
		occ, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return nil, fmt.Errorf("occurrence iteration error: %w", err)
		}
		occurrenceList = append(occurrenceList, occ)
	}

	return occurrenceList, nil
}

Node.js

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Node.js API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * TODO(developer): Uncomment these variables before running the sample
 */
// const projectId = 'your-project-id', // Your GCP Project ID
// If you are using Google Container Registry
// const imageUrl = 'https://gcr.io/my-project/my-repo/my-image:123' // Image to attach metadata to
// If you are using Google Artifact Registry
// const imageUrl = 'https://LOCATION-docker.pkg.dev/my-project/my-repo/my-image:123' // Image to attach metadata to

// Import the library and create a client
const {ContainerAnalysisClient} = require('@google-cloud/containeranalysis');
const client = new ContainerAnalysisClient();

const formattedParent = client.getGrafeasClient().projectPath(projectId);

// Retrieve a list of vulnerability occurrences assoviated with a resource
const [occurrences] = await client.getGrafeasClient().listOccurrences({
  parent: formattedParent,
  filter: `kind = "VULNERABILITY" AND resourceUrl = "${imageUrl}"`,
});

if (occurrences.length) {
  console.log(`All Vulnerabilities for ${imageUrl}`);
  occurrences.forEach(occurrence => {
    console.log(`${occurrence.name}:`);
  });
} else {
  console.log('No occurrences found.');
}

Ruby

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Ruby API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# resource_url = "The URL of the resource associated with the occurrence
#                e.g. https://gcr.io/project/image@sha256:123"
# project_id   = "The Google Cloud project ID of the vulnerabilities to find"

require "google/cloud/container_analysis"

# Initialize the client
client = Google::Cloud::ContainerAnalysis.container_analysis.grafeas_client

parent = client.project_path project: project_id
filter = "resourceUrl = \"#{resource_url}\" AND kind = \"VULNERABILITY\""
client.list_occurrences parent: parent, filter: filter

Python

To learn how to install and use the client library for Artifact Analysis, see Artifact Analysis client libraries. For more information, see the Artifact Analysis Python API reference documentation.

To authenticate to Artifact Analysis, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from typing import List

from google.cloud.devtools import containeranalysis_v1
from grafeas.grafeas_v1 import types


def find_vulnerabilities_for_image(
    resource_url: str, project_id: str
) -> List[types.grafeas.Occurrence]:
    """ "Retrieves all vulnerability occurrences associated with a resource."""
    # resource_url = 'https://gcr.io/my-project/my-image@sha256:123'
    # project_id = 'my-gcp-project'

    client = containeranalysis_v1.ContainerAnalysisClient()
    grafeas_client = client.get_grafeas_client()
    project_name = f"projects/{project_id}"

    filter_str = 'kind="VULNERABILITY" AND resourceUrl="{}"'.format(resource_url)
    return list(grafeas_client.list_occurrences(parent=project_name, filter=filter_str))

View occurrences of a specific type

In the two previous examples the only difference between the filter expressions is the value of kind, which identifies the type of occurrence. Use this field to limit the list of occurrences to a particular type, such as a vulnerability or deployment.

To retrieve occurrences for a specific image, use this filter expression:

kind="NOTE_KIND" AND resourceUrl="RESOURCE_URL"

Where:

  • NOTE_KIND is the kind of note.
    • For example, use the kind DISCOVERY to list discovery occurrences. These are created for images when they are initially pushed to the Container Registry.
    • To list vulnerability occurrences, use the kind VULNERABILITY.
  • RESOURCE_URL is the complete URL of the image https://HOSTNAME/PROJECT_ID/IMAGE_ID@sha256:HASH

The filter expression to retrieve occurrences of a specific kind across many images is:

kind="NOTE_KIND" AND has_prefix(resourceUrl, "RESOURCE_URL_PREFIX")

Where:

  • RESOURCE_URL_PREFIX is the URL prefix for some images
    • To list for all version of an image: https://HOSTNAME/PROJECT_ID/IMAGE_ID@
    • To list for all images in a project: https://HOSTNAME/PROJECT_ID/

View images associated with a specific note

You can retrieve a list of resources that are associated with a specific note ID. For example, you can list images with a specific CVE vulnerability.

To list all images within a project that are associated with a particular note, use the following filter expression:

noteProjectId="PROVIDER_PROJECT_ID" AND noteId="NOTE_ID"

To check a specific image for a specific note, use the following filter expression:

resourceUrl="RESOURCE_URL" AND noteProjectId="PROVIDER_PROJECT_ID" \
    AND noteId="NOTE_ID"

Where:

  • PROVIDER_PROJECT_ID is the ID of the provider project. For example, goog-vulnz provides the default vulnerability analysis.
  • NOTE_ID is the ID of the note. Security related notes are often formatted as CVE-2019-12345.
  • RESOURCE_URL is the complete URL of the image https://HOSTNAME/PROJECT_ID/IMAGE_ID@sha256:HASH

For example, to check for all images that have an occurrence of CVE-2017-16231 as analyzed by Google, use the following filter expression:

noteProjectId="goog-vulnz" AND noteId="CVE-2017-16231"

What's next