SAP BTP ログを収集する

以下でサポートされています。

このドキュメントでは、Cloud Storage V2 を使用して SAP Business Technology Platform(BTP)ログを Google Security Operations に取り込む方法について説明します。

SAP Business Technology Platform(BTP)は、アプリケーション開発、統合、データ マネジメント、分析機能を提供するクラウド プラットフォームです。セキュリティ監査ログ、アクセスログ、サービス イベントログが生成されます。これらは、プラットフォーム アクティビティのモニタリングとセキュリティ脅威の検出に不可欠です。Cloud Run functions の関数は、SAP Audit Log Management Service の監査ログ取得 API をスケジュールに従ってポーリングし、ログを NDJSON 形式で Cloud Storage バケットに書き込みます。Google SecOps は、Cloud Storage V2 フィードを介してそれらのログを取り込みます。

始める前に

次の前提条件を満たしていることを確認してください。

  • Google SecOps インスタンス
  • Cloud Storage API が有効になっている Google Cloud プロジェクト
  • Cloud Storage バケットを作成、管理する権限
  • Cloud Storage バケットの Identity and Access Management(IAM)ポリシーを管理する権限
  • Cloud Run サービス、Pub/Sub トピック、Cloud Scheduler ジョブを作成する権限
  • 監査ログの取得を構成する権限を持つ SAP BTP への管理者アクセス権(ターゲット Cloud Foundry スペースのスペース デベロッパー、およびグローバル アカウント レベルで利用資格を追加する機能)
  • SAP BTP サブアカウントに付与された監査ログ管理サービス(技術名: auditlog-management)

Cloud Storage バケットを作成する

  1. Google Cloud コンソールに移動します。
  2. プロジェクトを選択するか、新しいプロジェクトを作成します。
  3. ナビゲーション メニューで、[Cloud Storage] > [バケット] に移動します。
  4. [バケットを作成] をクリックします。
  5. 次の構成情報を提供してください。

    設定 値
    バケットに名前を付ける グローバルに一意の名前(sap-btp-logs など)を入力します。
    ロケーション タイプ ニーズに応じて選択します(リージョン、デュアルリージョン、マルチリージョン)。
    ロケーション ロケーションを選択します(例: us-central1)。
    ストレージ クラス Standard(頻繁にアクセスされるログに推奨)
    アクセス制御 均一(推奨)
    保護ツール 省略可: オブジェクトのバージョニングまたは保持ポリシーを有効にする
  6. [作成] をクリックします。

SAP BTP API 認証情報を収集する

Audit Log Management Service インスタンスを作成する

  1. SAP BTP Cockpit にログインします。
  2. Audit Log Management Service の利用資格がサブアカウントに割り当てられていることを確認します。サブアカウント ビューで、[Entitlements] > [Edit] > [Add Service Plans] に移動します(利用資格はグローバル アカウントから割り当てられます)。
  3. サブアカウントに移動します。
  4. [Services] > [Instances and Subscriptions] に移動します。
  5. [作成] をクリックします。
  6. 次の構成情報を指定します。
    • サービス: [監査ログ管理サービス](技術名: auditlog-management)を選択します。
    • Plan: [default] を選択します。
    • Runtime Environment: [Cloud Foundry] を選択します。
    • スペース: ターゲット スペースを選択します。
    • インスタンス名: 名前を入力します(例: auditlog-management-secops)。
  7. [作成] をクリックします。

サービスキーを作成する

  1. SAP BTP Cockpit で、[Services] > [Instances and Subscriptions] に移動し、auditlog-management サービス インスタンスを選択します。
  2. [Create Service Key] を選択します。
  3. 名前を入力します(例: google-secops-integration)。
  4. [作成] をクリックします。
  5. サービスキーから次の詳細をコピーして、安全な場所に保存します。

    • url: 監査ログ取得リクエストのベース URL。
    • uaa.url: OAuth サーバーのベース URL。トークン エンドポイントは <uaa.url>/oauth/token です。
    • uaa.clientid: OAuth クライアント ID。
    • uaa.clientsecret: OAuth クライアント シークレット。

