CyberArk Endpoint Privilege Manager 로그 수집

파서 버전: 2.0

다음에서 지원:

이 문서에서는 Cloud Storage V2를 사용하여 CyberArk Endpoint Privilege Manager(EPM) 로그를 Google Security Operations로 수집하는 방법을 설명합니다.

CyberArk Endpoint Privilege Manager는 로컬 관리자 권한을 제거하고, 실행 또는 승격할 수 있는 애플리케이션을 제어하고, 사용자 인증 정보를 도난으로부터 보호함으로써 Windows, macOS, Linux 엔드포인트에 최소 권한을 적용합니다. EPM SaaS는 EPM REST API를 통해 이벤트 데이터를 노출합니다. Cloud Run 함수는 각 EPM 세트의 원시 이벤트를 폴링하고 이를 Cloud Storage 버킷에 기록하며, Google SecOps는 이 버킷에서 이벤트를 수집합니다.

시작하기 전에

다음 기본 요건이 충족되었는지 확인합니다.

  • Google SecOps 인스턴스
  • Cloud Storage API가 사용 설정된 Google Cloud 프로젝트
  • Cloud Storage 버킷을 만들고 관리할 수 있는 권한
  • Cloud Storage 버킷에서 Identity and Access Management(IAM) 정책을 관리할 수 있는 권한
  • Cloud Run 서비스, Pub/Sub 주제, Cloud Scheduler 작업을 만들 수 있는 권한
  • CyberArk EPM SaaS 테넌트
  • API 사용자 및 역할을 만들 수 있는 EPM 계정 관리자

Cloud Storage 버킷 만들기

  1. Google Cloud 콘솔로 이동합니다.
  2. 프로젝트를 선택하거나 새 프로젝트를 만듭니다.
  3. 탐색 메뉴에서 Cloud Storage > 버킷으로 이동합니다.
  4. 버킷 만들기를 클릭합니다.
  5. 다음 구성 세부정보를 제공합니다.

    설정 값
    버킷 이름 지정 전역적으로 고유한 이름(예: cyberark-epm-secops-logs)을 입력합니다.
    위치 유형 필요에 따라 선택(리전, 이중 리전, 멀티 리전)
    위치 위치를 선택합니다(예: us-central1).
    스토리지 클래스 표준(자주 액세스하는 로그에 권장)
    액세스 제어 균일(권장)
    보호 도구 선택사항: 객체 버전 관리 또는 보관 정책 사용 설정
  6. 만들기를 클릭합니다.

CyberArk EPM 사용자 인증 정보 수집

Cloud Run Functions는 EPM 사용자로 EPM REST API에 로그인합니다. 이벤트를 수집하려는 세트에 대한 보기 전용 액세스 권한이 있는 전용 사용자를 만듭니다.

API 사용자 만들기

  1. 계정 관리자로 EPM 관리 콘솔에 로그인합니다.
  2. 관리 타일을 클릭합니다.
  3. 사용자 페이지로 이동하여 사용자 추가를 클릭합니다.
  4. 다음 구성 세부정보를 제공합니다.
    • 이메일 주소: 통합 사용자의 로그인 이름을 입력합니다(예: secops-collector@example.com).
    • 비밀번호: 12~128자(영문 기준)의 비밀번호를 입력합니다.
  5. 추가를 클릭합니다.
  6. 로그인 이름과 비밀번호를 안전하게 저장합니다. 이러한 값을 Cloud Run 함수의 EPM_USERNAME 및 EPM_PASSWORD 값으로 사용합니다.

보기 전용 역할 만들기 및 할당하기

  1. 관리에서 역할 페이지로 이동하여 역할 만들기를 클릭합니다.
  2. 다음 구성 세부정보를 제공합니다.
    • 이름: 역할의 이름을 입력합니다(예: SecOps view only).
    • 권한 그룹: 보기 전용을 선택합니다.
    • 세트: 이벤트를 수집할 모든 세트를 선택합니다.
  3. 만들기를 클릭합니다.
  4. 역할 할당 페이지로 이동합니다.
  5. 만든 역할의 행에서 작업 더보기(…) > 사용자 할당 또는 할당 취소를 클릭합니다.
  6. 사용자 할당을 클릭하고 통합 사용자를 검색하여 선택한 후 할당을 클릭합니다.
  7. 저장을 클릭합니다.

EPM 로그인 URL 확인

EPM 인증 API는 해당 리전의 디스패처 서버에서 제공됩니다. 함수는 이 URL을 로그인에만 사용합니다. 다른 모든 호출은 로그인 응답이 반환하는 관리자 URL로 이동합니다.

리전 로그인 URL
미국 https://login.epm.cyberark.com
독일 https://eu.epm.cyberark.com
스위스 https://ch.epm.cyberark.com
영국 https://uk.epm.cyberark.com
오스트레일리아 https://au.epm.cyberark.com
캐나다 https://ca.epm.cyberark.com
인도 https://in.epm.cyberark.com
일본 https://jp.epm.cyberark.com
싱가포르 https://sg.epm.cyberark.com
이탈리아 https://it.epm.cyberark.com
아랍에미리트 https://ae.epm.cyberark.com
연방 https://login.epm.cyberarkgov.cloud

