Memindai paket OS secara otomatis

Dalam dokumen ini, Anda akan mempelajari cara mengaktifkan Container Scanning API, mengirim image ke Artifact Registry, dan melihat daftar kerentanan yang ditemukan dalam image.

Artifact Analysis memberikan informasi kerentanan untuk image container di Artifact Registry. Metadata disimpan sebagai catatan. Kemunculan dibuat untuk setiap instance catatan yang terkait dengan gambar. Lihat dokumen ringkasan dan harga untuk mengetahui informasi selengkapnya.

Sebelum memulai

  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. Verify 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. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  7. To initialize the gcloud CLI, run the following command:

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

    Go to project selector

  9. Verify that billing is enabled for your Google Cloud project.

  10. Enable the Artifact Registry and Container Scanning APIs.

    Enable the APIs

  11. Install the Google Cloud CLI.

  12. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  13. To initialize the gcloud CLI, run the following command:

    gcloud init
  14. Buat repositori Docker di Artifact Registry dan kirim image container ke repositori. Jika Anda belum terbiasa dengan Artifact Registry, lihat Panduan memulai Docker.

Mengaktifkan API ini juga akan mengaktifkan pemindaian paket bahasa di Artifact Registry. Lihat jenis paket yang didukung.

Melihat kerentanan gambar

Artifact Analysis memindai image baru saat diupload ke Artifact Registry. Pemindaian ini mengekstrak informasi tentang paket sistem dalam container.

Anda dapat melihat kemunculan kerentanan untuk image di registri menggunakan konsol Google Cloud , Google Cloud CLI, atau Container Analysis API. Jika gambar memiliki kerentanan, Anda dapat memperoleh detailnya.

Analisis Artefak hanya memperbarui metadata untuk gambar yang di-push atau ditarik dalam 30 hari terakhir. Setelah 30 hari, metadata tidak akan diperbarui lagi, dan hasilnya akan menjadi tidak valid. Selain itu, Analisis Artefak mengarsipkan metadata yang sudah tidak berlaku selama lebih dari 90 hari, dan metadata tersebut tidak akan tersedia di konsol Google Cloud , gcloud, atau menggunakan API. Untuk memindai ulang gambar dengan metadata yang tidak berlaku atau diarsipkan, tarik gambar tersebut. Memperbarui metadata dapat memerlukan waktu hingga 24 jam.

Melihat kemunculan di konsol Google Cloud

Untuk melihat kerentanan dalam image:

  1. Dapatkan daftar repositori.

    Buka halaman Repositori

  2. Di daftar repositori, klik repositori.

  3. Di daftar gambar, klik nama gambar.

    Jumlah total kerentanan untuk setiap ringkasan gambar ditampilkan di kolom Kerentanan.

    Image yang dipindai dengan kerentanan

  4. Untuk melihat daftar kerentanan pada image, klik link di kolom Kerentanan.

    Bagian Hasil pemindaian menampilkan ringkasan jenis paket yang dipindai, total kerentanan, kerentanan dengan perbaikan yang tersedia, kerentanan tanpa perbaikan, dan tingkat keparahan efektif.

    Halaman Hasil pemindaian yang mencantumkan kerentanan, perbaikan, dan tingkat keparahan efektif

    Tabel kerentanan mencantumkan nama Kerentanan dan Eksposur Umum (CVE) untuk setiap kerentanan yang ditemukan, tingkat keparahan efektif, skor Sistem Penskoran Kerentanan Umum (CVSS), perbaikan (jika tersedia), nama paket yang berisi kerentanan, dan jenis paket. Anda dapat memfilter dan mengurutkan file ini untuk memeriksa file, direktori, atau jenis file tertentu menurut ekstensi file. Konsol Google Cloud menampilkan hingga 1.200 kerentanan per halaman dalam tabel ini.

  5. Untuk mengetahui detail CVE tertentu, klik nama CVE.

  6. Untuk melihat detail kemunculan kerentanan seperti nomor versi dan lokasi yang terpengaruh, klik Lihat atau Lihat yang Sudah Diperbaiki di baris dengan nama kerentanan. Teks link adalah Lihat untuk kerentanan tanpa perbaikan, dan Lihat yang Sudah Diperbaiki untuk kerentanan yang telah diperbaiki.

Melihat kemunculan menggunakan gcloud

Untuk melihat kemunculan image di Artifact Registry, jalankan perintah gcloud artifacts docker images list:

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

Dengan:

  • LOCATION adalah lokasi repositori regional atau multi-regional.
  • PROJECT_ID adalah Google Cloud project ID konsol Anda.
  • REPOSITORY adalah nama repositori tempat image disimpan.
  • IMAGE_ID adalah nama image di repositori. Anda tidak dapat menentukan tag gambar dengan perintah ini.

Secara default, perintah ini menampilkan 10 gambar terbaru. Untuk menampilkan jumlah gambar yang berbeda, gunakan tanda --show-occurrences-from. Misalnya, perintah berikut menampilkan 25 gambar terbaru:

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

Output-nya akan terlihat mirip dengan:

