收集 IBM Security Verify SaaS 日志

支持的平台:

本文档介绍了如何使用 Google Cloud Storage V2 将 IBM Security Verify SaaS 日志注入到 Google Security Operations。

IBM Security Verify SaaS 是一个基于云的身份和访问权限管理平台,提供 SSO、MFA 和自适应访问权限控制功能。它会针对身份验证事件、政策决策和用户生命周期管理生成审核日志。

准备工作

请确保满足以下前提条件:

  • Google SecOps 实例
  • 启用了 Cloud Storage API 的 GCP 项目
  • 创建和管理 GCS 存储桶的权限
  • 管理 GCS 存储桶的 IAM 政策的权限
  • 创建 Cloud Run 服务、Pub/Sub 主题和 Cloud Scheduler 作业的权限
  • 对 IBM Security Verify SaaS 的特权访问权限(管理员角色)

创建 Google Cloud Storage 存储桶

  1. 前往 Google Cloud 控制台。
  2. 选择您的项目或创建一个新项目。
  3. 在导航菜单中,依次前往 Cloud Storage > 存储桶。
  4. 点击创建存储分区。
  5. 提供以下配置详细信息:

    设置 值
    为存储桶命名 输入一个全局唯一的名称(例如 ibm-verify-saas-logs)
    位置类型 根据您的需求进行选择(区域级、双区域级、多区域级)
    位置 选择位置(例如 us-central1)
    存储类别 标准(建议用于频繁访问的日志)
    访问权限控制 均匀(推荐)
    保护工具 可选:启用对象版本控制或保留政策
  6. 点击创建。

收集 IBM Security Verify SaaS API 凭据

创建 API 客户端

  1. 登录 IBM Security Verify 管理控制台。
  2. 依次前往安全性 > API 访问权限。
  3. 点击添加 API 客户端。
  4. 输入 API 客户端的名称(例如 Google Security Operations Integration)。
  5. 分配以下权限:
    • 读取事件日志
    • 阅读报告
  6. 点击保存。
  7. 请复制以下详细信息并将其保存在安全的位置:
    • 客户端 ID:API 客户端标识符。
    • 客户端密钥:API 客户端密钥。

确定租户网址

API 基本网址源自您的 IBM Security Verify 租户。格式为:

控制台网址 API 基本网址
https://YOUR_TENANT.verify.ibm.com https://YOUR_TENANT.verify.ibm.com
  • 将 YOUR_TENANT 替换为您的实际 IBM Security Verify 租户名称。

验证权限

如需验证 API 客户端是否具有所需的权限,请执行以下操作:

  1. 登录 IBM Security Verify 管理控制台。
  2. 依次前往安全性 > API 访问权限。
  3. 点击 API 客户端名称。
  4. 验证读取事件日志和读取报告权限是否已启用。
  5. 如果缺少权限,请与 IBM Security Verify 管理员联系。

测试 API 访问权限

  • 在继续进行集成之前,请测试您的凭据:

    # Replace with your actual credentials
    CLIENT_ID="your-client-id"
    CLIENT_SECRET="your-client-secret"
    TENANT_URL="https://YOUR_TENANT.verify.ibm.com"
    
    # Get OAuth token
    TOKEN=$(curl -s -X POST "${TENANT_URL}/v1.0/endpoint/default/token" \
      -H "Content-Type: application/x-www-form-urlencoded" \
      -d "grant_type=client_credentials&client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}" \
      | jq -r '.access_token')
    
    # Test API access
    curl -v -H "Authorization: Bearer ${TOKEN}" "${TENANT_URL}/v1.0/events?size=1"
    

为 Cloud Run 函数创建服务账号

Cloud Run 函数需要一个服务账号,该账号具有写入 GCS 存储桶和被 Pub/Sub 调用的权限。

创建服务账号

  1. 在 GCP 控制台中,依次前往 IAM 和管理 > 服务账号。
  2. 点击创建服务账号。
  3. 提供以下配置详细信息:
    • 服务账号名称:输入 ibm-verify-collector-sa。
    • 服务账号说明:输入 Service account for Cloud Run function to collect IBM Security Verify SaaS logs。
  4. 点击创建并继续。
  5. 在向此服务账号授予对项目的访问权限部分,添加以下角色:
    1. 点击选择角色。
    2. 搜索并选择 Storage Object Admin。
    3. 点击 + 添加其他角色。
    4. 搜索并选择 Cloud Run Invoker。
    5. 点击 + 添加其他角色。
    6. 搜索并选择 Cloud Functions Invoker。
  6. 点击继续。
  7. 点击完成。