테스트 API 액세스

  • 통합을 진행하기 전에 다음과 같이 사용자 인증 정보를 테스트합니다.

    # Replace with your actual values
    EPM_LOGIN_URL="https://login.epm.cyberark.com"
    EPM_USERNAME="<your-username>"
    EPM_PASSWORD="<your-password>"
    
    # Sign in and get a session token and the manager URL
    curl -s -X POST "$EPM_LOGIN_URL/EPM/API/Auth/EPM/Logon" \
        -H "Content-Type: application/json" \
        -d "{\"Username\":\"$EPM_USERNAME\",\"Password\":\"$EPM_PASSWORD\",\"ApplicationID\":\"GoogleSecOps\"}"
    
  • 응답에 성공하면 EPMAuthenticationResult(세션 토큰) 및 ManagerURL가 반환됩니다. 역할을 확인하려면 다음과 같이 토큰이 있는 세트를 나열합니다.

    # Replace with the values from the sign-in response
    MANAGER_URL="<ManagerURL>"
    TOKEN="<EPMAuthenticationResult>"
    
    curl -s "$MANAGER_URL/EPM/API/Sets?Limit=1000" \
        -H "Authorization: basic $TOKEN"
    

응답에는 사용자가 볼 수 있는 모든 세트가 나열됩니다. Sets가 비어 있으면 역할이 할당되지 않거나 집합이 포함되지 않습니다.

Cloud Run 함수의 서비스 계정 만들기

Cloud Run 함수에는 Cloud Storage 버킷에 쓰고 Pub/Sub에서 호출할 수 있는 권한이 있는 서비스 계정이 필요합니다.

서비스 계정 만들기

  1. Google Cloud 콘솔에서 IAM 및 관리자 > 서비스 계정으로 이동합니다.
  2. 서비스 계정 만들기를 클릭합니다.
  3. 다음 구성 세부정보를 제공합니다.
    • 서비스 계정 이름: cyberark-epm-collector-sa을 입력합니다.
    • 서비스 계정 설명: Service account for Cloud Run function to collect CyberArk EPM logs을 입력합니다.
  4. 만들고 계속하기를 클릭합니다.
  5. 이 서비스 계정에 프로젝트에 대한 액세스 권한 부여 섹션에서 다음 역할을 추가합니다.
    1. 역할 선택을 클릭합니다.
    2. 스토리지 객체 관리자를 검색하여 선택합니다.
    3. + 다른 역할 추가를 클릭합니다.
    4. Cloud Run 호출자를 검색하여 선택합니다.
    5. + 다른 역할 추가를 클릭합니다.
    6. Cloud Functions 호출자를 검색하여 선택합니다.
  6. 계속을 클릭합니다.
  7. 완료를 클릭합니다.

이러한 역할은 다음 작업에 필요합니다.

  • 스토리지 객체 관리자: Cloud Storage 버킷에 로그를 쓰고 상태 파일을 관리합니다.
  • Cloud Run 호출자: Pub/Sub가 함수를 호출하도록 허용합니다.
  • Cloud Functions 호출자: 함수 호출 허용

Cloud Storage 버킷에 IAM 권한 부여

서비스 계정에 Cloud Storage 버킷에 대한 쓰기 권한을 부여합니다.

  1. Google Cloud 콘솔에서 Cloud Storage > 버킷으로 이동합니다.
  2. 버킷 이름을 클릭합니다.
  3. 권한 탭으로 이동합니다.
  4. 액세스 권한 부여를 클릭합니다.
  5. 다음 구성 세부정보를 제공합니다.
    • 주 구성원 추가: 서비스 계정 이메일(예: cyberark-epm-collector-sa@PROJECT_ID.iam.gserviceaccount.com)을 입력합니다.
    • 역할 할당: 스토리지 객체 관리자를 선택합니다.
  6. 저장을 클릭합니다.

Pub/Sub 주제 만들기

Cloud Scheduler가 게시하고 Cloud Run 함수가 구독할 Pub/Sub 주제를 만듭니다.

  1. Google Cloud 콘솔에서 Pub/Sub > 주제로 이동합니다.
  2. 주제 만들기를 클릭합니다.
  3. 다음 구성 세부정보를 제공합니다.
    • 주제 ID: cyberark-epm-trigger를 입력합니다.
    • 다른 설정은 기본값으로 둡니다.
  4. 만들기를 클릭합니다.

로그를 수집하는 Cloud Run 함수 만들기