Contoh output gambar

  {
      "name": "projects/my-project/locations/us-central1/occurrences/22d3edfb-34f2-4d3f-be08-fd90c549f010",
      "resource": {
        "uri": "https://us-central1-docker.pkg.dev/my-project/my-repo/golang-nginx@sha256:5b54ef20748417ccdb0b87afedf98c44e699e2f59bd6cv48cbdc1ca2e72c80e3"
      },
      "noteName": "projects/my-project/locations/us-central1/notes/CVE-2005-2541",
      "kind": "VULNERABILITY",
      "createTime": "2025-01-21T15:57:01.238832Z",
      "updateTime": "2025-01-21T15:57:01.238832Z",
      "vulnerability": {
        "severity": "CRITICAL",
        "cvssScore": 10,
        "packageIssue": [
          {
            "affectedLocation": {
              "cpeUri": "cpe:/o:debian:debian_linux:12",
              "package": "tar",
              "version": {
                "name": "1.34+dfsg",
                "revision": "1.2+deb12u1",
                "kind": "NORMAL"
              }
            },
            "fixedLocation": {
              "cpeUri": "cpe:/o:debian:debian_linux:12",
              "package": "tar",
              "version": {
                "kind": "MAXIMUM"
              }
            },
            "packageType": "OS",
            "effectiveSeverity": "LOW",
            "file_location": [
                {
                "file_path": "/var/lib/dpkg/status",
                "layerDetails": {
                  "index": 0,
                  "diffID": "sha256:123",
                  "buildCommand": "FROM golang:example_sha256",
                  "BaseImages": [
                    {
                      "name": "library/golang",
                    },
                  ],
                },
              },
            ],
          }
        ],
        "shortDescription": "CVE-2005-2541",
        "longDescription": "NIST vectors: AV:N/AC:L/Au:N/C:C/I:C/A:C",
        "relatedUrls": [
          {
            "url": "https://security-tracker.debian.org/tracker/CVE-2005-2541",
            "label": "More Info"
          }
        ],
        "effectiveSeverity": "LOW",
        "cvssVersion": "CVSS_VERSION_2",
        "cvssV2": {
          "baseScore": 10,
          "attackVector": "ATTACK_VECTOR_NETWORK",
          "attackComplexity": "ATTACK_COMPLEXITY_LOW",
          "authentication": "AUTHENTICATION_NONE",
          "confidentialityImpact": "IMPACT_COMPLETE",
          "integrityImpact": "IMPACT_COMPLETE",
          "availabilityImpact": "IMPACT_COMPLETE"
        }
      }
    }
  

Melihat kerentanan untuk tag image

Untuk melihat kerentanan pada tag image, masukkan salah satu perintah berikut:

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

atau

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

Dengan:

  • LOCATION adalah lokasi repositori regional atau multi-regional.
  • PROJECT_ID adalah Google Cloud project ID konsol Anda.
  • REPOSITORY adalah nama repositori tempat image disimpan.
  • IMAGE_ID adalah nama image di repositori.
  • TAG adalah tag gambar yang ingin Anda dapatkan informasinya.
  • HASH adalah ringkasan gambar.

Artifact Analysis menampilkan hasil yang mencakup packageType.

Memfilter kemunculan kerentanan

Untuk memfilter kemunculan kerentanan, gunakan parameter --occurrence-filter:

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

Dengan:

  • LOCATION adalah lokasi repositori regional atau multi-regional.
  • PROJECT_ID adalah Google Cloud project ID konsol Anda.
  • REPOSITORY adalah nama repositori tempat image disimpan.
  • IMAGE_ID adalah nama image di repositori.
  • FILTER_EXPRESSION adalah contoh ekspresi filter dalam format yang dijelaskan dalam Memfilter kemunculan kerentanan.

Melihat kerentanan untuk lapisan tertentu

Anda dapat menggunakan kolom layerDetails untuk menentukan lapisan spesifik yang memperkenalkan paket rentan, dan untuk melihat informasi tambahan tentang lapisan tersebut. Misalnya, perhatikan output layerDetails berikut untuk sebuah gambar:

  "layerDetails": {
    "index": 0,
    "diffID": "sha256:123",
    "buildCommand": "FROM golang:example_sha256",
    "BaseImages": [
      {
        "name": "library/golang",
      },
    ],
  }

Output menunjukkan bahwa indeks lapisan adalah 0 dalam image container, dengan hash lapisan sha256:123. Perintah build Docker yang digunakan untuk membangun lapisan ini adalah FROM golang:example_sha256, dan lapisan ini juga ditemukan di image dasar library/golang.

Melihat kemunculan menggunakan API atau kode

Untuk melihat kemunculan gambar, tentukan gambar dengan URL dalam format berikut:

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

API

Menggunakan cURL

Untuk mendapatkan daftar kemunculan dalam project Anda:

 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

Untuk mendapatkan ringkasan kerentanan dalam project Anda:

 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

Untuk mendapatkan detail tentang kemunculan tertentu:

 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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * 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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Ruby Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

# 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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Melihat kemunculan di Cloud Build

Jika menggunakan Cloud Build, Anda juga dapat melihat kerentanan image di panel samping Insight keamanan dalam konsol Google Cloud .

