검색

3.18. Buildah를 사용하여 컨테이너 이미지 권한이 없는 빌드

download PDF

컨테이너에서 Pipeline을 root 사용자로 실행하면 컨테이너 프로세스 및 호스트를 잠재적으로 악의적인 리소스에 노출할 수 있습니다. 워크로드를 컨테이너에서 루트가 아닌 특정 사용자로 실행하여 이러한 유형의 노출을 줄일 수 있습니다. Buildah를 사용하여 컨테이너 이미지의 권한이 없는 보안 빌드의 경우 다음 단계를 수행할 수 있습니다.

  • SA(사용자 정의 서비스 계정) 및 SCC(보안 컨텍스트 제약 조건)를 정의합니다.
  • ID 1000 으로 빌드 사용자를 사용하도록 Buildah를 구성합니다.
  • 사용자 정의 구성 맵을 사용하여 작업 실행을 시작하거나 파이프라인 실행과 통합합니다.

3.18.1. 사용자 정의 서비스 계정 및 보안 컨텍스트 제약 조건 구성

기본 파이프라인 SA를 사용하면 네임스페이스 범위 외부에서 사용자 ID를 사용할 수 있습니다. 기본 SA에 대한 종속성을 줄이기 위해 사용자 ID가 1000빌드 사용자에 대해 필요한 클러스터 역할 및 역할 바인딩을 사용하여 사용자 정의 SA 및 SCC를 정의할 수 있습니다.

절차

  • 필요한 클러스터 역할 및 역할 바인딩을 사용하여 사용자 지정 SA 및 SCC를 만듭니다.

    예: ID 1000을 사용하는 사용자 정의 SA 및 SCC

    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: pipelines-sa-userid-1000 1
    ---
    kind: SecurityContextConstraints
    metadata:
      annotations:
      name: pipelines-scc-userid-1000 2
    allowHostDirVolumePlugin: false
    allowHostIPC: false
    allowHostNetwork: false
    allowHostPID: false
    allowHostPorts: false
    allowPrivilegeEscalation: false
    allowPrivilegedContainer: false
    allowedCapabilities: null
    apiVersion: security.openshift.io/v1
    defaultAddCapabilities: null
    fsGroup:
      type: MustRunAs
    groups:
    - system:cluster-admins
    priority: 10
    readOnlyRootFilesystem: false
    requiredDropCapabilities:
    - MKNOD
    runAsUser: 3
      type: MustRunAs
      uid: 1000
    seLinuxContext:
      type: MustRunAs
    supplementalGroups:
      type: RunAsAny
    users: []
    volumes:
    - configMap
    - downwardAPI
    - emptyDir
    - persistentVolumeClaim
    - projected
    - secret
    ---
    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRole
    metadata:
      name: pipelines-scc-userid-1000-clusterrole 4
    rules:
    - apiGroups:
      - security.openshift.io
      resourceNames:
      - pipelines-scc-userid-1000
      resources:
      - securitycontextconstraints
      verbs:
      - use
    ---
    apiVersion: rbac.authorization.k8s.io/v1
    kind: RoleBinding
    metadata:
      name: pipelines-scc-userid-1000-rolebinding 5
    roleRef:
      apiGroup: rbac.authorization.k8s.io
      kind: ClusterRole
      name: pipelines-scc-userid-1000-clusterrole
    subjects:
    - kind: ServiceAccount
      name: pipelines-sa-userid-1000

1
사용자 정의 SA를 정의합니다.
2
수정된 runAsUser 필드를 사용하여 제한된 권한을 기반으로 생성된 사용자 정의 SCC를 정의합니다.
3
사용자 지정 SA를 통해 사용자 정의 SCC와 연결된 모든 Pod를 제한하여 사용자 ID 1000 으로 실행합니다.
4
사용자 지정 SCC를 사용하는 클러스터 역할을 정의합니다.
5
사용자 지정 SCC를 사용하는 클러스터 역할을 사용자 지정 SA에 바인딩합니다.

3.18.2. 빌드 사용자를 사용하도록 Buildah 구성

사용자 ID 1000 으로 빌드 사용자를 사용하도록 Buildah 작업을 정의할 수 있습니다.

