CloudEngineering (AWS)/Security

AWS EventBridge을 이용한 보안감사

Halfmoon 2022. 2. 7. 22:35

액세스 키 유출로 인해 계정이 탈취된 경험을 겪은 회사 혹은 개인이 생각보다 많을 것이다. 계정을 탈취하여 과도한 스펙을 가진 EC2를 생성하여 채굴을 한다거나 정말 악의적인 목적으로 리소스를 모두 지운 뒤 금전을 요구한다거나 하는 일이 발생하곤 한다.

과스펙의 EC2로 인한 과금은 내용 증명만 잘한다면 한 번쯤은 AWS에서 구제를 해줄 수는 있다. 하지만 리소스를 모두 지워버린다면 정말 답이 없는 상황이다. 이를 예방하기 위해 가장 중요한 것은 기본적인 보안이나 AWS Config 혹은 CloudTrail와 EventBridge를 통해 실시간으로 보안 감사를 적용할 수 있다.

AWS Config

AWS Config 서비스는 리전에 종속되어 주로 사용하는 리전에 개별로 적용할 때 유용하다. Config의 자세한 내용은 아래 문서를 참고하고 설정 방법은 간단하니 공식 문서를 보고 적용하면 된다.

 

AWS Config의 작동 방식 - AWS Config

이 페이지에 작업이 필요하다는 점을 알려 주셔서 감사합니다. 실망시켜 드려 죄송합니다. 잠깐 시간을 내어 설명서를 향상시킬 수 있는 방법에 대해 말씀해 주십시오.

docs.aws.amazon.com

별다른 규칙은 적용하지 않고 일반 설정에서 EC2 Instance만 기록하도록 설정한다. AWS Config 역할은 자동으로 생성된 역할을 사용하고 데이터 보존 기간은 회사에서 요구로 하는 혹은 필요로 하는 기간을 선택한다. 데이터 보존 기간은 금전적인 부분으로 이어지므로 알아두자.

 

EventBridge

EventBridge를 이용하면 AWS Config의 이벤트 패턴에 맞춰 원하는 내용의 알림을 SNS에 보낼 수 있다. 아래의 공식문서를 요약하자면 AWS Config에서 응답한 JSON 값들을 파싱 하여 사용자가 쉽게 읽을 수 있게 텍스트 값으로 변환하는 내용이다.

 

AWS Config를 사용하여 리소스를 생성할 때 사용자 지정 이메일 알림 수신

새 AWS 리소스가 생성될 때 서비스 이벤트 유형에 따라 시작하는 Amazon EventBridge 규칙을 생성했습니다. 하지만 응답은 JSON 형식입니다. 사용자 지정 알림이 포함된 이메일 응답을 받으려면 어떻게

aws.amazon.com

이벤트 패턴

{
  "source": [
    "aws.config"
  ],
  "detail-type": [
    "Config Configuration Item Change"
  ],
  "detail": {
    "messageType": [
      "ConfigurationItemChangeNotification"
    ],
    "configurationItem": {
      "resourceType": [
        "AWS::EC2::Instance"
      ],
      "configurationItemStatus": [
        "ResourceDiscovered"
      ]
    }
  }
}

source: 이벤트 패턴 중 정의된 AWS 서비스 리스트

detail-type: 정의된 서비스의 Detail 한 행동

detail: 이벤트의 detail 정보

발생한  이벤트와 정의된 값들이 일치할 경우 Eventbridge는 트리거 된다. aws.config 서비스에서 Config Configuration Item Change가 발생했을 때 EC2의 상태 값이 변경되었을 때 트리거한다는 내용이다.


입력 변환기

{"awsAccountId":"$.detail.configurationItem.awsAccountId","awsRegion":"$.detail.configurationItem.awsRegion","configurationItemCaptureTime":"$.detail.configurationItem.configurationItemCaptureTime","resource_ID":"$.detail.configurationItem.resourceId","resource_type":"$.detail.configurationItem.resourceType"}
"On <configurationItemCaptureTime> AWS Config service recorded a creation of a new <resource_type> with Id <resource_ID> in the account <awsAccountId> region <awsRegion>. For more details open the AWS Config console at https://console.aws.amazon.com/config/home?region=<awsRegion>#/timeline/<resource_type>/<resource_ID>/configuration"

AWS CloudTrail

위 내용을 응용해서 글로벌 서비스인 CloudTrail을 이용해 모든 리전에서 발생하는 이벤트를 필터링해서 중요 내용만 수신받을 수 있다. 아래 이벤트 패턴은 CloudTrail에서 수집된 모든 aws 서비스의 이벤트에 대하여 수집하나 버지니아 리전 같은 경우 모든 이벤트가 통합되는 리전으로 필터링하지 않을 경우 다량의 메일을 수신받을 수 있으니 주의해야 한다.

