Kanji
・클라우드 엔지니어 / 프리랜서 ・1993년생 ・에히메현 출신 / 도쿄도 시부야구 거주 ・AWS 경력 5년 프로필 상세
목차
Provider.get_global_provider()
Check_Report_AWS(metadata=self.metadata(), resource=...)
pydantic.v1
current_audit_info
ModuleNotFoundError
"Check was not found"
s3://
--checks-folder
AWSService
멀티 계정 AWS 환경에서 보안 감사를 자동화하다 보면 “AWS Security Hub 표준 컨트롤에는 없는 사내 고유 보안 규칙”이나 “Security Hub에서 수동(Manual) 항목으로 분류되어 자동 점검되지 않는 CIS 벤치마크 항목”을 어떻게 정기 점검할지 고민하게 됩니다.
처음에는 AWS Config 커스텀 규칙(Config Rules + AWS Lambda)으로 구현하려 했지만, 수십 개 계정과 다중 리전에 걸쳐 Lambda 함수와 Config 평가 비용을 유지하다 보니 규칙이 늘어날수록 운영 부담과 월별 비용이 크게 증가했습니다. 그래서 제가 실무에서 채택한 방식이 오픈소스 클라우드 보안 감사 도구인 Prowler 의 커스텀 체크 기능( --checks-folder / -x )입니다. CodeBuild나 GitHub Actions에서 하루 한 번 Prowler를 실행하고, 공통 S3 버킷에 저장된 커스텀 체크를 불러와 Security Hub(ASFF)로 결과를 집약하면 월 몇 달러 이하의 비용으로 조직 고유의 보안 감사를 자동화할 수 있습니다.
-x
하지만 공식 문서( Custom Checks - Prowler Documentation )에는 기본적인 폴더 구조만 간략히 나와 있고, 무엇보다 Prowler v3에서 v4 / v5로 메이저 업데이트되면서 내부 클래스 설계( Check_Report_AWS 인자 및 Provider 초기화 방식)에 파괴적 변경(Breaking Changes) 이 발생하여 기존 v3 시절 예제 코드를 그대로 실행하면 즉시 에러가 발생합니다.
Check_Report_AWS
Provider
이 글에서는 Prowler 실제 소스 코드( prowler/lib/check/ 및 prowler/providers/aws/ ) 분석과 실제 검증 결과를 바탕으로 최신 Prowler v4 / v5(및 v3와의 차이점) 에서 커스텀 체크를 작성하는 2가지 패턴과 디버깅 시 가장 많이 겪는 함정을 정리합니다.
prowler/lib/check/
prowler/providers/aws/
▲ Prowler v4/v5 커스텀 체크 동적 로더(로컬 / S3) 및 2계통 클라이언트 실행 아키텍처
기존 Prowler v3 환경에서 작성한 커스텀 체크를 Prowler v4 / v5에서 실행할 때 가장 먼저 부딪히는 3가지 핵심 변경 사항입니다.
<= v3.x
v4.x / v5.x
Check_Report_AWS(self.metadata())
Check_Report_AWS(metadata=self.metadata(), resource=resource_obj)
resource
TypeError: missing 1 required positional argument: 'resource'
could not be converted to dict
from prowler.providers.aws.lib.audit_info.audit_info import current_audit_info
Config(current_audit_info)
from prowler.providers.common.provider import Provider
Config(Provider.get_global_provider())
audit_info
from pydantic import BaseModel
from pydantic.v1 import BaseModel
.dict()
pydantic.v1.BaseModel
점검하려는 AWS 리소스 정보가 Prowler 기본 서비스 클라이언트에 이미 수집되어 있는지에 따라 두 가지 패턴으로 나뉩니다.
custom-checks-folder/ └── account_alternative_contact_information_is_registered/ ├── __init__.py ├── account_alternative_contact_information_is_registered.py └── account_alternative_contact_information_is_registered.metadata.json
parse_checks_from_folder()
_
account
prowler/providers/aws/services/{service}/
.py
class
.metadata.json
"CheckID"
ValidationError
account_alternative_contact_information_is_registered.py
import json from prowler.lib.logger import logger from prowler.lib.check.models import Check, Check_Report_AWS from prowler.providers.aws.services.account.account_client import account_client class account_alternative_contact_information_is_registered(Check): def execute(self): desired_alternative_contact_count = account_client.audit_config.get( "desired_alternative_contact_count", 3 ) findings = [] contact_emails = set(account_client.contact_emails or []) contact_emails.discard(None) # Prowler v4/v5에서는 두 번째 인자 resource(dict 또는 BaseModel) 전달이 필수입니다 report = Check_Report_AWS(metadata=self.metadata(), resource={}) report.region = account_client.region report.resource_arn = account_client.audited_account_arn report.resource_id = account_client.audited_account if len(contact_emails) < desired_alternative_contact_count: report.status = "FAIL" else: report.status = "PASS" report.status_extended = json.dumps( { "desired_alternative_contact_count": desired_alternative_contact_count, "contact_emails_count": len(contact_emails), "contact_emails": sorted(list(contact_emails)), } ) findings.append(report) return findings
account_alternative_contact_information_is_registered.metadata.json
{ "Provider": "aws", "CheckID": "account_alternative_contact_information_is_registered", "CheckTitle": "Ensure account alternative contact information (Security, Billing, Operations) is registered", "CheckType": [ "Software and Configuration Checks/AWS Security Best Practices" ], "ServiceName": "account", "SubServiceName": "", "ResourceIdTemplate": "arn:aws:account::account-id:account", "Severity": "medium", "ResourceType": "AwsAccount", "Description": "Ensure AWS account has alternative contacts registered for Security, Billing, and Operations.", "Risk": "Without valid alternative contacts, AWS security and billing notifications may not reach the responsible operations team in time.", "RelatedUrl": "https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-update-contact-alternate.html", "Remediation": { "Code": { "CLI": "aws account put-alternate-contact --alternate-contact-type SECURITY --email-address sec@example.com --name SecurityTeam --phone-number +81-3-0000-0000 --title Security", "NativeIaC": "", "Other": "", "Terraform": "" }, "Recommendation": { "Text": "Register Security, Billing, and Operations alternate contacts via AWS Organizations or Account settings.", "Url": "https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-update-contact-alternate.html" } }, "Categories": [ "custom-checks" ], "DependsOn": [], "RelatedTo": [], "Notes": "" }
Prowler 기본 config_service.py 에 없는 describe_delivery_channels API를 호출하려면 체크 폴더 내부에 cst_config_service.py 와 cst_config_client.py 를 함께 배치합니다.
config_service.py
describe_delivery_channels
cst_config_service.py
cst_config_client.py
# cst_config_service.py from typing import Optional from pydantic.v1 import BaseModel from prowler.lib.logger import logger from prowler.lib.scan_filters.scan_filters import is_resource_filtered from prowler.providers.aws.lib.service.service import AWSService class CustomConfig(AWSService): def __init__(self, provider): super().__init__("config", provider) self.delivery_channels = [] self.__threading_call__(self._describe_delivery_channels) def _describe_delivery_channels(self, regional_client): try: channels = regional_client.describe_delivery_channels().get( "DeliveryChannels", [] ) if not channels: self.delivery_channels.append( DeliveryChannel( id=self.audited_account, arn=f"arn:{self.audited_partition}:config:{regional_client.region}:{self.audited_account}:delivery-channel/none", name=self.audited_account, region=regional_client.region, ) ) return for channel in channels: channel_name = channel.get("name", "default") if not self.audit_resources or is_resource_filtered( channel_name, self.audit_resources ): self.delivery_channels.append( DeliveryChannel( id=channel_name, arn=f"arn:{self.audited_partition}:config:{regional_client.region}:{self.audited_account}:delivery-channel/{channel_name}", name=channel_name, s3_bucket_name=channel.get("s3BucketName"), s3_key_prefix=channel.get("s3KeyPrefix"), sns_topic_arn=channel.get("snsTopicARN"), region=regional_client.region, ) ) except Exception as error: logger.error(f"{regional_client.region} -- {error}") class DeliveryChannel(BaseModel): id: str arn: str name: str s3_bucket_name: Optional[str] = None s3_key_prefix: Optional[str] = None sns_topic_arn: Optional[str] = None region: str
# cst_config_client.py from prowler.providers.common.provider import Provider from cst_config_service import CustomConfig custom_config_client = CustomConfig(Provider.get_global_provider())
# config_delivery_channel_enabled.py import os import sys from prowler.lib.check.models import Check, Check_Report_AWS sys.path.append(os.path.dirname(__file__)) from cst_config_client import custom_config_client # noqa: E402 class config_delivery_channel_enabled(Check): def execute(self): findings = [] for channel in custom_config_client.delivery_channels: report = Check_Report_AWS(metadata=self.metadata(), resource=channel) if channel.s3_bucket_name: report.status = "PASS" report.status_extended = f"AWS Config delivery channel '{channel.name}' delivers to S3 bucket '{channel.s3_bucket_name}'." else: report.status = "FAIL" report.status_extended = f"No AWS Config delivery channel is configured in region {channel.region}." findings.append(report) return findings
# 개발 중인 단일 커스텀 체크만 빠르게 실행 및 디버그 로그 저장 prowler aws \ --checks-folder ./custom-checks-folder/ \ --checks account_alternative_contact_information_is_registered \ --log-level DEBUG \ -M csv json-ocsf \ --output-directory ./output > debug.log 2>&1
Prowler의 execute_checks() 는 체크 스크립트 내부에서 발생한 ModuleNotFoundError 도 모두 잡아 "Check '<name>' was not found for the AWS provider" 로 출력합니다. 이 오류가 발생하면 아래 순서로 점검하세요.
execute_checks()
"Check '<name>' was not found for the AWS provider"
{service}_service.py
--checks-folder s3://bucket/prefix/
^s3://([^/]+)/(.*?([^/]+))/$
/
Real-time AI quant analysis of corporate earnings reports.
실전 같은 AI 음성 모의 통화와 5축 정밀 피드백. 16강 인터랙티브 강의와 스튜디오급 AI 프로필 생성 지원.
영수증 촬영 즉시 Gemini AI가 품목과 금액을 자동 인식. 모임 및 여행 경비를 손쉽게 더치페이하고 정산합니다.
점술사, 집사, 바텐더 AI 캐릭터가 직접 게임을 진행하고 대화 주제를 던져 모임을 흥미진진하게 만듭니다.
人工甘味料や添加物のNG除外と有効成分あたりの実質単価比較データベース。