自動掃描 OS 套件

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

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

啟用此 API 也會在 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. 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. 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. Make sure 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 快速入門
  15. 查看映像檔安全漏洞

    將新的映像檔上傳至 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. 取得存放區清單。

      開啟「存放區」頁面

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

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

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

      發生安全漏洞的映像檔螢幕擷取畫面

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

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

      掃描結果部分的螢幕截圖,其中顯示安全漏洞、修正項目和有效嚴重性

      安全漏洞表格會列出每個發現的安全漏洞的「常見安全漏洞與資料外洩風險」(CVE) 名稱、有效嚴重性、常見安全漏洞評分系統 (CVSS) 分數、修正程式 (如有)、內含安全漏洞的套件名稱和套件類型。

      您可以篩選及排序這些檔案,依據檔案副檔名檢查特定檔案、目錄或檔案類型。

      Google Cloud 控制台會在這個表格中顯示最多 1,200 個安全漏洞。如果映像檔有超過 1, 200 個安全漏洞,您必須使用 gcloud 或 API 查看完整清單。

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

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

    使用 gcloud 查看事件

    如何查看圖片的例項:

    Artifact Registry

    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
    

    Container Registry

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

    其中:

    • HOSTNAME 是多地區主機名稱:
      • gcr.io
      • asia.gcr.io
      • eu.gcr.io
      • us.gcr.io
    • PROJECT_ID 是包含圖片的專案 ID。
    • IMAGE_ID 是您要查看安全漏洞的映像檔 ID。您無法使用此指令指定圖片標記。

    根據預設,指令會傳回最近的 10 張圖片。如要顯示不同數量的圖片,請使用 --show-occurrences-from 標記。例如,這個指令會傳回最近的 25 張圖片。

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

    如何查看圖片代碼或圖層的安全漏洞:

    Artifact Registry

    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 是圖片摘要。

    Container Registry

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

    其中:

    • HOSTNAME 是多地區主機名稱:
      • gcr.io
      • asia.gcr.io
      • eu.gcr.io
      • us.gcr.io
    • PROJECT_ID 是包含圖片的專案 ID。
    • IMAGE_ID 是您要查看安全漏洞的映像檔 ID。
    • HASH 是圖片摘要。

    如何篩選安全漏洞的例項:

    Artifact Registry

    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 是採用篩選安全漏洞例項一文所述格式的篩選器運算式範例。

    Container Registry

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

    其中:

    • HOSTNAME 是多地區主機名稱:
      • gcr.io
      • asia.gcr.io
      • eu.gcr.io
      • us.gcr.io
    • PROJECT_ID 是包含圖片的專案 ID。
    • IMAGE_ID 是您要查看安全漏洞例項的映像檔 ID。
    • FILTER_EXPRESSION 是採用篩選安全漏洞例項一文所述格式的篩選器運算式範例。

    使用 API 或程式碼查看事件

    如要查看某個映像檔的例項,請使用適當的程式碼片段。程式碼片段會指定 Container Registry 中映像檔的網址。如果您使用的是 Artifact Registry,請使用以下格式指定圖片的網址:

    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 用戶端程式庫」。詳情請參閱 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 用戶端程式庫」。詳情請參閱 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 用戶端程式庫」。詳情請參閱 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 用戶端程式庫」。詳情請參閱 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 用戶端程式庫」。詳情請參閱 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 主控台的「Security insights」側邊面板中查看映像檔安全漏洞。

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

    篩選事件

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

    查看掃描結果例項

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

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

    kind="DISCOVERY" AND resourceUrl="RESOURCE_URL"

    以下程式碼片段示範如何使用篩選器運算式查看圖片的掃描結果例項。程式碼片段會指定 Container Registry 中映像檔的網址。如果您使用的是 Artifact Registry,請使用以下格式指定圖片的網址:

    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
    

    Container Registry:

    gcloud beta container images list-tags \
    --occurrence-filter='kind="DISCOVERY"' --format=json HOSTNAME/PROJECT_ID/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 用戶端程式庫」。詳情請參閱 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 用戶端程式庫」。詳情請參閱 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 用戶端程式庫」。詳情請參閱 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 用戶端程式庫」。詳情請參閱 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 用戶端程式庫」。詳情請參閱 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"

    下列程式碼片段示範如何擷取映像檔的安全漏洞例項清單。程式碼片段會指定 Container Registry 中映像檔的網址。如果您使用的是 Artifact Registry,請使用以下格式指定圖片的網址:

    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
    

    Container Registry

    gcloud beta container images list-tags \
    --occurrence-filter='kind="VULNERABILITY"' --format=json HOSTNAME/PROJECT_ID/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 用戶端程式庫」。詳情請參閱 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 用戶端程式庫」。詳情請參閱 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 用戶端程式庫」。詳情請參閱 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 用戶端程式庫」。詳情請參閱 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 用戶端程式庫」。詳情請參閱 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 種類列出掃描結果例項。當您最初將映像檔推送至 Container 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"

    後續步驟