收集 SAP BTP 記錄

支援語言:

本文說明如何使用 Cloud Storage V2,將 SAP Business Technology Platform (BTP) 記錄檔擷取至 Google Security Operations。

SAP Business Technology Platform (BTP) 是一個雲端平台,提供應用程式開發、整合、資料管理和分析功能。這項服務會產生安全稽核記錄、存取記錄和服務事件記錄,有助於監控平台活動及偵測安全威脅。Cloud Run 函式會依排程輪詢 SAP 稽核記錄管理服務的稽核記錄擷取 API,以 NDJSON 格式將記錄寫入 Cloud Storage bucket,然後 Google SecOps 會透過 Cloud Storage V2 資訊提供擷取這些記錄。

事前準備

請確認您已完成下列事前準備事項:

  • Google SecOps 執行個體
  • 已啟用 Cloud Storage API 的 Google Cloud 專案
  • 建立及管理 Cloud Storage bucket 的權限
  • 管理 Cloud Storage 值區身分與存取權管理 (IAM) 政策的權限
  • 建立 Cloud Run 服務、Pub/Sub 主題和 Cloud Scheduler 工作的權限
  • SAP BTP 的管理員存取權,並具備設定稽核記錄擷取的權限 (目標 Cloud Foundry 空間中的「空間開發人員」,以及在全域帳戶層級新增權利的能力)
  • SAP BTP 子帳戶適用的稽核記錄管理服務 (技術名稱:auditlog-management)

建立 Cloud Storage bucket

  1. 前往 Google Cloud 控制台
  2. 選取專案或建立新專案。
  3. 在導覽選單中,依序前往「Cloud Storage」>「Bucket」
  4. 按一下「建立值區」
  5. 請提供下列設定詳細資料:

    設定
    為 bucket 命名 輸入全域不重複的名稱 (例如 sap-btp-logs)
    位置類型 根據需求選擇 (區域、雙區域、多區域)
    位置 選取位置 (例如 us-central1)
    儲存空間級別 標準 (建議用於經常存取的記錄)
    存取控管 統一 (建議)
    保護工具 選用:啟用物件版本管理或保留政策
  6. 點選「建立」

收集 SAP BTP API 憑證

建立稽核記錄管理服務執行個體

  1. 登入 SAP BTP Cockpit
  2. 確認已將「稽核記錄管理服務」權利指派給子帳戶:在子帳戶檢視畫面中,依序前往「權利」>「編輯」>「新增服務方案」 (權利是從全域帳戶分配)。
  3. 前往子帳戶。
  4. 依序前往「服務」>「執行個體和訂閱項目」
  5. 點選「建立」
  6. 提供下列設定詳細資料:
    • 服務:選取「稽核記錄管理服務」(技術名稱:auditlog-management)。
    • 方案:選取「default」
    • 執行階段環境:選取「Cloud Foundry」
    • 聊天室:選取目標聊天室。
    • 「執行個體名稱」:輸入名稱 (例如 auditlog-management-secops)。
  7. 點選「建立」

建立服務車鑰

  1. 在 SAP BTP Cockpit 中,依序前往「Services」>「Instances and Subscriptions」,然後選取 auditlog-management 服務執行個體。
  2. 選擇「建立服務金鑰」
  3. 輸入名稱 (例如 google-secops-integration)。
  4. 點選「建立」
  5. 複製並妥善儲存服務車鑰中的下列詳細資料:

    • url:稽核記錄擷取要求的基準網址。
    • uaa.url:OAuth 伺服器基本網址。權杖端點為 <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 函式建立服務帳戶

Cloud Run 函式需要具備 Cloud Storage bucket 寫入權限,且可由 Pub/Sub 叫用的服務帳戶。

建立服務帳戶

  1. GCP 控制台中,依序前往「IAM & Admin」(IAM 與管理) >「Service Accounts」(服務帳戶)
  2. 按一下「Create Service Account」(建立服務帳戶)
  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 Invoker」
    5. 點選「+ 新增其他角色」
    6. 搜尋並選取「Cloud Functions Invoker」(Cloud Functions 叫用者)
  6. 按一下「繼續」
  7. 按一下「完成」

這些角色適用於:

  • Storage 物件管理員:將記錄檔寫入 Cloud Storage bucket,並管理狀態檔案
  • Cloud Run 叫用者:允許 Pub/Sub 叫用函式
  • Cloud Functions 叫用者:允許函式叫用

授予 Cloud Storage bucket 的 IAM 權限