절차

  1. buildah 클러스터 작업의 사본을 일반 작업으로 생성합니다.

    $ tkn task create --from=buildah
  2. 복사한 buildah 작업을 편집합니다.

    $ oc edit task buildah

    예: 빌드 사용자가 포함된 Modified Buildah 작업

    apiVersion: tekton.dev/v1beta1
    kind: Task
    metadata:
      name: buildah-as-user
    spec:
      description: >-
        Buildah task builds source into a container image and
        then pushes it to a container registry.
        Buildah Task builds source into a container image using Project Atomic's
        Buildah build tool.It uses Buildah's support for building from Dockerfiles,
        using its buildah bud command.This command executes the directives in the
        Dockerfile to assemble a container image, then pushes that image to a
        container registry.
      params:
      - name: IMAGE
        description: Reference of the image buildah will produce.
      - name: BUILDER_IMAGE
        description: The location of the buildah builder image.
        default: registry.redhat.io/rhel8/buildah@sha256:99cae35f40c7ec050fed3765b2b27e0b8bbea2aa2da7c16408e2ca13c60ff8ee
      - name: STORAGE_DRIVER
        description: Set buildah storage driver
        default: vfs
      - name: DOCKERFILE
        description: Path to the Dockerfile to build.
        default: ./Dockerfile
      - name: CONTEXT
        description: Path to the directory to use as context.
        default: .
      - name: TLSVERIFY
        description: Verify the TLS on the registry endpoint (for push/pull to a non-TLS registry)
        default: "true"
      - name: FORMAT
        description: The format of the built container, oci or docker
        default: "oci"
      - name: BUILD_EXTRA_ARGS
        description: Extra parameters passed for the build command when building images.
        default: ""
      - description: Extra parameters passed for the push command when pushing images.
        name: PUSH_EXTRA_ARGS
        type: string
        default: ""
      - description: Skip pushing the built image
        name: SKIP_PUSH
        type: string
        default: "false"
      results:
      - description: Digest of the image just built.
        name: IMAGE_DIGEST
        type: string
      workspaces:
      - name: source
      steps:
      - name: build
        securityContext:
          runAsUser: 1000 1
        image: $(params.BUILDER_IMAGE)
        workingDir: $(workspaces.source.path)
        script: |
          echo "Running as USER ID `id`" 2
          buildah --storage-driver=$(params.STORAGE_DRIVER) bud \
            $(params.BUILD_EXTRA_ARGS) --format=$(params.FORMAT) \
            --tls-verify=$(params.TLSVERIFY) --no-cache \
            -f $(params.DOCKERFILE) -t $(params.IMAGE) $(params.CONTEXT)
          [[ "$(params.SKIP_PUSH)" == "true" ]] && echo "Push skipped" && exit 0
          buildah --storage-driver=$(params.STORAGE_DRIVER) push \
            $(params.PUSH_EXTRA_ARGS) --tls-verify=$(params.TLSVERIFY) \
            --digestfile $(workspaces.source.path)/image-digest $(params.IMAGE) \
            docker://$(params.IMAGE)
          cat $(workspaces.source.path)/image-digest | tee /tekton/results/IMAGE_DIGEST
        volumeMounts:
        - name: varlibcontainers
          mountPath: /home/build/.local/share/containers
        volumeMounts:
        - name: varlibcontainers
          mountPath: /home/build/.local/share/containers
      volumes:
      - name: varlibcontainers
        emptyDir: {}

    1
    Buildah 이미지의 빌드 사용자에 해당하는 사용자 ID 1000 으로 명시적으로 컨테이너를 실행합니다.
    2
    사용자 ID를 표시하여 프로세스가 사용자 ID 1000 으로 실행 중인지 확인합니다.

3.18.3. 사용자 정의 구성 맵 또는 파이프라인 실행을 사용하여 작업 실행 시작

사용자 정의 Buildah 클러스터 작업을 정의한 후 사용자 ID가 1000 인 빌드 사용자로 이미지를 빌드하는 TaskRun 오브젝트를 생성할 수 있습니다. 또한 TaskRun 오브젝트를 PipelineRun 오브젝트의 일부로 통합할 수 있습니다.