Cloud Run 함수는 Cloud Scheduler의 Pub/Sub 메시지에 의해 트리거되어 CyberArk EPM REST API에서 원시 이벤트를 가져와 Cloud Storage에 기록합니다.

  1. Google Cloud 콘솔에서 Cloud Run으로 이동합니다.
  2. 함수 작성을 클릭합니다.
  3. 구성 섹션에서 다음 구성 세부정보를 제공합니다.

    설정 값
    서비스 이름 cyberark-epm-collector
    리전 Cloud Storage 버킷과 일치하는 리전(예: us-central1)을 선택합니다.
    런타임 Python 3.12 이상을 선택합니다.
  4. 트리거 섹션에서 트리거 추가를 클릭하고 Pub/Sub 트리거를 선택합니다.

  5. Eventarc 트리거 창에서 다음 구성 세부정보를 제공합니다.

    • 트리거 이름: 생성된 이름을 유지하거나 트리거 이름을 입력합니다.
    • 트리거 유형: Google 소스를 선택합니다.
    • 이벤트 제공자: Pub/Sub를 선택합니다.
    • 이벤트 유형: google.cloud.pubsub.topic.v1.messagePublished를 선택합니다.
    • Cloud Pub/Sub 주제 선택: cyberark-epm-trigger 주제를 선택합니다.
    • 리전: 함수와 동일한 리전을 선택합니다.
    • 서비스 계정: 서비스 계정 cyberark-epm-collector-sa를 선택합니다.
  6. 트리거 저장을 클릭합니다.

  7. 인증 섹션에서 다음을 구성합니다.

    1. 인증 필요를 선택합니다.
    2. Identity and Access Management(IAM)를 선택합니다.
  8. 컨테이너, 네트워킹, 보안으로 이동하여 펼칩니다.

  9. 보안 탭으로 이동합니다.

    • 서비스 계정: 서비스 계정 cyberark-epm-collector-sa을 선택합니다.
  10. 컨테이너 탭으로 이동합니다.

    1. 변수 및 보안 비밀을 클릭합니다.
    2. 각 환경 변수에 대해 + 변수 추가를 클릭합니다.
    변수 이름 예시 값 설명
    GCS_BUCKET cyberark-epm-secops-logs Cloud Storage 버킷 이름
    GCS_PREFIX cyberark-epm 로그 파일의 프리픽스
    STATE_KEY cyberark-epm-state.json 로그 프리픽스 외부의 상태 경로
    EPM_LOGIN_URL https://login.epm.cyberark.com 거주 지역의 EPM 로그인 URL
    EPM_USERNAME secops-collector@example.com EPM API 사용자의 로그인 이름
    EPM_PASSWORD <your-password> EPM API 사용자의 비밀번호
    EPM_APPLICATION_ID GoogleSecOps 로그인 시 보고된 애플리케이션 이름
    EPM_SET_IDS (비어있음) 쉼표로 구분된 세트 ID(선택사항). 비어 있으면 사용자가 볼 수 있는 모든 세트를 수집합니다.
    EPM_API_VERSION (비어있음) 선택적 API 버전(예: 24.12.0.1). 비어 있으면 최신 버전이 사용됩니다.
    MAX_RECORDS 10000 실행당 최대 레코드 수
    PAGE_SIZE 1000 페이지당 레코드 수(API 최댓값은 1,000)
    LOOKBACK_HOURS 24 첫 실행 시 초기 대상 기간
    OVERLAP_MINUTES 15 워터마크 전에 기간을 다시 읽어 에이전트가 늦게 보고하는 이벤트 포착
  11. 변수 및 보안 비밀 섹션에서 요청으로 이동합니다.

    • 요청 제한 시간: 600초(10분)를 입력합니다.
  12. 설정 탭으로 이동합니다.

    • 리소스 섹션에서 다음을 수행합니다.
      • 메모리: 512MiB 이상을 선택합니다.
      • CPU: 1 선택
  13. 버전 확장 섹션에서 다음을 수행합니다.

    • 최소 인스턴스 수: 0를 입력합니다.
    • 최대 인스턴스 수: 1을 입력합니다.
  14. 만들기를 클릭합니다.

  15. 서비스가 생성될 때까지 기다립니다(1~2분).

  16. 서비스가 생성되면 인라인 코드 편집기가 자동으로 열립니다.