Panel samping Insight keamanan memberikan ringkasan informasi keamanan build tingkat tinggi untuk artefak yang disimpan di Artifact Registry. Untuk mempelajari lebih lanjut panel samping dan cara menggunakan Cloud Build untuk membantu melindungi supply chain software Anda, lihat Melihat insight keamanan build.

Memfilter kemunculan

Anda dapat menggunakan string filter dalam perintah gcloud dan Artifact Analysis API untuk memfilter kemunculan sebelum melihatnya. Bagian berikut menjelaskan filter penelusuran yang didukung.

Melihat kemunculan penemuan

Saat image pertama kali dikirim ke Artifact Registry, Artifact Registry akan membuat kejadian penemuan, yang berisi informasi tentang pemindaian awal image container.

Untuk mengambil temuan penemuan untuk gambar, gunakan ekspresi filter berikut:

kind="DISCOVERY" AND resourceUrl="RESOURCE_URL"

Dengan RESOURCE_URL memiliki format berikut:

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

gcloud

Melihat kemunculan penemuan untuk gambar:

Dalam hal ini, ekspresi tidak digunakan secara langsung dalam perintah, tetapi informasi yang sama diteruskan sebagai argumen:

Artifact Registry:

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

API

Untuk mengambil kemunculan penemuan, ekspresi filter Anda harus dienkode URL dan disematkan dalam permintaan GET sebagai berikut:

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

Lihat endpoint API projects.occurrences.get untuk mengetahui detail selengkapnya.

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * 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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Ruby Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

# 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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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)

Melihat kemunculan kerentanan

Untuk melihat kemunculan kerentanan untuk image tertentu, buat kueri dengan ekspresi filter:

kind="VULNERABILITY" AND resourceUrl="RESOURCE_URL"

Dengan RESOURCE_URL memiliki format berikut:

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

gcloud

Dalam hal ini, ekspresi tidak digunakan secara langsung dalam perintah, tetapi informasi yang sama diteruskan sebagai argumen:

Artifact Registry

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

API

URL resource harus dienkode ke URL, dan disematkan dalam permintaan GET sebagai berikut:

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

Lihat endpoint API projects.occurrences.get untuk mengetahui detail selengkapnya.

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

/**
 * 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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Ruby Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

# 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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Artifact Analysis, lihat library klien Artifact Analysis. Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Artifact Analysis.

Untuk melakukan autentikasi ke Artifact Analysis, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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))

Melihat kemunculan jenis tertentu

Dalam dua contoh sebelumnya, satu-satunya perbedaan antara ekspresi filter adalah nilai kind, yang mengidentifikasi jenis kejadian. Gunakan kolom ini untuk membatasi daftar kemunculan ke jenis tertentu, seperti kerentanan atau deployment.

Untuk mengambil kemunculan gambar tertentu, gunakan ekspresi filter ini:

kind="NOTE_KIND" AND resourceUrl="RESOURCE_URL"

Dengan:

  • NOTE_KIND adalah jenis catatan.
    • Misalnya, gunakan jenis DISCOVERY untuk mencantumkan kemunculan penemuan. Kemunculan penemuan dibuat untuk image saat pertama kali dikirim ke Artifact Registry.
    • Untuk mencantumkan kemunculan kerentanan, gunakan jenis VULNERABILITY.
  • RESOURCE_URL adalah URL lengkap gambar https://HOSTNAME/PROJECT_ID/IMAGE_ID@sha256:HASH

Ekspresi filter untuk mengambil kemunculan jenis tertentu di banyak gambar adalah:

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

Dengan:

  • RESOURCE_URL_PREFIX adalah awalan URL untuk beberapa gambar
    • Untuk mencantumkan semua versi gambar: https://HOSTNAME/PROJECT_ID/IMAGE_ID@
    • Untuk mencantumkan semua gambar dalam project: https://HOSTNAME/PROJECT_ID/

Melihat gambar yang terkait dengan catatan tertentu

Anda dapat mengambil daftar resource yang terkait dengan ID catatan tertentu. Misalnya, Anda dapat mencantumkan gambar dengan kerentanan CVE tertentu.

Untuk mencantumkan semua gambar dalam project yang terkait dengan catatan tertentu, gunakan ekspresi filter berikut:

noteProjectId="PROVIDER_PROJECT_ID" AND noteId="NOTE_ID"

Untuk memeriksa gambar tertentu untuk catatan tertentu, gunakan ekspresi filter berikut:

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

Dengan:

  • PROVIDER_PROJECT_ID adalah ID project penyedia. Misalnya, goog-vulnz menyediakan analisis kerentanan default.
  • NOTE_ID adalah ID catatan. Catatan terkait keamanan sering kali diformat sebagai CVE-2019-12345.
  • RESOURCE_URL adalah URL lengkap gambar https://HOSTNAME/PROJECT_ID/IMAGE_ID@sha256:HASH

Misalnya, untuk memeriksa semua gambar yang memiliki kemunculan CVE-2017-16231 seperti yang dianalisis oleh Google, gunakan ekspresi filter berikut:

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

Langkah berikutnya