Cloud Build 파이프라인에서 주문형 스캔 사용

Cloud Build 파이프라인의 일부로 On-Demand Scanning을 사용하면 컨테이너 이미지에 미리 정의된 수준과 일치하는 심각도의 취약점이 있는 경우 빌드를 차단할 수 있습니다.

이 튜토리얼에서는 Cloud Build를 사용하여 소스 코드에서 컨테이너 이미지를 빌드하고, 취약점을 스캔하고, 취약점의 심각도 수준을 확인하고, 특정 심각도 수준의 취약점이 없는 경우 이미지를 Artifact Registry에 푸시하는 방법을 보여줍니다.

이 튜토리얼에서는 새 Google Cloud 프로젝트를 만들고 격리된 환경에서 단계를 완료하는 것이 좋습니다.

목표

  • Cloud Build로 이미지를 빌드합니다.
  • On-Demand Scanning으로 빌드된 이미지를 스캔합니다.
  • 허용 가능한 취약점 수준을 평가합니다.
  • Artifact Registry에 이미지를 저장합니다.

비용

이 문서에서는 비용이 청구될 수 있는 구성요소를 사용합니다 Google Cloud.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용하세요.

Google Cloud 신규 사용자는 무료 체험판을 사용할 수 있습니다.

이 문서에 설명된 태스크를 완료했으면 만든 리소스를 삭제하여 청구가 계속되는 것을 방지할 수 있습니다. 자세한 내용은 삭제를 참조하세요.

시작하기 전에

  1. 계정에 로그인합니다. Google Cloud 를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. Google Cloud신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

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

  4. Enable the On-Demand Scanning, Cloud Build, and Artifact Registry APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. Google Cloud CLI를 설치합니다.

  6. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  7. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

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

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

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

  10. Enable the On-Demand Scanning, Cloud Build, and Artifact Registry APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  11. Google Cloud CLI를 설치합니다.

  12. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  13. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init

필요한 역할

Cloud Build에서 사용하는 서비스 계정에는 다음 역할이 필요합니다.

기본 Cloud Build 서비스 계정에는 동일한 프로젝트의 Artifact Registry 저장소에 필요한 권한이 있습니다. 저장소가 Cloud Build에 사용하는 동일한 프로젝트에 있는 경우 On-Demand Scanning 관리자 역할만 부여하면 됩니다.

Cloud Build에 사용자 제공 서비스 계정을 사용하는 경우 두 역할을 모두 부여해야 합니다.

소스 파일 준비

이 튜토리얼에서는 Dockerfile에서 이미지를 빌드합니다. Dockerfile은 Docker로 이미지를 빌드하기 위한 안내가 포함된 소스 파일입니다.

  1. 터미널을 열고 ods-tutorial이라는 새 디렉터리를 만든 후 디렉터리로 이동합니다.

    mkdir ods-tutorial && cd ods-tutorial
    
  2. 다음 콘텐츠로 Dockerfile이라는 파일을 만듭니다.

    # Debian10 image
    FROM gcr.io/google-appengine/debian10:latest
    
    # Ensures that the built image is always unique
    RUN apt-get update && apt-get -y install uuid-runtime && uuidgen > /IAMUNIQUE
    

Artifact Registry 저장소 만들기

  1. API를 사용 설정한 동일한 프로젝트로 프로젝트 ID를 설정합니다.

    gcloud config set project PROJECT_ID
    
  2. us-central1 위치에 ods-build-repo라는 Docker 저장소를 만듭니다.

    gcloud artifacts repositories create ods-build-repo --repository-format=docker \
    --location=us-central1 --description="Repository for scan and build"
    
  3. 저장소가 만들어졌는지 확인합니다.

    gcloud artifacts repositories list
    

빌드 및 스캔

