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 functions の関数が各 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)。
    ストレージ クラス Standard(頻繁にアクセスされるログに推奨)
    アクセス制御 均一(推奨)
    保護ツール 省略可: オブジェクトのバージョニングまたは保持ポリシーを有効にする
  6. [作成] をクリックします。

CyberArk EPM 認証情報を収集する

Cloud Run 関数は、EPM ユーザーで EPM REST API にログインします。イベントを収集するセットへの閲覧権限を持つ専用ユーザーを作成します。

API ユーザーを作成する

  1. アカウント管理者として EPM 管理コンソールにログインします。
  2. [Administration] タイルをクリックします。
  3. [ユーザー] ページに移動し、[ユーザーを追加] をクリックします。
  4. 次の構成情報を指定します。
    • メールアドレス: 統合ユーザーのログイン名を入力します(例: secops-collector@example.com)。
    • パスワード: 12 ~ 128 文字のパスワードを入力します。
  5. [追加] をクリックします。
  6. ログイン名とパスワードを安全に保存します。これらは、Cloud Run functions の EPM_USERNAME 値と EPM_PASSWORD 値として使用します。

表示専用ロールを作成して割り当てる

  1. [管理] で [ロール] ページに移動し、[ロールを作成] をクリックします。
  2. 次の構成情報を指定します。
    • 名前: ロールの名前を入力します(例: SecOps view only)。
    • 権限グループ: [表示専用] を選択します。
    • セット: イベントを収集するセットをすべて選択します。
  3. [作成] をクリックします。
  4. [ロールの割り当て] ページに移動します。
  5. 作成したロールの行で、[その他の操作(...)] > [ユーザーの割り当てまたは割り当て解除] をクリックします。
  6. [Assign users] をクリックし、統合ユーザーを検索して選択し、[Assign] をクリックします。
  7. [保存] をクリックします。

EPM ログイン URL を確認する

EPM 認証 API は、リージョンのディスパッチャ サーバーによって提供されます。この関数は、この URL をログインにのみ使用します。他のすべての呼び出しは、ログイン レスポンスが返すマネージャー URL に送信されます。

リージョン ログイン URL
USA 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 functions のサービス アカウントを作成する

Cloud Run functions の関数には、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. [Storage オブジェクト管理者] を検索して選択します。
    3. [+ 別のロールを追加] をクリックします。
    4. [Cloud Run 起動元] を検索して選択します。
    5. [+ 別のロールを追加] をクリックします。
    6. [Cloud Functions 起動元] を検索して選択します。
  6. [続行] をクリックします。
  7. [完了] をクリックします。

これらのロールは、次の操作に必要です。

  • Storage オブジェクト管理者: 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)を入力します。
    • ロールを割り当てる: [Storage オブジェクト管理者] を選択します。
  6. [保存] をクリックします。

Pub/Sub トピックの作成

Cloud Scheduler がパブリッシュし、Cloud Run functions の関数がサブスクライブする 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 1 回の実行あたりの最大レコード数
    PAGE_SIZE 1000 1 ページあたりのレコード数(API の最大値は 1,000)
    LOOKBACK_HOURS 24 最初の実行時の初期ルックバック期間
    OVERLAP_MINUTES 15 ウォーターマークの前にウィンドウを再読み取りして、エージェントが遅れて報告したイベントをキャッチする
  11. [変数とシークレット] セクションで、[リクエスト] に移動します。

    • リクエストのタイムアウト: 「600」秒(10 分)と入力します。
  12. [設定] タブに移動します。

    • [リソース] セクションで、次の操作を行います。
      • メモリ: 512 MiB 以上を選択します。
      • CPU: 1 を選択します。
  13. [リビジョン スケーリング] セクションで、次の操作を行います。

    • [インスタンスの最小数]: 「0」と入力します。
    • [インスタンスの最大数]: 「1」と入力します。
  14. [作成] をクリックします。

  15. サービスが作成されるまで待ちます(1 ~ 2 分)。

  16. サービスが作成されると、インライン コードエディタが自動的に開きます。

関数のコードを追加する

  1. [エントリ ポイント] フィールドに「main」と入力します。
  2. インライン コードエディタで、次の 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
      

    • 2 つ目のファイル - requirements.txt:

      functions-framework==3.*
      google-cloud-storage==2.*
      urllib3>=2.0.0
      
  3. [デプロイ] をクリックして関数を保存し、デプロイします。

  4. デプロイが完了するまで待ちます(2 ~ 3 分)。

関数がイベントを収集する方法

  • この関数は、実行ごとに 1 回ログインし、ユーザーが表示できるセットを一覧表示します。また、eventDate のフィルタを使用して各セットの Get detailed raw events 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 functions の関数と同じリージョンを選択します。
    周波数 0 * * * *(1 時間ごと、毎正時)
    タイムゾーン タイムゾーンを選択(UTC を推奨)
    ターゲット タイプ Pub/Sub
    トピック Pub/Sub トピック cyberark-epm-trigger を選択します。
    メッセージ本文 {}(空の JSON オブジェクト)
  4. [作成] をクリックします。

スケジュール頻度のオプション

ログの量とレイテンシの要件に基づいて頻度を選択します。

頻度 CRON 式 ユースケース
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. [Add New Feed] をクリックします。
  3. [単一フィードを設定] をクリックします。
  4. [フィード名] フィールドに、フィードの名前を入力します(例: CyberArk EPM logs)。
  5. [Source type] として [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 バケット名で置き換えます。
    • Source deletion option: 必要に応じて削除オプションを選択します。

      • ファイルを削除しない: ソースからファイルを削除しません(テストにおすすめ)。
      • 転送されたファイルと空のディレクトリを削除する: 取得が正常に完了した後、ソースからファイルと空のディレクトリを削除します。

    • ファイルの最長存続期間: 過去数日間に変更されたファイルを含めます(デフォルトは 180 日)。

    • Asset namespace: アセットの名前空間。

    • Ingestion labels: このフィードのイベントに適用されるラベル。

  12. [次へ] をクリックします。

  13. [Finalize] 画面で新しいフィードの設定を確認し、[送信] をクリックします。

Google SecOps サービス アカウントに IAM 権限を付与する

Google SecOps サービス アカウントには、Cloud Storage バケットに対する 2 つのロールが必要です。ログ オブジェクトを読み取るためのストレージ オブジェクト閲覧者ロールと、バケット メタデータを読み取るためのバケットレベルのロールです。

  1. [Cloud Storage] > [バケット] に移動します。
  2. バケット名をクリックします。
  3. [権限] タブに移動します。
  4. [アクセス権を付与] をクリックします。
  5. 次の構成情報を指定します。
    • プリンシパルを追加: Google SecOps サービス アカウントのメールアドレスを貼り付けます。
    • ロールを割り当てる: 次の両方を選択します。
      • Storage オブジェクト閲覧者: ログ オブジェクトを読み取ります。
      • Storage レガシー バケット読み取り: バケット メタデータを読み取ります。削除オプションとして [転送されたファイルと空のディレクトリを削除する] を選択した場合は、代わりに [ストレージ レガシー バケット書き込み] を選択します。これにより、削除権限も付与されます。
  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 のプロフェッショナルから回答を得ることができます。