以下操作需要这些角色:

  • Storage Object Admin:将日志写入 GCS 存储桶并管理状态文件
  • Cloud Run Invoker:允许 Pub/Sub 调用函数
  • Cloud Functions Invoker:允许调用函数

授予对 GCS 存储桶的 IAM 权限

向服务账号授予对 GCS 存储桶的写入权限:

  1. 前往 Cloud Storage > 存储桶。
  2. 点击您的存储桶名称(例如 ibm-verify-saas-logs)。
  3. 前往权限标签页。
  4. 点击授予访问权限。
  5. 提供以下配置详细信息:
    • 添加主账号:输入服务账号电子邮件地址(例如 ibm-verify-collector-sa@your-project.iam.gserviceaccount.com)。
    • 分配角色:选择 Storage Object Admin。
  6. 点击保存。

创建 Pub/Sub 主题

创建一个 Pub/Sub 主题,供 Cloud Scheduler 发布消息,并供 Cloud Run 函数订阅。

  1. 在 GCP 控制台中,前往 Pub/Sub > 主题。
  2. 点击创建主题。
  3. 提供以下配置详细信息:
    • 主题 ID:输入 ibm-verify-trigger。
    • 将其他设置保留为默认值。
  4. 点击创建。

创建 Cloud Run 函数以收集日志

Cloud Run 函数将由来自 Cloud Scheduler 的 Pub/Sub 消息触发,以从 IBM Security Verify SaaS API 中提取日志并将其写入 GCS。

  1. 在 GCP 控制台中,前往 Cloud Run。
  2. 点击创建服务。
  3. 选择函数(使用内嵌编辑器创建函数)。
  4. 在配置部分中,提供以下配置详细信息:

    设置 值
    Service 名称 ibm-verify-collector
    区域 选择与您的 GCS 存储桶匹配的区域(例如 us-central1)
    运行时 选择 Python 3.12 或更高版本
  5. 在触发器(可选)部分中:

    1. 点击 + 添加触发器。
    2. 选择 Cloud Pub/Sub。
    3. 在选择 Cloud Pub/Sub 主题中,选择主题 ibm-verify-trigger。
    4. 点击保存。
  6. 在身份验证部分中:

    1. 选择需要进行身份验证。
    2. 检查 Identity and Access Management (IAM)。
  7. 向下滚动并展开容器、网络、安全性。

  8. 前往安全标签页:

    • 服务账号:选择服务账号 ibm-verify-collector-sa。
  9. 前往容器标签页:

    1. 点击变量和密钥。
    2. 为每个环境变量点击 + 添加变量:
    变量名称 示例值 说明
    GCS_BUCKET ibm-verify-saas-logs GCS 存储桶名称
    GCS_PREFIX ibm-verify 日志文件的前缀
    STATE_KEY ibm-verify/state.json 状态文件路径
    TENANT_URL https://YOUR_TENANT.verify.ibm.com IBM Security Verify 租户网址
    CLIENT_ID your-client-id API 客户端 ID
    CLIENT_SECRET your-client-secret API 客户端密钥
    MAX_RECORDS 10000 每次运行的记录数上限
    PAGE_SIZE 1000 每页记录数
    LOOKBACK_HOURS 24 初始回溯期
  10. 在变量和 Secret 标签页中,向下滚动到请求:

    • 请求超时:输入 600 秒(10 分钟)。
  11. 前往容器中的设置标签页:

    • 在资源部分中:
      • 内存:选择 512 MiB 或更高值。
      • CPU:选择 1。
  12. 在修订版本伸缩部分中:

    • 实例数下限:输入 0。
    • 实例数上限:输入 100(或根据预期负载进行调整)。
  13. 点击创建。

  14. 等待服务创建完成(1-2 分钟)。

  15. 创建服务后,系统会自动打开内嵌代码编辑器。

