收集 SpyCloud 日志

支持的平台:

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

SpyCloud 是一款账号盗用防范平台,可提供数据泄露和被盗凭据情报。它通过 REST API 提供违规记录、监控名单提醒和遭入侵的凭据报告。

准备工作

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

  • Google SecOps 实例
  • 已启用 Cloud Storage API 的 GCP 项目
  • 创建和管理 GCS 存储分区的权限
  • 管理 GCS 存储分区的 IAM 政策的权限
  • 创建 Cloud Run 服务、Pub/Sub 主题和 Cloud Scheduler 作业的权限
  • 具有 API 访问权限和有效 API 密钥的 SpyCloud 账号

创建 Google Cloud Storage 存储桶

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

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

收集 SpyCloud API 凭据

获取 API 密钥

  1. 以管理员身份登录 SpyCloud 门户
  2. 依次前往设置 > API
  3. 复制 API 密钥并将其保存在安全的位置。

验证权限

如需验证您的 API 密钥是否具有所需的访问权限,请执行以下操作:

  1. 登录 SpyCloud 门户
  2. 依次前往设置 > API
  3. 验证 API 密钥是否有效,以及是否具有对所需端点(违规数据、监控名单、指南针)的访问权限。
  4. 如果访问权限受到限制,请与您的 SpyCloud 管理员联系。

测试 API 访问权限

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

    # Replace with your actual API key
    API_KEY="your-api-key"
    
    # Test API access - fetch watchlist data
    curl -v -H "X-API-Key: ${API_KEY}" \
      "https://api.spycloud.io/enterprise-v2/breach/data/watchlist?since=2024-01-01&until=2024-01-02"
    

为 Cloud Run 函数创建服务账号

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