テスト API へのアクセス

  • 統合に進む前に、認証情報をテストします。

    # Replace with your actual credentials from the service key
    UAA_URL="https://your-subdomain.authentication.region.hana.ondemand.com"
    CLIENT_ID="your-client-id"
    CLIENT_SECRET="your-client-secret"
    API_URL="https://auditlog-management.cfapps.us10.hana.ondemand.com"
    
    # Get OAuth token
    TOKEN=$(curl -s -X POST "${UAA_URL}/oauth/token" \
      -u "${CLIENT_ID}:${CLIENT_SECRET}" \
      -d "grant_type=client_credentials" \
      -H "Content-Type: application/x-www-form-urlencoded" | jq -r '.access_token')
    
    # Test API access: the API takes time_from/time_to in UTC without a
    # timezone suffix and returns a JSON array at the root. When the result
    # set is chunked, the next chunk's handle arrives in the "Paging"
    # response header.
    curl -v -H "Authorization: Bearer ${TOKEN}" \
      "${API_URL}/auditlog/v2/auditlogrecords?time_from=2026-08-07T00:00:00&time_to=2026-08-07T01:00:00"
    

Cloud Run functions のサービス アカウントを作成する

Cloud Run functions の関数には、Cloud Storage バケットへの書き込み権限と、Pub/Sub による呼び出し権限を持つサービス アカウントが必要です。

サービス アカウントを作成する

  1. GCP コンソールで、[IAM と管理] > [サービス アカウント] に移動します。
  2. [サービス アカウントを作成] をクリックします。
  3. 次の構成情報を指定します。
    • サービス アカウント名: 「sap-btp-collector-sa」と入力します。
    • サービス アカウントの説明: 「Service account for Cloud Run function to collect SAP BTP 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. [Cloud Storage] > [バケット] に移動します。
  2. バケット名(sap-btp-logs など)をクリックします。
  3. [権限] タブに移動します。
  4. [アクセス権を付与] をクリックします。
  5. 次の構成情報を指定します。
    • プリンシパルを追加: サービス アカウントのメールアドレス(例: sap-btp-collector-sa@your-project.iam.gserviceaccount.com)を入力します。
    • ロールを割り当てる: [Storage オブジェクト管理者] を選択します。
  6. [保存] をクリックします。

Pub/Sub トピックの作成

Cloud Scheduler がパブリッシュし、Cloud Run functions の関数がサブスクライブする Pub/Sub トピックを作成します。

  1. GCP コンソールで、[Pub/Sub] > [トピック] に移動します。
  2. [トピックを作成] をクリックします。
  3. 次の構成情報を指定します。
    • トピック ID: 「sap-btp-trigger」と入力します。
    • その他の設定はデフォルトのままにします。
  4. [作成] をクリックします。

ログを収集する Cloud Run 関数を作成する

Cloud Run 関数は、Cloud Scheduler からの Pub/Sub メッセージによってトリガーされ、Audit Log Management Service 取得 API から監査ログを取得して Cloud Storage に書き込みます。

  1. GCP Console で Cloud Run に移動します。
  2. [サービスを作成] をクリックします。
  3. [関数](インライン編集を使用して関数を作成する)を選択します。
  4. [構成] セクションで、次の構成の詳細を指定します。

    設定 値
    サービス名 sap-btp-collector
    リージョン Cloud Storage バケットに一致するリージョンを選択します(例: us-central1)。
    ランタイム [Python 3.12] 以降を選択します。
  5. [トリガー(省略可)] セクションで、次の操作を行います。

    1. [+ トリガーを追加] をクリックします。
    2. [Cloud Pub/Sub] を選択します。
    3. [Cloud Pub/Sub トピックを選択してください] で、トピック sap-btp-trigger を選択します。
    4. [保存] をクリックします。
  6. [認証] セクションで、次の操作を行います。

    1. [認証が必要] を選択します。
    2. Identity and Access Management(IAM)を確認します。
  7. [コンテナ、ネットワーキング、セキュリティ] を開きます。

  8. [セキュリティ] タブに移動します。

    • サービス アカウント: サービス アカウント sap-btp-collector-sa を選択します。
  9. [コンテナ] タブに移動します。

    1. [変数とシークレット] をクリックします。
    2. 環境変数ごとに [+ 変数を追加] をクリックします。
    変数名 値の例 説明
    GCS_BUCKET sap-btp-logs Cloud Storage バケットの名前
    GCS_PREFIX sap-btp ログファイルの接頭辞
    STATE_KEY sap-btp-state.json 状態ファイルのパス(ログ接頭辞の外側)
    SAP_API_URL https://auditlog-management.cfapps.us10.hana.ondemand.com サービスキーの url 値
    SAP_UAA_URL https://your-subdomain.authentication.region.hana.ondemand.com OAuth トークン エンドポイント URL
    SAP_CLIENT_ID your-client-id OAuth クライアント ID
    SAP_CLIENT_SECRET your-client-secret OAuth クライアント シークレット
    LOOKBACK_HOURS 24 最初のルックバック期間
  10. [変数とシークレット] タブで、[リクエスト] に移動します。

    • リクエスト タイムアウト: 600 秒(10 分)を入力します。
  11. [コンテナ] の [設定] タブに移動します。

    • [リソース] セクションで、次の操作を行います。
      • メモリ: 512 MiB 以上を選択します。
      • CPU: [1] を選択します。
    • [完了] をクリックします。
  12. [実行環境] に移動します。

    • [デフォルト](推奨)を選択します。
  13. [リビジョン スケーリング] セクションで、次の操作を行います。

    • [インスタンスの最小数] に「0」と入力します。
    • [インスタンスの最大数]: 「100」と入力します(または、予想される負荷に基づいて調整します)。
  14. [作成] をクリックします。

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

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

