自動掃描 OS 套件

本文將說明如何啟用 Container Scanning API、將映像檔推送至 Artifact Registry,以及查看映像檔中發現的安全漏洞清單。

Artifact Analysis 可針對 Artifact Registry 中的容器映像檔,提供安全漏洞資訊。中繼資料會以附註的型態儲存。每當某個映像檔有相關聯的註記時,系統便會建立相對應的例項。詳情請參閱總覽定價文件。

事前準備

  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. 在 Artifact Registry 中建立 Docker 存放區,並將容器映像檔推送至該存放區。如果您不熟悉 Artifact Registry,請參閱 Docker 快速入門導覽課程

啟用此 API 也會啟用 Artifact Registry 中的語言套件掃描功能。請參閱支援的套件類型

查看映像檔安全漏洞

將新的映像檔上傳至 Artifact Registry 時,Artifact Analysis 會掃描這些映像檔。這項掃描作業會擷取容器中的系統套件相關資訊。

您可以使用 Google Cloud 控制台、Google Cloud CLI 或 Container Analysis API,查看登錄檔中映像檔發生的安全漏洞。如果映像檔有安全漏洞,您就可以取得詳細資料。

Artifact Analysis 只會更新過去 30 天內推送或提取的映像檔中繼資料。30 天後,中繼資料將不再更新,結果也會過時。此外,Artifact Analysis 會封存過時逾 90 天的中繼資料,且這些中繼資料不會顯示在 Google Cloud 控制台、gcloud 或 API 中。如要重新掃描中繼資料已過時或已封存的映像檔,請提取該映像檔。 重新整理中繼資料最多可能需要 24 小時才能完成。

在 Google Cloud 控制台中查看發生次數

如要查看映像檔中的安全漏洞:

  1. 取得存放區清單。

    開啟「Repositories」(存放區) 頁面

  2. 在存放區清單中,按一下存放區。

  3. 在圖片清單中,按一下圖片名稱。

    每個映像檔摘要的安全漏洞總數會顯示在「Vulnerabilities」(安全漏洞) 資料欄中。

    掃描後發現安全漏洞的映像檔

  4. 如要查看映像檔的安全漏洞清單,請按一下「Vulnerabilities」(安全漏洞) 資料欄中的連結。

    「掃描結果」部分會顯示掃描的套件類型摘要、安全漏洞總數、有修正檔的安全漏洞、沒有修正檔的安全漏洞,以及有效嚴重程度。

    「掃描結果」頁面會列出安全漏洞、修正方式和有效嚴重程度

    安全漏洞表格會列出每個安全漏洞的常見安全漏洞與資料外洩風險 (CVE) 名稱、實際嚴重程度、常見安全漏洞評分系統 (CVSS) 分數、修正 (如有)、內含安全漏洞的套件名稱,以及套件類型。您可以篩選及排序這些檔案,依副檔名檢查特定檔案、目錄或檔案類型。 Google Cloud 主控台會在表格中顯示最多 1200 個網頁的安全性弱點。

  5. 如要查看特定 CVE 的詳細資料,請按一下 CVE 名稱。

  6. 如要查看安全漏洞發生詳細資料,例如版本號碼和受影響的位置,請在安全漏洞名稱的資料列中,按一下「查看」或「查看已修正」。如果安全漏洞尚未修正,連結文字會顯示「查看」;如果安全漏洞已修正,連結文字則會顯示「查看已修正」

使用 gcloud 查看發生次數

如要查看 Artifact Registry 中映像檔的例項,請執行 gcloud artifacts docker images list 指令:

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

其中:

  • LOCATION 是存放區的區域或多區域位置
  • PROJECT_ID 是您的 Google Cloud 控制台專案 ID
  • REPOSITORY 是儲存映像檔的存放區名稱。
  • IMAGE_ID 是存放區中的映像檔名稱。 您無法使用此指令指定圖片標記。

根據預設,這項指令會傳回最近 10 個映像檔。如要顯示不同數量的圖片,請使用 --show-occurrences-from 旗標。舉例來說,下列指令會傳回最近 25 張圖片:

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

輸出內容大致如下:

圖片輸出範例

  {
      "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"
        }
      }
    }
  

查看映像檔標記的安全漏洞

如要查看映像檔標記的安全漏洞,請輸入下列其中一個指令:

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

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

其中:

  • LOCATION 是存放區的區域或多區域位置
  • PROJECT_ID 是您的 Google Cloud 控制台專案 ID
  • REPOSITORY 是儲存映像檔的存放區名稱。
  • IMAGE_ID 是存放區中的映像檔名稱。
  • TAG 是您要取得相關資訊的映像檔標記。
  • HASH 是映像檔摘要。

Artifact Analysis 會傳回結果,包括 packageType

篩選安全漏洞例項

如要篩選安全漏洞例項,請使用 --occurrence-filter 參數:

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

其中:

  • LOCATION 是存放區的區域或多區域位置
  • PROJECT_ID 是您的 Google Cloud 控制台專案 ID
  • REPOSITORY 是儲存映像檔的存放區名稱。
  • IMAGE_ID 是存放區中的映像檔名稱。
  • FILTER_EXPRESSION 是採用篩選安全漏洞例項一文所述格式的篩選器運算式範例。

查看特定層的安全漏洞