授予服務帳戶 Cloud Storage 值區的寫入權限:

  1. 依序前往「Cloud Storage」>「Buckets」
  2. 按一下 bucket 名稱 (例如 sap-btp-logs)。
  3. 前往「權限」分頁標籤。
  4. 按一下「授予存取權」
  5. 提供下列設定詳細資料:
    • 新增主體:輸入服務帳戶電子郵件地址 (例如 sap-btp-collector-sa@your-project.iam.gserviceaccount.com)。
    • 指派角色:選取「Storage 物件管理員」
  6. 按一下 [儲存]

建立 Pub/Sub 主題

建立 Pub/Sub 主題,Cloud Scheduler 會將訊息發布至該主題,而 Cloud Run 函式會訂閱該主題。

  1. GCP Console 中,前往「Pub/Sub」>「Topics」(主題)
  2. 按一下「建立主題」
  3. 提供下列設定詳細資料:
    • 主題 ID:輸入 sap-btp-trigger
    • 其他設定保留預設值。
  4. 點選「建立」

建立 Cloud Run 函式來收集記錄

Cloud Run 函式會由 Cloud Scheduler 的 Pub/Sub 訊息觸發,從稽核記錄管理服務擷取 API 擷取稽核記錄,並將記錄寫入 Cloud Storage。

  1. 前往 GCP Console 的「Cloud Run」
  2. 按一下「Create service」(建立服務)
  3. 選取「函式」 (使用內嵌編輯器建立函式)。
  4. 在「設定」部分,提供下列設定詳細資料:

    設定
    服務名稱 sap-btp-collector
    區域 選取與 Cloud Storage bucket 相符的區域 (例如 us-central1)
    執行階段 選取 Python 3.12 以上版本
  5. 在「觸發條件 (選用)」部分:

    1. 按一下「+ 新增觸發條件」
    2. 選取「Cloud Pub/Sub」
    3. 在「選取 Cloud Pub/Sub 主題」中,選擇主題 sap-btp-trigger
    4. 按一下 [儲存]
  6. 在「Authentication」(驗證) 部分:

    1. 選取「需要驗證」
    2. 檢查 Identity and Access Management (IAM)
  7. 展開「Containers, Networking, Security」(容器、網路、安全性)

  8. 前往「安全性」分頁:

    • 服務帳戶:選取服務帳戶 sap-btp-collector-sa
  9. 前往「容器」分頁:

    1. 按一下「變數與密鑰」
    2. 針對每個環境變數,按一下「+ 新增變數」
    變數名稱 範例值 說明
    GCS_BUCKET sap-btp-logs Cloud Storage Bucket 名稱
    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 權杖端點網址
    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
    • 「Maximum number of instances」(執行個體數量上限):輸入 100 (或根據預期負載調整)。
  14. 點選「建立」

  15. 等待服務建立完成 (1 到 2 分鐘)。

  16. 服務建立完成後,系統會自動開啟內嵌程式碼編輯器

新增函式程式碼

  1. 在「函式進入點」中輸入 main
  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
      

    • 第二個檔案 - 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 主控台的「Cloud Scheduler」
  2. 點選「建立工作」
  3. 請提供下列設定詳細資料:

    設定
    名稱 sap-btp-collector-hourly
    區域 選取與 Cloud Run 函式相同的區域
    頻率 0 * * * * (每小時整點)
    時區 選取時區 (建議使用世界標準時間)
    目標類型 Pub/Sub
    主題 選取主題 sap-btp-trigger
    郵件內文 {} (空白 JSON 物件)
  4. 點選「建立」

排程頻率選項

根據記錄檔量和延遲時間要求選擇頻率:

頻率 Cron 運算式 用途
每 5 分鐘 */5 * * * * 高容量、低延遲
每 15 分鐘 */15 * * * * 中等
每小時 0 * * * * 標準 (建議)
每 6 小時 0 */6 * * * 少量、批次處理
每天 0 0 * * * 歷來資料集合

測試整合項目

  1. Cloud Scheduler 控制台中,找出您的工作 (sap-btp-collector-hourly)。
  2. 按一下「強制執行」即可手動觸發。
  3. 等待幾秒鐘,然後依序前往「Cloud Run」>「Services」>「sap-btp-collector」>「Logs」
  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 bucket (sap-btp-logs),確認稽核記錄已寫入。