이 섹션에서는 빌드 구성 파일을 사용하여 빌드 파이프라인을 실행합니다. 빌드 구성 파일은 사양에 따라 여러 작업을 수행하는 방법을 Cloud Build에 안내합니다.

  1. ods-tutorial/ 폴더에서 다음 콘텐츠로 cloudbuild.yaml 파일을 만듭니다.

    steps:
       - id: build
         name: gcr.io/cloud-builders/docker
         entrypoint: /bin/bash
         args:
         - -c
         - |
           docker build -t us-central1-docker.pkg.dev/$_PROJECT_ID/ods-build-repo/ods-test:latest -f ./Dockerfile . &&
           docker image inspect us-central1-docker.pkg.dev/$_PROJECT_ID/ods-build-repo/ods-test:latest --format \
           '{{index .RepoTags 0}}@{{.Id}}' > /workspace/image-digest.txt &&
           cat image-digest.txt
       - id: scan
         name: gcr.io/google.com/cloudsdktool/cloud-sdk
         entrypoint: /bin/bash
         args:
         - -c
         - |
           gcloud artifacts docker images scan us-central1-docker.pkg.dev/$_PROJECT_ID/ods-build-repo/ods-test:latest \
           --format='value(response.scan)' > /workspace/scan_id.txt
       - id: severity check
         name: gcr.io/google.com/cloudsdktool/cloud-sdk
         entrypoint: /bin/bash
         args:
         - -c
         - |
           gcloud artifacts docker images list-vulnerabilities $(cat /workspace/scan_id.txt) \
           --format='value(vulnerability.effectiveSeverity)' | if grep -Exq $_SEVERITY; \
           then echo 'Failed vulnerability check' && exit 1; else exit 0; fi
       - id: push
         name: gcr.io/cloud-builders/docker
         entrypoint: /bin/bash
         args:
         - -c
         - |
           docker push us-central1-docker.pkg.dev/$_PROJECT_ID/ods-build-repo/ods-test:latest
    images: ['us-central1-docker.pkg.dev/$_PROJECT_ID/ods-build-repo/ods-test:latest']
    
    

    이 파일에는 Artifact Registry에서 이전에 만든 위치와 저장소가 포함되어 있습니다. 다른 값을 사용하려면 cloudbuild.yaml 파일을 적절히 수정합니다. PROJECT_IDSEVERITY 값은 빌드 명령어의 스크립트에 전달됩니다.

  2. 차단할 취약점 SEVERITY 수준을 지정하고 빌드를 시작합니다.

    SEVERITY에 다음 값을 사용할 수 있습니다.

    • CRITICAL
    • HIGH
    • MEDIUM
    • LOW

    정규 표현식을 사용하여 여러 심각도를 지정할 수 있습니다.

    다음 예에서는 CRITICALHIGH 심각도 값을 모두 지정합니다. 이렇게 하면 Cloud Build가 HIGH 심각도 수준 이상으로 분류된 취약점을 확인하도록 안내합니다.

    gcloud builds submit --substitutions=_PROJECT_ID=PROJECT_ID,_SEVERITY='"CRITICAL|HIGH"' \
    --config cloudbuild.yaml
    

    WHERE

    • PROJECT_ID는 프로젝트 ID입니다.
    • SEVERITY를 사용하면 차단할 심각도 수준을 설정할 수 있습니다. On-Demand Scanning에서 지정된 심각도 수준과 일치하는 취약점을 발견하면 빌드가 실패합니다.

결과 이해하기

SEVERITY 값을 CRITICAL|HIGH로 설정하면 On-Demand Scanning에서 취약점을 스캔한 후 HIGH 수준과 더 심각한 CRITICAL 수준의 취약점이 있는지 확인합니다. 이미지에서 일치하는 취약점이 발견되지 않으면 빌드가 성공하고 Cloud Build가 이미지를 Artifact Registry에 푸시합니다.

출력은 다음과 비슷합니다.

DONE
--------------------------------------------------------------------------------------------------------------------------------------------

ID                                    CREATE_TIME                DURATION  SOURCE                                                                                         IMAGES                                                                        STATUS
abb3ce73-6ae8-41d1-9080-7d74a7ecd7bc  2021-03-15T06:50:32+00:00  1M48S     gs://ods-tests_cloudbuild/source/1615791031.906807-a648d10faf4a46d695c163186a6208d5.tgz  us-central1-docker.pkg.dev/ods-tests/ods-build-repo/ods-test (+1 more)  SUCCESS

On-Demand Scanning에서 이미지에 HIGH 또는 CRITICAL 취약점을 발견하면 scan 빌드 단계가 실패하고 후속 빌드 단계가 시작되지 않으며 Cloud Build가 이미지를 Artifact Registry에 푸시하지 않습니다.

출력은 다음과 비슷합니다.

Step #2 - "severity check": Failed vulnerability check
Finished Step #2 - "severity check"
ERROR
ERROR: build step 2 "gcr.io/cloud-builders/gcloud" failed: step exited with non-zero status: 1

이 튜토리얼에서는 샘플 소스 코드가 공개적으로 사용 가능한 Linux 배포판인 debian10:latest이므로 결과가 다를 수 있습니다. Linux 배포판 및 관련 취약점 데이터는 지속적으로 업데이트됩니다.

소프트웨어 공급망을 보호하는 데 도움이 되는 추가 Google Cloud 도구 및 권장사항에 대해 알아보려면 소프트웨어 공급망 보안을 참조하세요.

Linux 취약점 관리 권장사항에 대한 자세한 내용은 Linux Foundation에서 제공하는 무료 온라인 교육을 참고하세요. 보안 소프트웨어 개발을 참조하세요.

삭제

이 튜토리얼에서 사용된 리소스 비용이 Google Cloud 계정에 청구되지 않도록 하려면 리소스가 포함된 프로젝트를 삭제하거나 프로젝트를 유지하고 개별 리소스를 삭제하세요.

프로젝트 삭제

  1. 콘솔에서 리소스 관리 페이지로 이동합니다. Google Cloud

    리소스 관리로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료 를 클릭하여 프로젝트를 삭제합니다.

개별 리소스 삭제

저장소를 삭제하기 전에, 보관할 이미지를 다른 위치에서 사용할 수 있는지 확인합니다.

저장소를 삭제하려면 다음 안내를 따르세요.

콘솔

  1. 콘솔에서 저장소 페이지를 엽니다. Google Cloud

    저장소 페이지 열기

  2. 저장소 목록에서 ods-build-repo 저장소를 선택합니다.

  3. 삭제를 클릭합니다.

gcloud

ods-build-repo 저장소를 삭제하려면 다음 명령어를 실행합니다.

gcloud artifacts repositories delete ods-build-repo --location=us-central1

다음 단계