절차

  1. 사용자 정의 ConfigMapDockerfile 오브젝트를 사용하여 TaskRun 오브젝트를 생성합니다.

    예: 사용자 ID 1000으로 Buildah를 실행하는 작업 실행

    apiVersion: v1
    data:
      Dockerfile: |
        ARG BASE_IMG=registry.access.redhat.com/ubi8/ubi
        FROM $BASE_IMG AS buildah-runner
        RUN dnf -y update && \
            dnf -y install git && \
            dnf clean all
        CMD git
    kind: ConfigMap
    metadata:
      name: dockerfile 1
    ---
    apiVersion: tekton.dev/v1beta1
    kind: TaskRun
    metadata:
      name: buildah-as-user-1000
    spec:
      serviceAccountName: pipelines-sa-userid-1000
      params:
      - name: IMAGE
        value: image-registry.openshift-image-registry.svc:5000/test/buildahuser
      taskRef:
        kind: Task
        name: buildah-as-user
      workspaces:
      - configMap:
          name: dockerfile 2
        name: source

    1
    Dockerfile을 사용하여 일부 소스를 가져오는 이전 작업 없이 작업 실행에 중점을 두므로 구성 맵을 사용합니다.
    2
    구성 맵을 buildah-as-user 작업의 소스 작업 공간으로 마운트합니다.
  2. (선택 사항) 파이프라인 및 해당 파이프라인 실행을 생성합니다.

    예: 파이프라인 및 해당 파이프라인 실행

    apiVersion: tekton.dev/v1beta1
    kind: Pipeline
    metadata:
      name: pipeline-buildah-as-user-1000
    spec:
      params:
      - name: IMAGE
      - name: URL
      workspaces:
      - name: shared-workspace
      - name: sslcertdir
        optional: true
      tasks:
      - name: fetch-repository 1
        taskRef:
          name: git-clone
          kind: ClusterTask
        workspaces:
        - name: output
          workspace: shared-workspace
        params:
        - name: url
          value: $(params.URL)
        - name: subdirectory
          value: ""
        - name: deleteExisting
          value: "true"
      - name: buildah
        taskRef:
          name: buildah-as-user 2
        runAfter:
        - fetch-repository
        workspaces:
        - name: source
          workspace: shared-workspace
        - name: sslcertdir
          workspace: sslcertdir
        params:
        - name: IMAGE
          value: $(params.IMAGE)
    ---
    apiVersion: tekton.dev/v1beta1
    kind: PipelineRun
    metadata:
      name: pipelinerun-buildah-as-user-1000
    spec:
      serviceAccountName: pipelines-sa-userid-1000
      params:
      - name: URL
        value: https://github.com/openshift/pipelines-vote-api
      - name: IMAGE
        value: image-registry.openshift-image-registry.svc:5000/test/buildahuser
      taskRef:
        kind: Pipeline
        name: pipeline-buildah-as-user-1000
      workspaces:
      - name: shared-workspace 3
        volumeClaimTemplate:
          spec:
            accessModes:
              - ReadWriteOnce
            resources:
              requests:
                storage: 100Mi

    1
    git-clone 클러스터 작업을 사용하여 Dockerfile이 포함된 소스를 가져와서 수정된 Buildah 작업을 사용하여 빌드합니다.
    2
    수정된 Buildah 작업을 참조하십시오.
    3
    컨트롤러에서 자동으로 생성한 PVC(영구 볼륨 클레임)를 사용하여 git-clone 작업과 수정된 Buildah 작업 간 데이터를 공유합니다.
  3. 작업 실행 또는 파이프라인 실행을 시작합니다.

3.18.4. 권한이 없는 빌드의 제한

권한이 없는 빌드의 프로세스는 대부분의 Dockerfile 오브젝트에서 작동합니다. 그러나 몇 가지 알려진 제한으로 인해 빌드가 실패할 수 있습니다.

  • 필요한 권한 문제가 없기 때문에 --mount=type=cache 옵션을 사용하지 못할 수 있습니다. 자세한 내용은 이 문서 를 참조하십시오.
  • 마운트 리소스에는 사용자 정의 SCC에서 제공하지 않는 추가 기능이 필요하므로 --mount=type=secret 옵션을 사용할 수 없습니다.
Red Hat logoGithubRedditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 문서 정보

Red Hat을 사용하는 고객은 신뢰할 수 있는 콘텐츠가 포함된 제품과 서비스를 통해 혁신하고 목표를 달성할 수 있습니다.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

© 2024 Red Hat, Inc.