함수 코드 추가

  1. 진입점 필드에 main을 입력하세요.
  2. 인라인 코드 편집기에서 다음 두 파일을 만듭니다.

    • 첫 번째 파일 - main.py:

      import functions_framework
      from google.cloud import storage
      from google.cloud.exceptions import NotFound
      import hashlib
      import json
      import os
      import urllib3
      from urllib.parse import urlencode
      from datetime import datetime, timezone, timedelta
      import time
      
      # Initialize HTTP client with timeouts
      http = urllib3.PoolManager(
              timeout=urllib3.Timeout(connect=5.0, read=60.0),
              retries=False,
      )
      
      # Initialize Storage client
      storage_client = storage.Client()
      
      # Environment variables
      GCS_BUCKET = os.environ.get('GCS_BUCKET')
      GCS_PREFIX = os.environ.get('GCS_PREFIX', 'cyberark-epm')
      # STATE_KEY must stay OUTSIDE GCS_PREFIX. The feed ingests every object under
      # its bucket URI and, with a deletion option selected, deletes what it
      # transferred. A state file inside the prefix would be ingested as log data and
      # then deleted, resetting collection and re-ingesting duplicates.
      STATE_KEY = os.environ.get('STATE_KEY', 'cyberark-epm-state.json')
      EPM_LOGIN_URL = os.environ.get('EPM_LOGIN_URL', 'https://login.epm.cyberark.com')
      EPM_USERNAME = os.environ.get('EPM_USERNAME')
      EPM_PASSWORD = os.environ.get('EPM_PASSWORD')
      EPM_APPLICATION_ID = os.environ.get('EPM_APPLICATION_ID', 'GoogleSecOps')
      # Comma-separated set IDs to collect. Empty collects every set the user can view.
      EPM_SET_IDS = [s.strip() for s in os.environ.get('EPM_SET_IDS', '').split(',') if s.strip()]
      # API version segment. Empty uses the latest version, which CyberArk recommends.
      EPM_API_VERSION = os.environ.get('EPM_API_VERSION', '').strip()
      MAX_RECORDS = int(os.environ.get('MAX_RECORDS', '10000'))
      # The Events/Search API returns at most 1,000 records per page.
      PAGE_SIZE = min(int(os.environ.get('PAGE_SIZE', '1000')), 1000)
      LOOKBACK_HOURS = int(os.environ.get('LOOKBACK_HOURS', '24'))
      # The query re-reads this many minutes before the watermark. EPM agents report
      # in batches, so an event can reach the service well after its event date.
      # Re-read events are removed by content hash.
      OVERLAP_MINUTES = int(os.environ.get('OVERLAP_MINUTES', '15'))
      # The events APIs allow 5 calls per second; keep a small gap between calls.
      CALL_INTERVAL_SECONDS = 0.25
      
      class FetchError(Exception):
              """Raised when the EPM API call fails.
      
              The watermark must never advance on a failed fetch, otherwise the events in
              the failed window are skipped permanently.
              """
      
      def parse_datetime(value: str) -> datetime:
              """Parse an ISO 8601 datetime string into an aware datetime."""
              if value.endswith('Z'):
                      value = value[:-1] + '+00:00'
              dt = datetime.fromisoformat(value)
              if dt.tzinfo is None:
                      dt = dt.replace(tzinfo=timezone.utc)
              return dt
      
      def epm_time(dt: datetime) -> str:
              """Render a datetime in the YYYY-MM-DDThh:mm:ssZ form the EPM filter accepts."""
              return dt.astimezone(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
      
      def api_path(*parts: str) -> str:
              """Build an /EPM/API path, inserting the version segment when one is set."""
              segments = ['EPM', 'API']
              if EPM_API_VERSION:
                      segments.append(EPM_API_VERSION)
              segments.extend(parts)
              return '/' + '/'.join(segments)
      
      def event_keys(event: dict) -> set:
              """Return the identity this event can be recognised by.
      
              Raw events carry no unique event ID, so a record counts as already
              collected when its full JSON content was seen before. The overlap window
              returns the same JSON again, which this catches without any knowledge of
              the payload schema.
              """
              return {'sha256:' + hashlib.sha256(
                      json.dumps(event, sort_keys=True, ensure_ascii=False).encode('utf-8')
              ).hexdigest()}
      
      def event_time(event: dict) -> str:
              """Return the event timestamp as an ISO 8601 string, or an empty string.
      
              Raw events carry the time of the most recent occurrence in `lastEventDate`.
              """
              value = event.get('lastEventDate')
              return str(value) if value else ''
      
      @functions_framework.cloud_event
      def main(cloud_event):
              """Fetch CyberArk EPM raw events and write them to Cloud Storage.
      
              Args:
                      cloud_event: CloudEvent object containing the Pub/Sub message.
              """
              if not all([GCS_BUCKET, EPM_LOGIN_URL, EPM_USERNAME, EPM_PASSWORD]):
                      # Raise rather than return: a bare return acks the Pub/Sub message and
                      # reports the run as successful, silently discarding the schedule tick.
                      raise RuntimeError('Missing required environment variables')
      
              bucket = storage_client.bucket(GCS_BUCKET)
              state = load_state(bucket, STATE_KEY)
              set_states = state.get('sets', {})
      
              now = datetime.now(timezone.utc)
      
              manager_url, token = login()
              headers = {
                      'Authorization': f'basic {token}',
                      'Content-Type': 'application/json',
                      'Accept': 'application/json',
              }
      
              sets = list_sets(manager_url, headers)
              if EPM_SET_IDS:
                      sets = [s for s in sets if s['Id'] in EPM_SET_IDS]
                      missing = set(EPM_SET_IDS) - {s['Id'] for s in sets}
                      if missing:
                              raise FetchError(f'Configured set IDs not visible to this user: {sorted(missing)}')
              if not sets:
                      raise FetchError('No EPM sets are visible to this user; check the assigned role')
      
              fresh_all = []
              new_set_states = {}
              budget = MAX_RECORDS
      
              for epm_set in sets:
                      set_id = epm_set['Id']
                      set_state = set_states.get(set_id, {})
                      watermark = None
                      if set_state.get('last_event_time'):
                              watermark = parse_datetime(set_state['last_event_time'])
                      seen_keys = set(set_state.get('seen_keys', []))
      
                      if watermark is None:
                              start_time = now - timedelta(hours=LOOKBACK_HOURS)
                      else:
                              start_time = watermark - timedelta(minutes=OVERLAP_MINUTES)
      
                      print(f"Set {set_id} ({epm_set.get('Name', '')}): fetching events from {start_time.isoformat()} to {now.isoformat()}")
      
                      # A FetchError here propagates: the run fails, the watermark is untouched,
                      # and the next invocation retries the same window.
                      records, newest_event_time = fetch_events(
                              manager_url=manager_url,
                              headers=headers,
                              set_id=set_id,
                              start_time=start_time,
                              end_time=now,
                              page_size=PAGE_SIZE,
                              max_records=budget,
                      )
                      budget -= len(records)
      
                      # Remove events already written by an earlier run. Without this, the overlap
                      # window re-emits its events on every invocation.
                      fresh = [r for r in records if not (event_keys(r) & seen_keys)]
                      print(f"Set {set_id}: fetched {len(records)} records, {len(fresh)} new after deduplication")
      
                      if not fresh:
                              new_set_states[set_id] = set_state
                              continue
      
                      if not newest_event_time:
                              # A watermark that cannot be derived from the data is not a watermark.
                              # Advancing on wall-clock here would skip every late-reported event.
                              raise FetchError(f'Set {set_id}: records were returned but no event timestamp could be parsed')
      
                      # The parser reads the set from the event itself. Annotate copies so the
                      # deduplication hashes keep matching what the API returns next time.
                      fresh_all.extend({**record, 'setID': set_id} for record in fresh)
      
                      new_watermark = parse_datetime(newest_event_time)
                      if watermark and new_watermark < watermark:
                              new_watermark = watermark
      
                      # Retain only the hashes still inside the overlap window, so the state file
                      # stays small while covering every event the next query can re-read.
                      cutoff = new_watermark - timedelta(minutes=OVERLAP_MINUTES)
                      retained = set()
                      for record in records:
                              stamp = event_time(record)
                              if not stamp:
                                      continue
                              try:
                                      if parse_datetime(stamp) >= cutoff:
                                              retained.update(event_keys(record))
                              except ValueError:
                                      continue
      
                      new_set_states[set_id] = {
                              'last_event_time': new_watermark.isoformat(),
                              'seen_keys': sorted(retained),
                      }
      
                      if budget <= 0:
                              print(f"Reached max_records limit ({MAX_RECORDS}); remaining sets are collected by the next run")
                              break
      
              # Keep the state of sets not visited in this run.
              for set_id, set_state in set_states.items():
                      new_set_states.setdefault(set_id, set_state)
      
              if not fresh_all:
                      print("No new events found. Watermarks left unchanged.")
                      return
      
              timestamp = now.strftime('%Y%m%dT%H%M%SZ')
              object_key = f"{GCS_PREFIX}/events_{timestamp}.ndjson"
              blob = bucket.blob(object_key)
      
              ndjson = '\n'.join(json.dumps(record, ensure_ascii=False) for record in fresh_all) + '\n'
              blob.upload_from_string(ndjson, content_type='application/x-ndjson')
      
              print(f"Wrote {len(fresh_all)} records to gs://{GCS_BUCKET}/{object_key}")
      
              # Advance the watermarks only after the data is durably written.
              save_state(bucket, STATE_KEY, {'sets': new_set_states})
      
              print(f"Successfully processed {len(fresh_all)} records")
      
      def load_state(bucket, key):
              """Read the collector state from Cloud Storage.
      
              Only a missing object is treated as a cold start. Any other error is raised:
              swallowing it would silently reset collection to the full lookback window
              and re-ingest that entire period.
              """
              blob = bucket.blob(key)
              try:
                      return json.loads(blob.download_as_text())
              except NotFound:
                      print('No state file found. Starting from the lookback window.')
                      return {}
      
      def save_state(bucket, key, state: dict):
              """Write the collector state to Cloud Storage.
      
              Failures are raised, not logged. If the state write fails after the data was
              uploaded, the next run repeats the same window and duplicates it.
              """
              blob = bucket.blob(key)
              blob.upload_from_string(
                      json.dumps(state, indent=2),
                      content_type='application/json',
              )
              print(f"Saved state for {len(state.get('sets', {}))} sets")
      
      def request_json(method: str, url: str, headers: dict, body: dict = None):
              """Call the EPM API and return the decoded JSON body.
      
              Raises FetchError on any transport or HTTP failure, so that the caller does
              not mistake a failed call for an empty result and advance the watermark.
              """
              backoff = 1.0
              for attempt in range(5):
                      time.sleep(CALL_INTERVAL_SECONDS)
                      try:
                              response = http.request(
                                      method,
                                      url,
                                      body=json.dumps(body).encode('utf-8') if body is not None else None,
                                      headers=headers,
                              )
                      except Exception as e:
                              raise FetchError(f'Request to {url} failed: {e}') from e
      
                      if response.status == 429:
                              raw_retry_after = response.headers.get('Retry-After')
                              try:
                                      # Retry-After may also be an HTTP date, which int() cannot parse.
                                      wait = int(raw_retry_after) if raw_retry_after else int(backoff)
                              except (TypeError, ValueError):
                                      wait = int(backoff)
                              print(f"Rate limited (429). Retrying after {wait}s...")
                              time.sleep(wait)
                              backoff = min(backoff * 2, 30.0)
                              continue
      
                      if response.status != 200:
                              raise FetchError(f'HTTP {response.status} from {url}: {response.data.decode("utf-8", "replace")}')
      
                      try:
                              return json.loads(response.data.decode('utf-8'))
                      except json.JSONDecodeError as e:
                              raise FetchError(f'Malformed JSON response from {url}: {e}') from e
      
              raise FetchError('Rate limited repeatedly; giving up without advancing the watermark')
      
      def login():
              """Authenticate to EPM and return the manager URL and session token.
      
              EPM allows one API login per minute per user, so the function signs in once
              per run and reuses the token for every call in that run.
              """
              url = f"{EPM_LOGIN_URL.rstrip('/')}{api_path('Auth', 'EPM', 'Logon')}"
              body = {
                      'Username': EPM_USERNAME,
                      'Password': EPM_PASSWORD,
                      'ApplicationID': EPM_APPLICATION_ID,
              }
              data = request_json('POST', url, {'Content-Type': 'application/json'}, body)
              token = data.get('EPMAuthenticationResult')
              manager_url = data.get('ManagerURL')
              if not token or not manager_url:
                      raise FetchError(f'Login response did not contain a token and manager URL: {data}')
              if data.get('IsPasswordExpired'):
                      raise FetchError('The EPM user password has expired; set a new password and update EPM_PASSWORD')
              return manager_url.rstrip('/'), token
      
      def list_sets(manager_url: str, headers: dict):
              """Return the sets visible to the API user."""
              url = f"{manager_url}{api_path('Sets')}?{urlencode({'Offset': 0, 'Limit': 1000})}"
              data = request_json('GET', url, headers)
              sets = data.get('Sets') or []
              print(f"Found {len(sets)} sets")
              return sets
      
      def fetch_events(manager_url: str, headers: dict, set_id: str, start_time: datetime, end_time: datetime, page_size: int, max_records: int):
              """Fetch raw events for one set from the EPM Events/Search API.
      
              Pages with nextCursor, which returns events in chronological order. A time
              watermark is only correct over an ascending scan: with newest-first ordering
              a truncated run would advance the watermark past unread events.
      
              Returns:
                      Tuple of (records list, newest_event_time ISO string).
              """
              endpoint = f"{manager_url}{api_path('Sets', set_id, 'Events', 'Search')}"
              body = {
                      'filter': f'eventDate GE {epm_time(start_time)} AND eventDate LE {epm_time(end_time)}',
              }
      
              records = []
              newest_time = None
              cursor = 'start'
              page_num = 0
      
              while True:
                      page_num += 1
      
                      if len(records) >= max_records:
                              # Stop cleanly. The remaining events stay ahead of the watermark and
                              # are collected by the next run.
                              print(f"Set {set_id}: reached max_records limit ({max_records})")
                              break
      
                      # Rebuild the full query on every page; the time window must never be dropped.
                      url = f"{endpoint}?{urlencode({'nextCursor': cursor, 'limit': page_size})}"
                      data = request_json('POST', url, headers, body)
      
                      page_results = data.get('events') or []
                      if not page_results:
                              print(f"Set {set_id}: no more results (empty page)")
                              break
      
                      print(f"Set {set_id}: page {page_num} retrieved {len(page_results)} events")
                      records.extend(page_results)
      
                      for event in page_results:
                              stamp = event_time(event)
                              if not stamp:
                                      continue
                              try:
                                      if newest_time is None or parse_datetime(stamp) > parse_datetime(newest_time):
                                              newest_time = stamp
                              except ValueError as e:
                                      print(f"Warning: Could not parse event time {stamp!r}: {e}")
      
                      cursor = data.get('nextCursor')
                      if not cursor:
                              break
      
              print(f"Set {set_id}: retrieved {len(records)} total events from {page_num} pages")
              return records, newest_time
      

    • 두 번째 파일 - requirements.txt:

      functions-framework==3.*
      google-cloud-storage==2.*
      urllib3>=2.0.0
      
  3. 배포를 클릭하여 함수를 저장하고 배포합니다.

  4. 배포가 완료될 때까지 기다립니다(2~3분).

함수가 이벤트를 수집하는 방법

  • 이 함수는 실행당 한 번 로그인하고, 사용자가 볼 수 있는 세트를 나열하고, eventDate에 대한 필터를 사용하여 각 세트의 원시 이벤트 세부정보 가져오기 API를 호출하고, 시간순으로 nextCursor를 사용하여 페이징합니다.
  • 각 이벤트는 추가 setID 필드와 함께 작성되므로 집합이 로그에 보존됩니다.
  • 상태 파일은 세트당 확인된 최신 lastEventDate 및 중복 기간 내 이벤트의 해시를 유지합니다. 실행할 때마다 해당 워터마크 이전에 OVERLAP_MINUTES를 다시 읽고 이미 작성된 이벤트를 삭제하므로 지연 보고하는 에이전트가 중복 없이 수집됩니다.
  • API, 로그인 또는 스토리지 오류가 발생하면 실행이 실패하고 워터마크가 변경되지 않으므로 다음 실행에서 동일한 기간을 다시 시도합니다.

Cloud Scheduler 작업 만들기

Cloud Scheduler는 정기적으로 Pub/Sub 주제에 메시지를 게시하여 Cloud Run 함수를 트리거합니다.

  1. Google Cloud 콘솔에서 Cloud Scheduler로 이동합니다.
  2. 작업 만들기를 클릭합니다.
  3. 다음 구성 세부정보를 제공합니다.

    설정 값
    이름 cyberark-epm-collector-hourly
    리전 Cloud Run 함수와 동일한 리전 선택
    주파수 0 * * * *(매시간 정각)
    시간대 시간대 선택(UTC 권장)
    타겟 유형 Pub/Sub
    주제 Pub/Sub 주제 cyberark-epm-trigger 선택
    메일 본문 {}(빈 JSON 객체)
  4. 만들기를 클릭합니다.

일정 빈도 옵션

로그 볼륨 및 지연 시간 요구사항에 따라 빈도를 선택합니다.

빈도 크론 표현식 사용 사례
15분마다 */15 * * * * 짧은 지연 시간
1시간마다 0 * * * * 표준(권장)
6시간마다 0 */6 * * * 소량, 일괄 처리

통합 테스트

  1. Cloud Scheduler 콘솔에서 작업을 찾습니다.
  2. 강제 실행을 클릭하여 작업을 수동으로 트리거합니다.
  3. 몇 초 동안 기다립니다.
  4. Cloud Run > 서비스로 이동합니다.
  5. 함수 이름(cyberark-epm-collector)을 클릭합니다.
  6. 로그 탭을 클릭합니다.
  7. 함수가 실행되었는지 확인합니다. 다음 항목을 찾습니다.

    Found N sets
    Set <set-id> (<set-name>): fetching events from YYYY-MM-DDTHH:MM:SS+00:00 to YYYY-MM-DDTHH:MM:SS+00:00
    Set <set-id>: page 1 retrieved X events
    Wrote X records to gs://cyberark-epm-secops-logs/cyberark-epm/events_YYYYMMDDTHHMMSSZ.ndjson
    Successfully processed X records
    
  8. Cloud Storage > 버킷으로 이동합니다.

  9. 버킷 이름을 클릭합니다.

  10. 접두사 폴더(cyberark-epm/)로 이동합니다.

  11. 현재 타임스탬프로 새 .ndjson 파일이 생성되었는지 확인합니다.

로그에 오류가 표시되는 경우:

  • HTTP 401: EPM_USERNAME 및 EPM_PASSWORD를 확인하거나 1분 이내에 로그인이 반복되었는지 확인합니다.
  • HTTP 403: 사용자에게 세트에 대한 역할이 없거나 테넌트의 API 사용량 한도에 도달했습니다.
  • HTTP 404: EPM_SET_IDS의 잘못된 세트 ID
  • HTTP 429: 비율 제한 - 백오프를 사용한 함수 재시도
  • 환경 변수 누락: 필요한 모든 변수가 설정되어 있는지 확인합니다.

Google SecOps 서비스 계정 가져오기

Google SecOps는 고유한 서비스 계정을 사용하여 Cloud Storage 버킷에서 데이터를 읽습니다. 이 서비스 계정에 버킷에 대한 액세스 권한을 부여해야 합니다.

서비스 계정 이메일 가져오기

  1. 설정 > 데이터 관리 > 피드로 이동합니다. SIEM 전용 플랫폼을 사용하는 경우 설정 > 피드로 이동합니다.
  2. 새 피드 추가를 클릭합니다.
  3. 단일 피드 구성을 클릭합니다.
  4. 피드 이름 필드에 피드 이름을 입력합니다(예: CyberArk EPM logs).
  5. 소스 유형으로 Google Cloud Storage V2를 선택합니다.
  6. 로그 유형으로 CyberArk Endpoint Privilege Manager(EPM)를 선택합니다.
  7. 서비스 계정 가져오기를 클릭합니다.
  8. 고유한 서비스 계정 이메일이 표시됩니다. 예를 들면 다음과 같습니다.

    chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com
    
  9. 다음 단계에서 사용할 수 있도록 이 이메일 주소를 복사합니다.

  10. 다음을 클릭합니다.

  11. 다음 입력 파라미터의 값을 지정합니다.

    • 스토리지 버킷 URL: 프리픽스 경로가 있는 Cloud Storage 버킷 URI를 입력합니다.

      gs://cyberark-epm-secops-logs/cyberark-epm/
      
      • cyberark-epm-secops-logs을 Cloud Storage 버킷 이름으로 바꿉니다.
    • 소스 삭제 옵션: 환경설정에 따라 삭제 옵션을 선택합니다.

      • 파일 삭제 안함: 소스에서 파일을 삭제하지 않습니다(테스트에 권장).
      • 전송된 파일 및 빈 디렉터리 삭제: 가져오기가 완료된 후 소스에서 파일과 빈 디렉터리를 삭제합니다.

    • 최대 파일 기간: 지난 며칠 동안 수정된 파일을 포함합니다(기본값은 180일).

    • 애셋 네임스페이스: 애셋 네임스페이스

    • 수집 라벨: 이 피드의 이벤트에 적용할 라벨입니다.

  12. 다음을 클릭합니다.

  13. 확정 화면에서 새 피드 구성을 검토한 다음 제출을 클릭합니다.

Google SecOps 서비스 계정에 IAM 권한 부여

Google SecOps 서비스 계정에는 Cloud Storage 버킷에 대한 두 가지 역할이 필요합니다. 로그 객체를 읽기 위한 스토리지 객체 뷰어와 버킷 메타데이터를 읽기 위한 버킷 수준 역할입니다.

  1. Cloud Storage > 버킷으로 이동합니다.
  2. 버킷 이름을 클릭합니다.
  3. 권한 탭으로 이동합니다.
  4. 액세스 권한 부여를 클릭합니다.
  5. 다음 구성 세부정보를 제공합니다.
    • 주 구성원 추가: Google SecOps 서비스 계정 이메일을 붙여넣습니다.
    • 역할 할당: 다음을 모두 선택합니다.
      • 스토리지 객체 뷰어: 로그 객체를 읽습니다.
      • 스토리지 기존 버킷 리더: 버킷 메타데이터를 읽습니다. 전송된 파일 및 빈 디렉터리 삭제 삭제 옵션을 선택한 경우 대신 스토리지 기존 버킷 작성자를 선택합니다. 이 역할은 삭제 권한도 부여합니다.
  6. 저장을 클릭합니다.

UDM 매핑 테이블

로그 필드 UDM 매핑 로직
accessTargetType_label additional.fields 병합됨
accessaction_label additional.fields 병합됨
agentEventCount_label additional.fields 병합됨
arrivalTime_label additional.fields 병합됨
deceptionType_label additional.fields 병합됨
eventCount_label additional.fields 병합됨
logonAttemptTypeId_label additional.fields 병합됨
logonStatusId_label additional.fields 병합됨
modificationTime_label additional.fields 병합됨
originalFileName_label additional.fields 병합됨
owner_label additional.fields 병합됨
packageName_label additional.fields 병합됨
publisher_field additional.fields 병합됨
publisher_label additional.fields 병합됨
setID_label additional.fields 병합됨
skippedCount_label additional.fields 병합됨
sourceProcessSigner_field additional.fields 병합됨
sourceProcessSigner_label additional.fields 병합됨
sourceType_label additional.fields 병합됨
threatProtectionActionId_label additional.fields 병합됨
threatProtectionAction_label additional.fields 병합됨
user_is_admin_label additional.fields 병합됨
winEventRecordId_label additional.fields 병합됨
winEventType_label additional.fields 병합됨
workingDirectory_label additional.fields 병합됨
displayName metadata.description 직접 매핑됨
eachevent.displayName metadata.description 직접 매핑됨
lastEventDate metadata.event_timestamp ISO8601(으)로 파싱됨
has_principal metadata.event_type 매핑됨: true → STATUS_UPDATE
has_principal_user metadata.event_type 매핑됨: true → USER_UNCATEGORIZED
eachevent.eventType metadata.product_event_type 직접 매핑됨
eventType metadata.product_event_type 직접 매핑됨
productName metadata.product_version 직접 매핑됨
productVersion metadata.product_version 직접 매핑됨
url network.http.referral_url 직접 매핑됨
agentId principal.asset.asset_id 직접 매핑됨
eachevent.agentId principal.asset.asset_id 직접 매핑됨
computerName principal.asset.hostname 직접 매핑됨
sourceName principal.file.full_path 직접 매핑됨
computerName principal.hostname 직접 매핑됨
eachevent.computerName principal.hostname 직접 매핑됨
operatingSystemType principal.platform 직접 매핑됨
operating_system_type principal.platform 매핑됨: Windows → WINDOWS
company principal.user.company_name 직접 매핑됨
eachevent.userName principal.user.userid 직접 매핑됨
userName principal.user.userid 직접 매핑됨
sec_result security_result 병합됨
threat_protection_action security_result.action_details 직접 매핑됨
fileDescription security_result.description 직접 매핑됨
eachevent.policyName security_result.rule_name 직접 매핑됨
policyName security_result.rule_name 직접 매핑됨
justification security_result.summary 직접 매핑됨
fileQualifier target.asset.asset_id 직접 매핑됨
software target.asset.software 병합됨
eachevent.filePath target.file.full_path 직접 매핑됨
filePath target.file.full_path 직접 매핑됨
eachevent.hash target.file.sha1 직접 매핑됨
hash target.file.sha1 직접 매핑됨
fileSize target.file.size 직접 매핑됨
eachevent.processCommandLine target.process.command_line 이름 변경/매핑됨
processCommandLine target.process.command_line 직접 매핑됨
fileName target.process.file.names 병합됨
eachevent.sourceProcessCommandLine target.process.parent_process.command_line 이름 변경/매핑됨
sourceProcessCommandLine target.process.parent_process.command_line 직접 매핑됨
each_event.sourceProcessHash target.process.parent_process.file.sha1 이름 변경/매핑됨
sourceProcessHash target.process.parent_process.file.sha1 직접 매핑됨
sourceProcessPublisher_label target.resource.attribute.labels 병합됨
exposed_accountName target.user.attribute.labels 병합됨
exposed_domain target.user.attribute.labels 병합됨
exposed_source target.user.attribute.labels 병합됨
exposed_username target.user.attribute.labels 병합됨
sourceProcessUsername target.user.userid 직접 매핑됨
해당 사항 없음 metadata.event_type 상수: STATUS_UPDATE
해당 사항 없음 metadata.product_name 상수: EPM
해당 사항 없음 metadata.vendor_name 상수: CYBERARK
해당 사항 없음 principal.platform 상수: WINDOWS
해당 사항 없음 security_result.alert_state 상수: ALERTING

변경 로그

이 파서의 변경 로그 보기

도움이 더 필요하신가요? 커뮤니티 회원 및 Google SecOps 전문가에게 문의하여 답변을 받으세요.