创建服务账号

  1. GCP 控制台中,依次前往 IAM 和管理 > 服务账号
  2. 点击创建服务账号
  3. 提供以下配置详细信息:
    • 服务账号名称:输入 spycloud-collector-sa
    • 服务账号说明:输入 Service account for Cloud Run function to collect SpyCloud 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. 点击您的存储桶名称(例如 spycloud-logs)。
  3. 前往权限标签页。
  4. 点击授予访问权限
  5. 提供以下配置详细信息:
    • 添加主账号:输入服务账号电子邮件地址(例如 spycloud-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:输入 spycloud-trigger
    • 将其他设置保留为默认值。
  4. 点击创建

创建 Cloud Run 函数以收集日志

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

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

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

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

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

  8. 前往安全性标签页:

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

    1. 点击变量和密钥
    2. 为每个环境变量点击+ 添加变量
    变量名称 示例值 说明
    GCS_BUCKET spycloud-logs GCS 存储桶名称
    GCS_PREFIX spycloud 日志文件的前缀
    STATE_KEY spycloud/state.json 状态文件路径
    API_KEY your-api-key SpyCloud API 密钥
    API_BASE https://api.spycloud.io API 基本网址
    MAX_RECORDS 10000 每次运行的记录数上限
    LOOKBACK_DAYS 7 初始回溯期(以天为单位)
    STREAMS watchlist,catalog 以逗号分隔的数据流
  10. 变量和密钥标签页中,向下滚动到请求

    • 请求超时:输入 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
      
      # 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', 'spycloud')
      STATE_KEY = os.environ.get('STATE_KEY', 'spycloud/state.json')
      API_KEY = os.environ.get('API_KEY', '')
      API_BASE = os.environ.get('API_BASE', 'https://api.spycloud.io').rstrip('/')
      MAX_RECORDS = int(os.environ.get('MAX_RECORDS', '10000'))
      LOOKBACK_DAYS = int(os.environ.get('LOOKBACK_DAYS', '7'))
      STREAMS = [s.strip() for s in os.environ.get('STREAMS', 'watchlist').split(',') if s.strip()]
      
      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)
      
      @functions_framework.cloud_event
      def main(cloud_event):
        """
        Cloud Run function triggered by Pub/Sub to fetch SpyCloud logs and write to GCS.
      
        Args:
          cloud_event: CloudEvent object containing Pub/Sub message
        """
      
        if not all([GCS_BUCKET, API_KEY]):
          print('Error: Missing required environment variables')
          return
      
        try:
          bucket = storage_client.bucket(GCS_BUCKET)
      
          # Load state
          state = load_state(bucket, STATE_KEY)
      
          now = datetime.now(timezone.utc)
      
          # Determine date range
          if isinstance(state, dict) and state.get("last_date"):
            since_date = state["last_date"]
          else:
            since_date = (now - timedelta(days=LOOKBACK_DAYS)).strftime('%Y-%m-%d')
      
          until_date = now.strftime('%Y-%m-%d')
      
          print(f"Fetching data from {since_date} to {until_date}")
      
          report = {}
      
          if 'watchlist' in STREAMS:
            print("Fetching watchlist breach data...")
            count = pull_watchlist(bucket, since_date, until_date)
            report['watchlist_records'] = count
      
          if 'catalog' in STREAMS:
            print("Fetching breach catalog...")
            count = pull_catalog(bucket, since_date, until_date)
            report['catalog_records'] = count
      
          if 'compass' in STREAMS:
            print("Fetching compass data...")
            count = pull_compass(bucket, since_date, until_date)
            report['compass_records'] = count
      
          # Update state
          save_state(bucket, STATE_KEY, until_date)
          print(f"Successfully processed: {json.dumps(report)}")
      
        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_date: str):
        """Save the last query date to GCS state file."""
        try:
          state = {'last_date': last_date, 'last_event_time': datetime.now(timezone.utc).isoformat()}
          blob = bucket.blob(key)
          blob.upload_from_string(
            json.dumps(state, indent=2),
            content_type='application/json'
          )
          print(f"Saved state: last_date={last_date}")
        except Exception as e:
          print(f"Warning: Could not save state: {e}")
      
      def api_get(endpoint: str, params: dict = None):
        """Make authenticated GET request to SpyCloud API with rate limiting."""
        url = f"{API_BASE}{endpoint}"
        if params:
          query = '&'.join([f"{k}={v}" for k, v in params.items()])
          url = f"{url}?{query}"
      
        headers = {
          'X-API-Key': API_KEY,
          'Accept': 'application/json',
          'User-Agent': 'GoogleSecOps-SpyCloudCollector/1.0'
        }
      
        backoff = 1.0
        max_retries = 3
      
        for attempt in range(max_retries):
          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
      
          if response.status != 200:
            print(f"HTTP Error: {response.status} - {response.data.decode('utf-8')}")
            return None
      
          return json.loads(response.data.decode('utf-8'))
      
        print(f"Failed after {max_retries} retries due to rate limiting")
        return None
      
      def write_ndjson(bucket, prefix: str, stream_name: str, records: list):
        """Write records to GCS as NDJSON."""
        if not records:
          return 0
      
        now = datetime.now(timezone.utc)
        timestamp = now.strftime('%Y%m%d_%H%M%S')
        object_key = f"{GCS_PREFIX}/{stream_name}/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}")
        return len(records)
      
      def pull_watchlist(bucket, since_date: str, until_date: str):
        """Fetch watchlist breach data."""
        cursor = None
        all_records = []
      
        while True:
          params = {'since': since_date, 'until': until_date}
          if cursor:
            params['cursor'] = cursor
      
          data = api_get('/enterprise-v2/breach/data/watchlist', params)
          if not data:
            break
      
          results = data.get('results', [])
          if not results:
            break
      
          all_records.extend(results)
      
          if len(all_records) >= MAX_RECORDS:
            print(f"Reached max_records limit ({MAX_RECORDS})")
            break
      
          cursor = data.get('cursor')
          if not cursor:
            break
      
        return write_ndjson(bucket, GCS_PREFIX, 'watchlist', all_records)
      
      def pull_catalog(bucket, since_date: str, until_date: str):
        """Fetch breach catalog."""
        params = {'since': since_date, 'until': until_date}
        data = api_get('/enterprise-v2/breach/catalog', params)
        if not data:
          return 0
      
        results = data.get('results', [])
        return write_ndjson(bucket, GCS_PREFIX, 'catalog', results)
      
      def pull_compass(bucket, since_date: str, until_date: str):
        """Fetch compass findings."""
        cursor = None
        all_records = []
      
        while True:
          params = {'since': since_date, 'until': until_date}
          if cursor:
            params['cursor'] = cursor
      
          data = api_get('/enterprise-v2/compass/data', params)
          if not data:
            break
      
          results = data.get('results', [])
          if not results:
            break
      
          all_records.extend(results)
      
          if len(all_records) >= MAX_RECORDS:
            print(f"Reached max_records limit ({MAX_RECORDS})")
            break
      
          cursor = data.get('cursor')
          if not cursor:
            break
      
        return write_ndjson(bucket, GCS_PREFIX, 'compass', all_records)
      
    • 第二个文件: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. 提供以下配置详细信息:

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

时间表频率选项

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

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