如果記錄中顯示錯誤:

  • HTTP 401:檢查環境變數中的 OAuth 憑證,或權杖可能已過期 (函式會自動處理重新整理)
  • HTTP 403:確認服務金鑰屬於同一個子帳戶中的 auditlog-management 執行個體,且該子帳戶的記錄符合您的預期;使用者角色集合不適用於用戶端憑證權杖
  • HTTP 429:頻率限制 - 函式會自動重試,並延遲一段時間
  • 無法取得存取權杖:確認 SAP_UAA_URLSAP_CLIENT_IDSAP_CLIENT_SECRET 正確無誤

在 Google SecOps 中設定動態饋給,擷取 SAP BTP 記錄

  1. 依序前往「SIEM 設定」>「動態饋給」
  2. 按一下「新增動態消息」
  3. 按一下「設定單一動態饋給」
  4. 在「動態饋給名稱」欄位中輸入動態饋給名稱 (例如 SAP BTP Logs)。
  5. 選取「Google Cloud Storage V2」做為「來源類型」
  6. 選取「Sap Business Technology Platform」做為「記錄類型」
  7. 按一下「取得服務帳戶」。系統會顯示專屬服務帳戶電子郵件地址,例如:

    chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com
    
  8. 複製這個電子郵件地址,後續步驟會用到。

  9. 點選「下一步」

  10. 指定下列輸入參數的值:

    • 儲存空間 bucket URL:輸入 Cloud Storage bucket URI,並加上前置路徑:

      gs://sap-btp-logs/sap-btp/
      
      • 取代:
        • sap-btp-logs:Cloud Storage bucket 名稱。
        • sap-btp/:記錄檔的儲存路徑。
    • 來源刪除選項:根據偏好設定選取刪除選項:

      • 一律不刪除檔案:一律不刪除來源中的檔案 (建議用於測試)。
      • 刪除已轉移的檔案和空白目錄:成功擷取檔案後,從來源刪除檔案和空白目錄。
    • 檔案存在時間上限:包含在過去天數內修改的檔案 (預設為 180 天)。

    • 資產命名空間資產命名空間

    • 擷取標籤:要套用至這個動態饋給事件的標籤。

  11. 點選「下一步」

  12. 在「Finalize」(完成) 畫面中檢查新的動態饋給設定,然後按一下「Submit」(提交)

將 IAM 權限授予 Google SecOps 服務帳戶

Google SecOps 服務帳戶需要 Cloud Storage bucket 的兩個角色:Storage 物件檢視者,用於讀取記錄物件;以及 bucket 層級角色,用於讀取 bucket 中繼資料。

  1. 依序前往「Cloud Storage」>「Buckets」
  2. 按一下 bucket 名稱 (sap-btp-logs)。
  3. 前往「權限」分頁標籤。
  4. 按一下「授予存取權」
  5. 提供下列設定詳細資料:
    • 新增主體:貼上 Google SecOps 服務帳戶電子郵件地址。
    • 指派角色:選取下列兩個角色:
      • Storage 物件檢視者:讀取記錄檔物件。
      • Storage 舊版值區讀取者:讀取值區中繼資料。如果您選取「刪除已轉移的檔案和空目錄」刪除選項,請改為選取「Storage Legacy Bucket Writer」,這也會授予刪除權限。
  6. 按一下 [儲存]

UDM 對應表

記錄欄位 UDM 對應 邏輯
time metadata.event_timestamp 已剖析為 ISO8601
principal_present metadata.event_type 已對應:trueSTATUS_UPDATE
user_present metadata.event_type 已對應:trueUSER_RESOURCE_ACCESStrueUSER_UNCATEGORIZED
json_message_uuid metadata.product_log_id 直接對應
host principal.asset.hostname 直接對應
key principal.asset.ip 已對應:ipvalue
principal_ip principal.asset.ip 已合併
value principal.asset.ip 已合併
host principal.hostname 直接對應
key principal.ip 已對應:ipvalue
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 已對應:emailsvalue2userNamevalue1
key2 principal.user.email_addresses 已對應:valuevalue2
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_messagemessage_labelidattribute_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 對應:levelINFORMATIONALlevelMEDIUMlevelUNKNOWN_SEVERITY
level security_result.severity 已對應:INFOINFORMATIONAL
value security_result.severity 已對應:INFOINFORMATIONALWARNMEDIUM
level security_result.severity_details 直接對應
value1 target.resource.product_object_id 直接對應
key1 target.resource.resource_type 已對應:clusterIDCLUSTER
不適用 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 專業人員尋求解答。