関数のコードを追加する

  1. [関数のエントリ ポイント] に「main」と入力します。
  2. インライン コードエディタで、次の 2 つのファイルを作成します。

    • 最初のファイル - main.py:

      import functions_framework
      from google.cloud import storage
      import hashlib
      import json
      import os
      import urllib3
      from datetime import datetime, timezone, timedelta
      import time
      import base64
      import uuid
      
      # Initialize HTTP client with timeouts
      http = urllib3.PoolManager(
          timeout=urllib3.Timeout(connect=5.0, read=30.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', 'sap-btp')
      STATE_KEY = os.environ.get('STATE_KEY', 'sap-btp-state.json')
      SEEN_KEY = STATE_KEY + '.seen'
      API_URL = os.environ.get('SAP_API_URL')
      UAA_URL = os.environ.get('SAP_UAA_URL')
      CLIENT_ID = os.environ.get('SAP_CLIENT_ID')
      CLIENT_SECRET = os.environ.get('SAP_CLIENT_SECRET')
      LOOKBACK_HOURS = int(os.environ.get('LOOKBACK_HOURS', '24'))
      
      def parse_datetime(value: str) -> datetime:
          """Parse ISO datetime string to datetime object."""
          if value.endswith("Z"):
              value = value[:-1] + "+00:00"
          return datetime.fromisoformat(value)
      
      # message_uuid is the identifier of an audit log record; the parser maps it to
      # metadata.product_log_id.
      ID_FIELDS = ('message_uuid',)
      
      def event_keys(event):
          """Return every identity this event can be recognised by."""
          keys = {'sha256:' + hashlib.sha256(
              json.dumps(event, sort_keys=True, ensure_ascii=False).encode('utf-8')
          ).hexdigest()}
          for field in ID_FIELDS:
              value = event.get(field)
              if value:
                  keys.add(f'{field}:{value}')
          return keys
      
      def get_oauth_token():
          """Get OAuth 2.0 access token using client credentials flow."""
          token_url = f"{UAA_URL.rstrip('/')}/oauth/token"
      
          credentials = f"{CLIENT_ID}:{CLIENT_SECRET}"
          encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
      
          headers = {
              'Authorization': f'Basic {encoded_credentials}',
              'Content-Type': 'application/x-www-form-urlencoded',
              'Accept': 'application/json'
          }
      
          body = 'grant_type=client_credentials'
      
          backoff = 1.0
          max_retries = 3
      
          for attempt in range(max_retries):
              response = http.request('POST', token_url, body=body, headers=headers)
      
              if response.status == 429:
                  retry_after = int(response.headers.get('Retry-After', str(int(backoff))))
                  print(f"Rate limited (429) on token request. Retrying after {retry_after}s...")
                  time.sleep(retry_after)
                  backoff = min(backoff * 2, 30.0)
                  continue
      
              if response.status != 200:
                  raise RuntimeError(f"Failed to get access token: {response.status} - {response.data.decode('utf-8')}")
      
              data = json.loads(response.data.decode('utf-8'))
              return data['access_token']
      
          raise RuntimeError(f"Failed to get token after {max_retries} retries due to rate limiting")
      
      @functions_framework.cloud_event
      def main(cloud_event):
          """
          Cloud Run function triggered by Pub/Sub to fetch SAP BTP
          audit logs and write to GCS.
      
          Args:
              cloud_event: CloudEvent object containing Pub/Sub message
          """
      
          if not all([GCS_BUCKET, API_URL, UAA_URL, CLIENT_ID, CLIENT_SECRET]):
              # 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')
      
          try:
              bucket = storage_client.bucket(GCS_BUCKET)
      
              # Load state
              state = load_state(bucket, STATE_KEY)
              seen_keys = load_seen(bucket, SEEN_KEY)
      
              # Determine time window
              now = datetime.now(timezone.utc)
              last_time = None
      
              if isinstance(state, dict) and state.get("last_event_time"):
                  try:
                      last_time = parse_datetime(state["last_event_time"])
                      last_time = last_time - timedelta(minutes=2)
                  except Exception as e:
                      print(f"Warning: Could not parse last_event_time: {e}")
      
              if last_time is None:
                  last_time = now - timedelta(hours=LOOKBACK_HOURS)
      
              print(f"Fetching audit logs from {last_time.isoformat()} to {now.isoformat()}")
      
              # Get OAuth token
              token = get_oauth_token()
      
              # Fetch audit logs
              records, newest_event_time = fetch_audit_logs(
                  token=token,
                  start_time=last_time,
                  end_time=now,
              )
      
              # Drop the events already written by a previous run (overlap window)
              fresh = [r for r in records if not (event_keys(r) & seen_keys)]
      
              if not fresh:
                  print("No new audit log records found.")
                  return
      
              # Write to GCS as NDJSON
              timestamp = now.strftime('%Y%m%d_%H%M%S')
              # The random suffix keeps concurrent executions (Pub/Sub delivers at
              # least once) from overwriting each other's object within one second.
              object_key = f"{GCS_PREFIX}/audit_{timestamp}_{uuid.uuid4().hex[:8]}.ndjson"
              blob = bucket.blob(object_key)
      
              ndjson = '\n'.join([json.dumps(record, ensure_ascii=False) for record in fresh]) + '\n'
              blob.upload_from_string(ndjson, content_type='application/x-ndjson')
      
              print(f"Wrote {len(fresh)} records to gs://{GCS_BUCKET}/{object_key}")
      
              # Remember every fetched record so the next overlap window is deduplicated
              save_seen(bucket, SEEN_KEY, records)
      
              # Update state with newest event time. The watermark must be an event
              # timestamp, never wall clock: a wall-clock watermark skips every event
              # the vendor indexes late.
              if not newest_event_time:
                  raise RuntimeError('Records were returned but no event timestamp could be parsed')
              save_state(bucket, STATE_KEY, newest_event_time)
      
              print(f"Successfully processed {len(fresh)} records")
      
          except Exception as e:
              print(f'Error processing audit logs: {str(e)}')
              raise
      
      def load_state(bucket, key):
          """Load state from GCS."""
          try:
              blob = bucket.blob(key)
              if blob.exists():
                  state_data = blob.download_as_text()
                  return json.loads(state_data)
          except Exception as e:
              print(f"Warning: Could not load state: {e}")
              raise
      
          return {}
      
      def save_state(bucket, key, last_event_time_iso: str):
          """Save the last event timestamp to GCS state file."""
          try:
              state = {'last_event_time': last_event_time_iso}
              blob = bucket.blob(key)
              blob.upload_from_string(
                  json.dumps(state, indent=2),
                  content_type='application/json'
              )
              print(f"Saved state: last_event_time={last_event_time_iso}")
          except Exception as e:
              print(f"Warning: Could not save state: {e}")
              raise
      
      def load_seen(bucket, key):
          """Load the event keys written by the previous run."""
          try:
              blob = bucket.blob(key)
              if blob.exists():
                  return set(json.loads(blob.download_as_text()))
          except Exception as e:
              print(f"Warning: Could not load seen keys: {e}")
              raise
      
          return set()
      
      def save_seen(bucket, key, records):
          """Save the keys of every fetched record for the next overlap window."""
          try:
              keys = set()
              for record in records:
                  keys |= event_keys(record)
              blob = bucket.blob(key)
              blob.upload_from_string(
                  json.dumps(sorted(keys)),
                  content_type='application/json'
              )
              print(f"Saved {len(keys)} seen keys")
          except Exception as e:
              print(f"Warning: Could not save seen keys: {e}")
              raise
      
      def fetch_audit_logs(token: str, start_time: datetime, end_time: datetime):
          """
          Fetch audit logs from the Audit Log Management Service retrieval API.
      
          The API takes time_from/time_to in UTC without a timezone designator and
          returns a JSON array at the root (HTTP 204 when the window is empty).
          When the result set is chunked, the next chunk's handle arrives in the
          "Paging" response header as handle=<value> and is passed back as the
          handle query parameter; the server chunk size is fixed at 500 records.
      
          Args:
              token: OAuth 2.0 access token
              start_time: Start time for log query
              end_time: End time for log query
      
          Returns:
              Tuple of (records list, newest_event_time ISO string)
      
          Raises:
              RuntimeError: on any API failure, so a failed fetch can never be
                  mistaken for an empty result.
          """
          base_url = API_URL.rstrip('/')
          endpoint = f"{base_url}/auditlog/v2/auditlogrecords"
      
          headers = {
              'Authorization': f'Bearer {token}',
              'Accept': 'application/json',
              'User-Agent': 'GoogleSecOps-SAPBTPCollector/1.0'
          }
      
          records = []
          newest_time = None
          page_num = 0
          backoff = 1.0
          rate_limit_retries = 0
          token_refreshed = False
      
          # The API expects UTC timestamps with no timezone suffix.
          time_from = start_time.strftime('%Y-%m-%dT%H:%M:%S')
          time_to = end_time.strftime('%Y-%m-%dT%H:%M:%S')
          handle = None
      
          from urllib.parse import urlencode
      
          while True:
              page_num += 1
      
              # Rebuild the full parameter set on every request.
              params = {'time_from': time_from, 'time_to': time_to}
              if handle:
                  params['handle'] = handle
              url = f"{endpoint}?{urlencode(params)}"
      
              response = http.request('GET', url, headers=headers)
      
              # The documented rate limit is 4 requests per second (burst 20).
              if response.status == 429:
                  rate_limit_retries += 1
                  if rate_limit_retries > 5:
                      raise RuntimeError('Rate limited repeatedly; giving up without advancing the watermark')
                  retry_after = response.headers.get('Retry-After')
                  try:
                      delay = float(retry_after) if retry_after else backoff
                  except (TypeError, ValueError):
                      delay = backoff
                  delay = min(max(delay, 1.0), 60.0)
                  print(f"Rate limited (429). Retrying after {delay}s...")
                  time.sleep(delay)
                  backoff = min(backoff * 2, 30.0)
                  continue
      
              backoff = 1.0
              rate_limit_retries = 0
      
              if response.status == 401:
                  # One refresh per run: a second consecutive 401 means the audit
                  # service rejects tokens UAA still issues, and retrying forever
                  # would hammer both services until the platform kills the run.
                  if token_refreshed:
                      raise RuntimeError('Audit log request still unauthorized after a token refresh')
                  print("Token expired, refreshing...")
                  token = get_oauth_token()
                  headers['Authorization'] = f'Bearer {token}'
                  token_refreshed = True
                  continue
      
              token_refreshed = False
      
              if response.status == 204:
                  # Documented empty result for the requested window.
                  break
      
              if response.status != 200:
                  raise RuntimeError(
                      f"Audit log request failed: {response.status} - "
                      f"{response.data.decode('utf-8')}"
                  )
      
              data = json.loads(response.data.decode('utf-8'))
      
              # The records arrive as a JSON array at the root. Tolerate wrapped
              # shapes defensively, but never call .get on a list: doing so
              # crashed previous revisions of this function.
              if isinstance(data, list):
                  page_results = data
              elif isinstance(data, dict):
                  page_results = data.get('value', data.get('results', []))
              else:
                  page_results = []
      
              print(f"Page {page_num}: Retrieved {len(page_results)} audit records")
              records.extend(page_results)
      
              # Track newest event time. Parse before assigning: an unparseable
              # stamp must never become the persisted watermark.
              for record in page_results:
                  event_time = record.get('time') or record.get('timestamp')
                  if not event_time:
                      continue
                  try:
                      parsed = parse_datetime(event_time)
                  except Exception as e:
                      print(f"Warning: Could not parse event time: {e}")
                      continue
                  if newest_time is None or parsed > parse_datetime(newest_time):
                      newest_time = event_time
      
              # More chunks are signaled only by the Paging response header.
              paging = response.headers.get('Paging') or response.headers.get('paging') or ''
              handle = paging.split('=', 1)[1] if '=' in paging else None
              if not handle:
                  break
      
          print(f"Retrieved {len(records)} total audit records 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 分)。

Cloud Scheduler ジョブを作成する

Cloud Scheduler は、定期的に Pub/Sub トピックにメッセージをパブリッシュし、Cloud Run 関数をトリガーします。

  1. GCP Console で、[Cloud Scheduler] に移動します。
  2. [ジョブを作成] をクリックします。
  3. 次の構成情報を提供してください。

    設定 値
    名前 sap-btp-collector-hourly
    リージョン Cloud Run functions の関数と同じリージョンを選択します。
    周波数 0 * * * *(1 時間ごと、毎正時)
    タイムゾーン タイムゾーンを選択(UTC を推奨)
    ターゲット タイプ Pub/Sub
    トピック トピック sap-btp-trigger を選択します。
    メッセージ本文 {}(空の JSON オブジェクト)
  4. [作成] をクリックします。

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

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

頻度 CRON 式 ユースケース
5 分おき */5 * * * * 大容量、低レイテンシ
15 分ごと */15 * * * * 検索量が普通
1 時間ごと 0 * * * * 標準(推奨)
6 時間ごと 0 */6 * * * 少量のバッチ処理
毎日 0 0 * * * 過去のデータの収集

統合をテストする

  1. Cloud Scheduler コンソールで、ジョブ(sap-btp-collector-hourly)を見つけます。
  2. [強制実行] をクリックして手動でトリガーします。
  3. 数秒待ってから、[Cloud Run] > [サービス] > [sap-btp-collector] > [ログ] に移動します。
  4. 関数が正常に実行されたことを確認します。以下のものを探します。

    Fetching audit logs from YYYY-MM-DDTHH:MM:SS+00:00 to YYYY-MM-DDTHH:MM:SS+00:00
    Page 1: Retrieved X audit records
    Wrote X records to gs://sap-btp-logs/sap-btp/audit_YYYYMMDD_HHMMSS.ndjson
    Successfully processed X records
    
  5. Cloud Storage バケット(sap-btp-logs)をチェックして、監査ログが書き込まれたことを確認します。

ログにエラーが表示される場合:

  • HTTP 401: 環境変数内の OAuth 認証情報を確認します。または、トークンの有効期限が切れている可能性があります(関数は更新を自動的に処理します)。
  • HTTP 403: サービスキーが、ログを想定している同じサブアカウントの auditlog-management インスタンスに属していることを確認します。ユーザーロール コレクションは、クライアント認証情報トークンには適用されません。
  • HTTP 429: レート制限 - 関数はバックオフを使用して自動的に再試行します
  • Failed to get access token: SAP_UAA_URL、SAP_CLIENT_ID、SAP_CLIENT_SECRET が正しいことを確認します。

SAP BTP のログを取り込むように Google SecOps でフィードを構成する

  1. [設定] > [データ管理] > [フィード] に移動します。SIEM のみのプラットフォームを使用している場合は、[設定] > [フィード] に移動します。
  2. [Add New Feed] をクリックします。
  3. [単一フィードを設定] をクリックします。
  4. [フィード名] フィールドに、フィードの名前を入力します(例: SAP BTP Logs)。
  5. [Source type] として [Google Cloud Storage V2] を選択します。
  6. [ログタイプ] として [Sap Business Technology Platform] を選択します。
  7. [サービス アカウントを取得する] をクリックします。一意のサービス アカウントのメールアドレスが表示されます。例:

    chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com
    
  8. このメールアドレスをコピーします。次のステップでこれを使用します。

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

  10. 次の入力パラメータの値を指定します。

    • ストレージ バケットの URL: 接頭辞パスを含む Cloud Storage バケット URI を入力します。

      gs://sap-btp-logs/sap-btp/
      
      • 次のように置き換えます。
        • sap-btp-logs: Cloud Storage バケット名。
        • sap-btp/: ログが保存されるパス。
    • Source deletion option: 必要に応じて削除オプションを選択します。

      • ファイルを削除しない: ソースからファイルを削除しません(テストにおすすめ)。
      • 転送されたファイルと空のディレクトリを削除する: 取得が正常に完了した後、ソースからファイルと空のディレクトリを削除します。
    • ファイルの最長存続期間: 過去数日間に変更されたファイルを含めます(デフォルトは 180 日)。

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

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

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

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

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

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

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

UDM マッピング テーブル

ログフィールド UDM マッピング ロジック
time metadata.event_timestamp ISO8601 として解析
principal_present metadata.event_type マッピング済み: true → STATUS_UPDATE
user_present metadata.event_type マッピング済み: true → USER_RESOURCE_ACCESS、true → USER_UNCATEGORIZED
json_message_uuid metadata.product_log_id 直接マッピングされます。
host principal.asset.hostname 直接マッピングされます。
key principal.asset.ip マッピング済み: ip → value
principal_ip principal.asset.ip 統合済み
value principal.asset.ip 統合済み
host principal.hostname 直接マッピングされます。
key principal.ip マッピング済み: ip → value
principal_ip principal.ip 統合済み
value principal.ip 統合済み
principal_user_role principal.user.attribute.roles 統合済み
key principal.user.email_addresses マッピング済み: "new","old" → value2、"new","old" → value1
key1 principal.user.email_addresses マッピング済み: emails → value2、userName → value1
key2 principal.user.email_addresses マッピング済み: value → value2
value1 principal.user.email_addresses マッピング済み: ^.+@.+$ → value1
value2 principal.user.email_addresses 統合済み
user principal.user.user_display_name 直接マッピングされます。
json_message.data_subject.id.userid principal.user.userid 直接マッピングされます。
value1 principal.user.userid 直接マッピングされます。
category security_result.category_details 統合済み
als_service_id_label security_result.detection_fields 統合済み
app_or_service_id_label security_result.detection_fields 統合済み
attri_label security_result.detection_fields 統合済み
attribute_label security_result.detection_fields 統合済み
attribute_label1 security_result.detection_fields 統合済み
custom_status_label security_result.detection_fields 統合済み
custom_success_label security_result.detection_fields 統合済み
custom_type_label security_result.detection_fields 統合済み
desc_label security_result.detection_fields 統合済み
format_version_label security_result.detection_fields 統合済み
key security_result.detection_fields マッピング済み: json_message → message_label、id → attribute_label、"new","old" → `attribu...
message_id_label security_result.detection_fields 統合済み
message_label security_result.detection_fields 統合済み
message_label_json_message security_result.detection_fields 統合済み
message_label_msgId security_result.detection_fields 統合済み
message_label_msgNo security_result.detection_fields 統合済み
message_label_uuid security_result.detection_fields 統合済み
message_label_version security_result.detection_fields 統合済み
org_id_label security_result.detection_fields 統合済み
space_id_label security_result.detection_fields 統合済み
tenant_label security_result.detection_fields 統合済み
key security_result.severity マッピング済み: level → INFORMATIONAL、level → MEDIUM、level → UNKNOWN_SEVERITY
level security_result.severity マッピング済み: INFO → INFORMATIONAL
value security_result.severity マッピング済み: INFO → INFORMATIONAL、WARN → MEDIUM
level security_result.severity_details 直接マッピングされます。
value1 target.resource.product_object_id 直接マッピングされます。
key1 target.resource.resource_type マッピング済み: clusterID → CLUSTER
なし metadata.event_type 定数: GENERIC_EVENT
なし metadata.product_name 定数: SAP_BTP
なし metadata.vendor_name 定数: SAP_BTP
なし security_result.severity 定数: INFORMATIONAL
なし target.resource.resource_type 定数: CLUSTER

変更ログ

このパーサーの変更ログを表示する

さらにサポートが必要な場合 コミュニティ メンバーや Google SecOps のプロフェッショナルから回答を得ることができます。