测试集成

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

    Fetching data from YYYY-MM-DD to YYYY-MM-DD
    Fetching watchlist breach data...
    Wrote X records to gs://spycloud-logs/spycloud/watchlist/logs_YYYYMMDD_HHMMSS.ndjson
    Successfully processed: {"watchlist_records": X, "catalog_records": Y}
    
  5. 检查 GCS 存储桶 (spycloud-logs) 以确认日志是否已写入。

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

  • HTTP 401:检查环境变量中的 API 密钥
  • HTTP 403:验证 API 密钥是否具有对所需端点的访问权限
  • HTTP 429:速率限制 - 函数将自动重试并进行退避
  • 缺少环境变量:检查是否已设置所有必需的变量

在 Google SecOps 中配置 Feed 以注入 SpyCloud 日志

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

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

  9. 点击下一步

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

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

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

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

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

    • 资产命名空间资产命名空间

    • 提取标签:要应用于相应 Feed 中事件的标签。

  11. 点击下一步

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

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

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

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

UDM 映射表

日志字段 UDM 映射 逻辑
av_softwares、assets.av_softwares、assets.country、assets.country_code、assets.display_resolution、assets.email、assets.full_name、assets.infected_machine_id、assets.infected_path、assets.infected_time、assets.ip_addresses、assets.keyboard_languages、assets.password、assets.target_url、assets.username、assets.user_browser、assets.user_hostname、assets.user_os、assets.user_sys_registered_owner additional.fields 从根据这些字段和 av_software_list 创建的标签合并而来
密码 extensions.auth.auth_details 直接复制值
when metadata.event_timestamp 解析为 ISO8601 时间戳
metadata.event_type 根据条件设置:如果具有 has_principal、has_target、has_network,则为 NETWORK_CONNECTION;如果具有 has_principal 和 has_principal_userid,则为 USER_UNCATEGORIZED;如果具有 has_principal 但不具有 has_principal_ip,则为 STATUS_UPDATE;否则为 GENERIC_EVENT;如果存在 user_hostname、ip 或 infected_machine_id,则为 USER_UNCATEGORIZED
infected_time metadata.ingested_timestamp 解析为时间戳,格式为 yyyy-MM-ddTHH:mm:ssZ、RFC 3339、ISO8601
log_id、assets.log_id、uuid metadata.product_log_id 如果 log_id 不为空,则使用 log_id 中的值;否则,使用 assets.log_id 中的值;否则,使用 UUID
user_os network.http.parsed_user_agent 已转换为已解析的用户代理
user_os network.http.user_agent 直接复制值
cookie_domain principal.administrative_domain 直接复制值
国家/地区 principal.asset.location.country_or_region 直接复制值
infected_machine_id principal.asset_id 串联为“id: ”+ infected_machine_id
infected_path principal.file.full_path 直接复制值
user_hostname, domain principal.hostname 如果不为空,则设置为 user_hostname;如果不为空,则设置为网域
ip, ip_addresses principal.ip 从 ip 和 ip_addresses 数组合并而来
country_code principal.resource.attribute.labels 从 country_code 创建的 country_code_label 合并而来
id principal.resource.id 直接复制的值(已转换为字符串)
首页 principal.url 直接复制值
电子邮件 principal.user.email_addresses 直接复制值
full_name principal.user.user_display_name 直接复制值
user_sys_registered_owner, email_username principal.user.userid 设置为 user_sys_registered_owner,如果该值不为空,则设置为 email_username
置信度 security_result.confidence_details 已转换为字符串
说明 security_result.description 直接复制值
cookie_expiration、cookie_name、cookie_subdomain、cookie_value、day、document_id、locality_zone、source_id、spycloud_publishdate、spycloud_publish_date、user_browser、infected_time、timezone、password_type、password_plaintext、email_domain、api_token、account_status、breach_category、breach_main_category、consumer_category、malware_family、num_records、premium_flag、sensitive_source、short_title、site_description、title、tlp、type、display_resolution、keyboard_languages security_result.detection_fields 根据这些字段创建的标签合并而来
和程度上减少 security_result.severity 如果值为“2”,则设置为 LOW;如果值为“5”,则设置为 INFORMATIONAL;如果值为“20”,则设置为 HIGH;如果值为“25”或“26”,则设置为 CRITICAL
和程度上减少 security_result.severity_details 直接复制值
target_subdomain target.administrative_domain 直接复制值
target_domain target.asset.hostname 直接复制值
target_domain target.hostname 直接复制值
target_url target.url 直接复制值
用户名 target.user.userid 直接复制值
metadata.product_name 设置为“SPYCLOUD”
metadata.vendor_name 设置为“SpyCloud”
spycloud_publish_date", "infected_time", and "timezone security_result.detection_fields 从变更日志映射

更新日志

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

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