添加函数代码

  1. 在函数入口点中输入 main。
  2. 在内嵌代码编辑器中,创建两个文件:

    • 第一个文件 - main.py::

      import functions_framework
      from google.cloud import storage
      import json
      import os
      import urllib3
      from datetime import datetime, timezone, timedelta
      import time
      import base64
      
      # 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', 'ibm-verify')
      STATE_KEY = os.environ.get('STATE_KEY', 'ibm-verify/state.json')
      TENANT_URL = os.environ.get('TENANT_URL', '').rstrip('/')
      CLIENT_ID = os.environ.get('CLIENT_ID', '')
      CLIENT_SECRET = os.environ.get('CLIENT_SECRET', '')
      MAX_RECORDS = int(os.environ.get('MAX_RECORDS', '10000'))
      PAGE_SIZE = int(os.environ.get('PAGE_SIZE', '1000'))
      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)
      
      def get_token():
        """Get OAuth 2.0 access token using client credentials flow."""
        token_url = f"{TENANT_URL}/v1.0/endpoint/default/token"
      
        body = f"grant_type=client_credentials&client_id={CLIENT_ID}&client_secret={CLIENT_SECRET}"
      
        headers = {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Accept': 'application/json'
        }
      
        backoff = 1.0
        max_retries = 3
      
        for attempt in range(max_retries):
          response = http.request('POST', token_url, body=body.encode('utf-8'), 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 IBM Security Verify SaaS logs and write to GCS.
      
        Args:
          cloud_event: CloudEvent object containing Pub/Sub message
        """
      
        if not all([GCS_BUCKET, TENANT_URL, CLIENT_ID, CLIENT_SECRET]):
          print('Error: Missing required environment variables')
          return
      
        try:
          bucket = storage_client.bucket(GCS_BUCKET)
      
          # Load state
          state = load_state(bucket, STATE_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 logs from {last_time.isoformat()} to {now.isoformat()}")
      
          # Get access token
          token = get_token()
      
          # Fetch logs
          records, newest_event_time = fetch_logs(
            token=token,
            start_time=last_time,
            end_time=now,
            page_size=PAGE_SIZE,
            max_records=MAX_RECORDS,
          )
      
          if not records:
            print("No new log records found.")
            save_state(bucket, STATE_KEY, now.isoformat())
            return
      
          # Write to GCS as NDJSON
          timestamp = now.strftime('%Y%m%d_%H%M%S')
          object_key = f"{GCS_PREFIX}/logs_{timestamp}.ndjson"
          blob = bucket.blob(object_key)
      
          ndjson = '\n'.join([json.dumps(record, ensure_ascii=False) for record in records]) + '\n'
          blob.upload_from_string(ndjson, content_type='application/x-ndjson')
      
          print(f"Wrote {len(records)} records to gs://{GCS_BUCKET}/{object_key}")
      
          if newest_event_time:
            save_state(bucket, STATE_KEY, newest_event_time)
          else:
            save_state(bucket, STATE_KEY, now.isoformat())
      
          print(f"Successfully processed {len(records)} records")
      
        except Exception as e:
          print(f'Error processing 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}")
      
        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}")
      
      def fetch_logs(token: str, start_time: datetime, end_time: datetime, page_size: int, max_records: int):
        """
        Fetch logs from IBM Security Verify SaaS Events API with pagination and rate limiting.
      
        Args:
          token: OAuth 2.0 access token
          start_time: Start time for log query
          end_time: End time for log query
          page_size: Number of records per page
          max_records: Maximum total records to fetch
      
        Returns:
          Tuple of (records list, newest_event_time ISO string)
        """
        endpoint = f"{TENANT_URL}/v1.0/events"
      
        headers = {
          'Authorization': f'Bearer {token}',
          'Accept': 'application/json',
          'User-Agent': 'GoogleSecOps-IBMVerifyCollector/1.0'
        }
      
        records = []
        newest_time = None
        page_num = 0
        backoff = 1.0
      
        start_iso = start_time.strftime('%Y-%m-%dT%H:%M:%S.000Z')
        end_iso = end_time.strftime('%Y-%m-%dT%H:%M:%S.000Z')
      
        # IBM Verify Events API uses filter and sort_order with pagination
        search_after = None
      
        while True:
          page_num += 1
      
          if len(records) >= max_records:
            print(f"Reached max_records limit ({max_records})")
            break
      
          params = []
          params.append(f"size={min(page_size, max_records - len(records))}")
          params.append(f"filter=time+ge+\"{start_iso}\"+and+time+le+\"{end_iso}\"")
          params.append("sort_order=asc")
          if search_after:
            params.append(f"search_after={search_after}")
      
          url = f"{endpoint}?{'&'.join(params)}"
      
          try:
            response = http.request('GET', url, headers=headers)
      
            if response.status == 429:
              retry_after = int(response.headers.get('Retry-After', str(int(backoff))))
              print(f"Rate limited (429). Retrying after {retry_after}s...")
              time.sleep(retry_after)
              backoff = min(backoff * 2, 30.0)
              continue
      
            backoff = 1.0
      
            if response.status != 200:
              print(f"HTTP Error: {response.status}")
              response_text = response.data.decode('utf-8')
              print(f"Response body: {response_text}")
              return [], None
      
            data = json.loads(response.data.decode('utf-8'))
      
            page_results = data.get('events', [])
      
            if not page_results:
              print(f"No more results (empty page)")
              break
      
            print(f"Page {page_num}: Retrieved {len(page_results)} events")
            records.extend(page_results)
      
            # Track newest event time
            for event in page_results:
              try:
                event_time = event.get('time')
                if event_time:
                  if newest_time is None or parse_datetime(event_time) > parse_datetime(newest_time):
                    newest_time = event_time
              except Exception as e:
                print(f"Warning: Could not parse event time: {e}")
      
            # Check for more results using search_after pagination
            if len(page_results) < page_size:
              print(f"Reached last page (size={len(page_results)} < limit={page_size})")
              break
      
            # Use the last event's sort value for pagination
            last_event = page_results[-1]
            search_after = last_event.get('time', '')
      
          except Exception as e:
            print(f"Error fetching logs: {e}")
            return [], None
      
        print(f"Retrieved {len(records)} total 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. 提供以下配置详细信息:

    设置 值
    名称 ibm-verify-collector-hourly
    区域 选择与 Cloud Run 函数相同的区域
    频率 0 * * * *(每小时整点)
    时区 选择时区(建议选择世界协调时间 [UTC])
    目标类型 Pub/Sub
    主题 选择主题 ibm-verify-trigger
    消息正文 {}(空 JSON 对象)
  4. 点击创建。

时间表频率选项

根据日志量和延迟时间要求选择频次:

频率 Cron 表达式 使用场景
每隔 5 分钟 */5 * * * * 大容量、低延迟
每隔 15 分钟 */15 * * * * 搜索量中等
每小时 0 * * * * 标准(推荐)
每 6 小时 0 */6 * * * 低量批处理
每天 0 0 * * * 历史数据收集

测试集成

  1. 在 Cloud Scheduler 控制台中,找到您的作业 (ibm-verify-collector-hourly)。
  2. 点击强制运行以手动触发。
  3. 等待几秒钟,然后依次前往 Cloud Run > 服务 > ibm-verify-collector > 日志。
  4. 验证函数是否已成功执行。查找:

    Fetching logs from YYYY-MM-DDTHH:MM:SS+00:00 to YYYY-MM-DDTHH:MM:SS+00:00
    Page 1: Retrieved X events
    Wrote X records to gs://ibm-verify-saas-logs/ibm-verify/logs_YYYYMMDD_HHMMSS.ndjson
    Successfully processed X records
    
  5. 检查 GCS 存储桶 (ibm-verify-saas-logs) 以确认日志是否已写入。

如果您在日志中看到错误,请执行以下操作:

  • HTTP 401:检查环境变量中的 API 凭据
  • HTTP 403:在 IBM Security Verify 管理控制台中验证 API 客户端是否具有所需权限
  • HTTP 429:速率限制 - 函数将自动重试并进行退避
  • 无法获取访问令牌:验证 TENANT_URL、CLIENT_ID 和 CLIENT_SECRET 是否正确

在 Google SecOps 中配置 Feed 以注入 IBM Security Verify SaaS 日志

  1. 前往 SIEM 设置 > Feed。
  2. 点击添加新 Feed。
  3. 点击配置单个 Feed。
  4. 在 Feed 名称字段中,输入 Feed 的名称(例如 IBM Security Verify SaaS Logs)。
  5. 选择 Google Cloud Storage V2 作为来源类型。
  6. 选择 IBM Security Verify SaaS 作为日志类型。
  7. 点击获取服务账号。系统会显示一个唯一的服务账号电子邮件地址,例如:

    chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com
    
  8. 复制此电子邮件地址。您将在下一步骤中用到它。

  9. 点击下一步。

  10. 为以下输入参数指定值:

    • 存储桶网址:输入带有前缀路径的 GCS 存储桶 URI:

      gs://ibm-verify-saas-logs/ibm-verify/
      
      • 替换:
        • ibm-verify-saas-logs:您的 GCS 存储桶名称。
        • ibm-verify:存储日志的可选前缀/文件夹路径(留空表示根目录)。
    • 来源删除选项:根据您的偏好选择删除选项:

      • 永不:转移后永不删除任何文件(建议用于测试)。
      • 删除已转移的文件:成功转移后删除文件。
      • 删除已转移的文件和空目录:成功转移后删除文件和空目录。

    • 文件存在时间上限:包含在过去指定天数内修改过的文件(默认值为 180 天)。

    • 资源命名空间:资源命名空间。

    • 注入标签:要应用于此 Feed 中事件的标签。

  11. 点击下一步。

  12. 在最终确定界面中查看新的 Feed 配置,然后点击提交。

向 Google SecOps 服务账号授予 IAM 权限

Google SecOps 服务账号需要您的 GCS 存储桶的 Storage Object Viewer 角色。

  1. 前往 Cloud Storage > 存储桶。
  2. 点击您的存储桶名称 (ibm-verify-saas-logs)。
  3. 前往权限标签页。
  4. 点击授予访问权限。
  5. 提供以下配置详细信息:
    • 添加主账号:粘贴 Google SecOps 服务账号电子邮件地址。
    • 分配角色:选择 Storage Object Viewer。
  6. 点击保存。

UDM 映射表

日志字段 UDM 映射 逻辑
data.realm、geoip.continent_name、data.applicationtype、data.id_token、data.grant_id、data.grant_type、data.at_hash、data.rt_hash、id、data.scope、data.uasessionid、data.performedby_type、data.subject_type、data.target_type、data.templateid、data.subjectid、data.performedby、data.action、data.performedby_clientname、geoip.as_org、geoip.country_iso_code、operation.op、operation.path、operation.value、operation.value.name、operation.value.values additional.fields 标准 UDM 字段未涵盖的其他元数据字段
auth_type extensions.auth.type 使用的身份验证类型
meta_event_type metadata.event_type 事件类型(例如 USER_LOGIN、NETWORK_CONNECTION)
tenantid metadata.product_deployment_id 商品部署的标识符
event_type metadata.product_event_type 特定于产品的事件类型
data.ib_request_id metadata.product_log_id 特定于产品的日志标识符
data.devicetype network.http.parsed_user_agent 已解析的用户代理字符串
data.devicetype network.http.user_agent 用户代理字符串
data.sessionid network.session_id 会话标识符
tenantname observer.hostname 观察方的主机名
data.applicationname principal.application 与主体关联的应用
data.origin, geoip.ip principal.ip 主账号的 IP 地址
geoip.city_name principal.location.city 委托人的主要营业地点所在的城市
geoip.country_name principal.location.country_or_region 委托人所在地的国家/区域
geoip.location.lat principal.location.region_latitude 负责人的位置纬度
geoip.location.lon principal.location.region_longitude 委托人所在位置的经度
geoip.region_name principal.location.state 委托人的位置信息状态
data.applicationid principal.resource.product_object_id 资源的商品对象标识符
data.subtype principal.resource.resource_subtype 资源的子类型
data.redirecturl principal.url 与委托人关联的网址
data.username principal.user.user_display_name 用户的显示名称
data.userid principal.user.userid 用户标识符
security_result security_result 安全结果信息
data.client_id、data.client_name、data.client_type security_result.about.resource.attribute.labels 资源属性的标签
action1 security_result.action 安防系统采取的措施
data.result security_result.action_details 安全操作的详细信息
data.status_code, correlationid security_result.detection_fields 与检测相关的字段
servicename target.application 定位到的应用
data.targetid target.resource.id 目标资源的标识符
data.account_name target.user.user_display_name 目标用户的显示名称
data.target target.user.userid 目标的相应用户标识符
metadata.product_name 产品名称
metadata.vendor_name 供应商/公司名称
data.status_code", "data.performedby_type", "data.subject_type", "data.target_type", "data.templateid", "data.subjectid", "data.performedby", "data.action", and "data.performedby_clientname additional.fields 从更新日志映射
data.cause security_result.summary 从更新日志映射
data.json.Operations.path", "data.json.Operations.op", and "data.json.Operations.value additional.fields 从更新日志映射
geoip.as_org", "geoip.country_iso_code additional.fields 从更新日志映射

更新日志

查看相应解析器的更新日志

需要更多帮助?获得社区成员和 Google SecOps 专业人士的解答。