이벤트 패턴

{
  "source": [{
    "prefix": "aws"
  }],
  "detail-type": ["AWS API Call via CloudTrail"],
  "detail": {
    "eventSource": [{
      "anything-but": ["cloudtrail.amazonaws.com", "kms.amazonaws.com", "sts.amazonaws.com", "support.amazonaws.com"]
    }],
    "userAgent": [{
      "anything-but": ["support.amazonaws.com", "events.amazonaws.com", "Datadog", "trustedadvisor.amazonaws.com", "config.amazonaws.com"]
    }]
  }
}

source: 전체 - aws로 시작하는 모든 서비스

detail-type: CloudTrail로 수집되는 모든 이벤트

eventSource: anything-but에 명시된 서비스를 제외한 모든 서비스

userAgent: anything-but에 명시된 userAgent를 제외한 모든 서비스

해당 이벤트 패턴을 적용하면 분명 다량의 메일을 수신받을 수 있다. 일단 적용하고 하나씩 줄여가는 것을 추천한다. 예를 들면 Datadog을 사용하여 CloudWatch를 수집한다면 매분마다 Datadog이 이벤트를 수집할 때 알람이 발생하는 데 이 부분을 예외 처리해주어야 한다.


 

Content filtering in Amazon EventBridge event patterns - Amazon EventBridge

Content filtering in Amazon EventBridge event patterns Amazon EventBridge supports declarative content filtering using event patterns. With content filtering, you can write complex event patterns that only match events under very specific conditions. For e

docs.aws.amazon.com

입력 변환기

"<eventName> has executed on <eventSource> located in AWS region <awsRegion> at <eventTime> (UTC)."
"Event Details:"
"Account ID: <awsAccountId>"
"Region: <awsRegion>"
"User: <userName>"
"Agent: <userAgent>"
"sourceIP: <sourceIPAddress>"
"request Param: <requestDetails>"

이메일 수신

"AttachRolePolicy has executed on iam.amazonaws.com located in AWS region us-east-1 at 2022-02-04T01:40:14Z (UTC)."
"Event Details:"
"Account ID: ..생략"
"Region: us-east-1"
"User: ..생략"
"Agent: aws-internal/3 aws-sdk-java/1.11.1030 Linux/5.4.156-94.273.amzn2int.x86_64 OpenJDK_64-Bit_Server_VM/25.312-b07 java/1.8.0_312 vendor/Oracle_Corporation cfg/retry-mode/standard, AWSLambdaConsole/1.1"
"sourceIP: ..생략"
"request Param: ... 생략"

--
If you wish to stop receiving notifications from this topic, please click or visit the link below to unsubscribe:

Please do not reply directly to this email. If you have any questions or comments regarding this email, please contact us at https://aws.amazon.com/support

이런 식의 형태로 메일을 수신받을 수 있다.  us-east-1 리전에서 IAM Role에 특정 정책을 Attach 한 이벤트가 발생했다는 내용이다. 어떤 User가 어떤 IP에서 특정 행위를 했는지 자세하게 확인이 가능하다.

 

EventBridge 교차리전

여기서 생각해봐야 할 것이 있다. CloudTrail은 Global 한 서비스이나 EventBridge에 연동할 SNS는 리전 종속이다. 그렇다면 미사용 리전 전체의 알림을 받고 싶을 때는 EventBridge와 SNS 모두 일일이 등록해야 하는 것일까?

 

Sending and receiving Amazon EventBridge events between AWS Regions - Amazon EventBridge

Sending and receiving Amazon EventBridge events between AWS Regions You can configure EventBridge to send and receive events between AWS Regions. You can also allow or deny events from specific Regions, specific rules associated with the event bus, or even

docs.aws.amazon.com

EventBridge 교차리전은 다른 리전의 EventBridge를 통합할 수 있는 기능이다. 즉, 미사용 리전마다 등록된 EventBridge를 하나의 리전에서 통합한 뒤 해당 리전에서 SNS를 연동하면 된다. SNS를 모든 리전에 일일이 등록하는 반복 작업은 피했으나 안타깝게도 EventBridge는 하나하나 적용해줘야 한다. 

 

마치며


위에서도 언급했듯이 본 글과 동일하게 적용할 경우 대량의 EventBridge 알림을 받을 수도 있을 것이다. 일단 적용하고 예외 처리하는 것을 추천한다. 물론 크리티컬 한 동작을 이메일로 수신받으며 한동안은 좋을 것이다. 하지만 이는 근본적인 보안 해결 방안이 아니므로 AWS에서 제공하는 Best Practice로 콘솔 계정을 관리하는 것이 좋다. 이는 계정 탈취를 당한 직후나 특정 감사일에 일시적으로 적용할 것을 추천한다.