您可以使用 layerDetails 欄位,判斷哪個特定層引進了有安全漏洞的套件,並查看該層的其他資訊。舉例來說,請參考以下圖片的 layerDetails 輸出內容:

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

輸出內容顯示容器映像檔中的層索引為 0,層雜湊為 sha256:123。用於建構這個層的 Docker 建構指令是 FROM golang:example_sha256,這個層也會出現在 library/golang 基本映像檔中。

使用 API 或程式碼查看發生次數

如要查看映像檔的例項,請以網址指定映像檔,格式如下:

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

API

使用 cURL

如何取得專案的例項清單:

 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

如何取得專案的安全漏洞匯總資料:

 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

如要取得特定例項的詳細資料:

 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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Java API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Go API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Node.js API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Ruby API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

# 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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Python API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

在 Cloud Build 中查看發生項目

如果您使用 Cloud Build,也可以在 Google Cloud 控制台的「安全性洞察」側邊面板中查看映像檔安全漏洞。

「安全性深入分析」側邊面板會顯示儲存在 Artifact Registry 中的構件建構安全性資訊總覽。如要進一步瞭解側邊面板,以及如何使用 Cloud Build 協助保護軟體供應鏈,請參閱「查看建構作業安全性洞察資訊」。

篩選例項

您可以在 gcloud 指令和 Artifact Analysis API 中使用篩選字串,在查看之前先篩選例項。下列各節說明支援的搜尋篩選器。

查看掃描結果例項

您最初將映像檔推送至 Artifact Registry 時,Artifact Registry 會建立掃描結果例項,其中包含容器映像檔的初始掃描相關資訊。

如要擷取映像檔的掃描結果例項,請使用下列篩選器運算式:

kind="DISCOVERY" AND resourceUrl="RESOURCE_URL"

其中 RESOURCE_URL 的格式如下:

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

gcloud

查看映像檔的掃描結果例項:

在本例中,運算式不會直接用於指令,但會以引數形式傳遞相同資訊:

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

如要擷取掃描結果例項,篩選器運算式必須使用網址編碼,並嵌入 GET 要求中,如下所示:

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

詳情請參閱 projects.occurrences.get API 端點。

Java

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Java API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Go API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Node.js API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Ruby API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

# 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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Python API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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)

查看安全漏洞例項

如要查看特定映像檔的安全漏洞例項,請使用篩選器運算式建立查詢:

kind="VULNERABILITY" AND resourceUrl="RESOURCE_URL"

其中 RESOURCE_URL 的格式如下:

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

gcloud

在本例中,運算式不會直接用於指令,但會以引數形式傳遞相同資訊:

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

資源網址必須經過網址編碼,並嵌入 GET 要求中,如下所示:

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

詳情請參閱 projects.occurrences.get API 端點。

Java

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Java API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Go API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Node.js API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Ruby API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

# 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

如要瞭解如何安裝及使用 Artifact Analysis 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Artifact Analysis Python API 參考說明文件

如要向 Artifact Analysis 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

查看特定類型的例項

在先前的兩個範例中,篩選器運算式之間的唯一差異是 kind 的值,這個值會識別事件類型。使用此欄位可將例項清單限制為一種特定類型,如安全漏洞或部署。

如要擷取特定映像檔的例項,請使用下列篩選器運算式:

kind="NOTE_KIND" AND resourceUrl="RESOURCE_URL"

其中:

  • NOTE_KIND 是註記的種類
    • 舉例來說,您可以利用 DISCOVERY 種類列出掃描結果例項。當您最初將映像檔推送至 Artifact Registry 時,系統即會建立掃描結果例項。
    • 如要列出安全漏洞例項,請使用 VULNERABILITY 種類。
  • RESOURCE_URL 是圖片的完整網址 https://HOSTNAME/PROJECT_ID/IMAGE_ID@sha256:HASH

針對多個映像檔擷取特定種類例項的篩選器,運算式如下:

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

其中:

  • RESOURCE_URL_PREFIX 是部分映像檔的網址前置字串
    • 如要針對某個映像檔的所有版本列出網址前置字串:https://HOSTNAME/PROJECT_ID/IMAGE_ID@
    • 如要針對專案中所有映像檔列出網址前置字串:https://HOSTNAME/PROJECT_ID/

查看與特定記事相關聯的圖片

您可以擷取與特定註記 ID 相關聯的資源清單。例如,您可以使用特定 CVE 安全漏洞來列出映像檔。

如要列出專案中與特定註記相關聯的的所有映像檔,請使用下列篩選器運算式:

noteProjectId="PROVIDER_PROJECT_ID" AND noteId="NOTE_ID"

如要查看特定註記的特定映像檔,請使用下列篩選器運算式:

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

其中:

  • PROVIDER_PROJECT_ID 是供應商專案的 ID。例如,goog-vulnz 會提供預設的安全漏洞分析。
  • NOTE_ID 是註記的 ID。安全性相關註記的格式通常為 CVE-2019-12345
  • RESOURCE_URL 是圖片的完整網址 https://HOSTNAME/PROJECT_ID/IMAGE_ID@sha256:HASH

例如,若要查看經 Google 分析後具有 CVE-2017-16231 例項的所有映像檔,請使用下列篩選器運算式:

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

後續步驟