收集 Box JSON 日志

支持的平台:

本文档介绍了如何使用 Google Cloud Storage 将 Box JSON 日志提取到 Google Security Operations。解析器会处理 JSON 格式的 Box 事件日志,并将其映射到统一数据模型 (UDM)。它从原始日志中提取相关字段,执行重命名和合并等数据转换,并使用中间信息丰富数据,然后输出结构化事件数据。

准备工作

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

  • Google SecOps 实例
  • 已启用 Cloud Storage API 的 GCP 项目
  • 创建和管理 GCS 存储分区的权限
  • 管理 GCS 存储分区的 IAM 政策的权限
  • 创建 Cloud Run 服务、Pub/Sub 主题和 Cloud Scheduler 作业的权限
  • 对 Box 的特权访问权限(管理员 + 开发者控制台)

配置 Box 开发者控制台(客户端凭据)

  1. 登录 Box 开发者控制台
  2. 创建具有服务器身份验证(客户端凭据授权)自定义应用
  3. 应用访问权限设置为应用 + 企业访问权限
  4. 应用范围中,启用管理企业资源
  5. 管理控制台 > 应用 > 自定义应用管理器中,通过客户端 ID 授权应用。
  6. 复制客户端 ID客户端密钥,并将其保存到安全的位置。
  7. 前往管理控制台 > 账号和结算 > 账号信息
  8. 复制并保存企业 ID,并将其存储在安全的位置。

创建 Google Cloud Storage 存储分区

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

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

为 Cloud Run 函数创建服务账号

Cloud Run 函数需要一个服务账号,该账号具有向 GCS 存储分区写入内容以及被 Pub/Sub 调用的权限。

创建服务账号

  1. GCP 控制台中,依次前往 IAM 和管理 > 服务账号
  2. 点击创建服务账号
  3. 提供以下配置详细信息:
    • 服务账号名称:输入 box-collaboration-collector-sa
    • 服务账号说明:输入 Service account for Cloud Run function to collect Box Collaboration 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. 点击您的存储分区名称。
  3. 前往权限标签页。
  4. 点击授予访问权限
  5. 提供以下配置详细信息:
    • 添加主账号:输入服务账号电子邮件地址 (box-collaboration-collector-sa@PROJECT_ID.iam.gserviceaccount.com)。
    • 分配角色:选择 Storage Object Admin
  6. 点击保存

创建发布/订阅主题

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

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

创建 Cloud Run 函数以收集日志

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

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

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

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

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

  8. 前往安全标签页:

    • 服务账号:选择服务账号 (box-collaboration-collector-sa)。
  9. 前往容器标签页:

    1. 点击变量和密钥
    2. 为每个环境变量点击 + 添加变量
    变量名称 示例值
    GCS_BUCKET box-collaboration-logs
    GCS_PREFIX box/collaboration/
    STATE_KEY box/collaboration/state.json
    BOX_CLIENT_ID 输入 Box 客户端 ID
    BOX_CLIENT_SECRET 输入 Box 客户端密钥
    BOX_ENTERPRISE_ID 输入 Box 企业 ID
    STREAM_TYPE admin_logs_streaming
    LIMIT 500
  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
    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()
    
    TOKEN_URL = "https://api.box.com/oauth2/token"
    EVENTS_URL = "https://api.box.com/2.0/events"
    
    @functions_framework.cloud_event
    def main(cloud_event):
        """
        Cloud Run function triggered by Pub/Sub to fetch Box enterprise events and write to GCS.
    
        Args:
            cloud_event: CloudEvent object containing Pub/Sub message
        """
    
        # Get environment variables
        bucket_name = os.environ.get('GCS_BUCKET')
        prefix = os.environ.get('GCS_PREFIX', 'box/collaboration/')
        state_key = os.environ.get('STATE_KEY', 'box/collaboration/state.json')
    
        client_id = os.environ.get('BOX_CLIENT_ID')
        client_secret = os.environ.get('BOX_CLIENT_SECRET')
        enterprise_id = os.environ.get('BOX_ENTERPRISE_ID')
        stream_type = os.environ.get('STREAM_TYPE', 'admin_logs_streaming')
        limit = int(os.environ.get('LIMIT', '500'))
    
        if not all([bucket_name, client_id, client_secret, enterprise_id]):
            print('Error: Missing required environment variables')
            return
    
        try:
            # Get GCS bucket
            bucket = storage_client.bucket(bucket_name)
    
            # Get OAuth token
            token = get_token(client_id, client_secret, enterprise_id)
    
            # Load state (stream position)
            state = load_state(bucket, state_key)
            stream_position = state.get('stream_position')
    
            print(f'Processing events from stream position: {stream_position}')
    
            total_events = 0
            idx = 0
    
            while True:
                # Fetch events page
                page = fetch_events(token, stream_type, limit, stream_position)
                entries = page.get('entries') or []
    
                if not entries:
                    next_pos = page.get('next_stream_position') or stream_position
                    if next_pos and next_pos != stream_position:
                        save_state(bucket, state_key, {'stream_position': next_pos})
                    break
    
                # Write page to GCS
                timestamp = datetime.now(timezone.utc).strftime('%Y/%m/%d/%H%M%S')
                blob_name = f"{prefix}{timestamp}-box-events-{idx:03d}.json"
                blob = bucket.blob(blob_name)
                blob.upload_from_string(
                    json.dumps(page, separators=(',', ':')),
                    content_type='application/json'
                )
    
                idx += 1
                total_events += len(entries)
                stream_position = page.get('next_stream_position') or stream_position
    
                # Save state after each page
                if stream_position:
                    save_state(bucket, state_key, {'stream_position': stream_position})
    
                # Break if fewer entries than limit (last page)
                if len(entries) < limit:
                    break
    
            print(f'Successfully processed {total_events} events, final position: {stream_position}')
    
        except Exception as e:
            print(f'Error processing Box events: {str(e)}')
            raise
    
    def get_token(client_id, client_secret, enterprise_id):
        """Get OAuth 2.0 access token using client credentials grant."""
        fields = {
            'grant_type': 'client_credentials',
            'client_id': client_id,
            'client_secret': client_secret,
            'box_subject_type': 'enterprise',
            'box_subject_id': enterprise_id
        }
    
        response = http.request(
            'POST',
            TOKEN_URL,
            fields=fields,
            headers={'Content-Type': 'application/x-www-form-urlencoded'}
        )
    
        token_data = json.loads(response.data.decode('utf-8'))
        return token_data['access_token']
    
    def fetch_events(token, stream_type, limit, stream_position=None, timeout=60, max_retries=5):
        """Fetch events from Box API with retry logic."""
        params = {
            'stream_type': stream_type,
            'limit': str(limit),
            'stream_position': stream_position or 'now'
        }
    
        # Build query string
        query_string = '&'.join([f"{k}={v}" for k, v in params.items()])
        url = f"{EVENTS_URL}?{query_string}"
    
        attempt = 0
        backoff = 1.0
    
        while True:
            try:
                response = http.request(
                    'GET',
                    url,
                    headers={'Authorization': f'Bearer {token}'},
                    timeout=timeout
                )
    
                if response.status == 200:
                    return json.loads(response.data.decode('utf-8'))
                elif response.status == 429 and attempt < max_retries:
                    # Rate limited - retry with backoff
                    retry_after = response.headers.get('Retry-After')
                    delay = int(retry_after) if retry_after and retry_after.isdigit() else int(backoff)
                    print(f'Rate limited, retrying after {delay} seconds')
                    import time
                    time.sleep(max(1, delay))
                    attempt += 1
                    backoff *= 2
                    continue
                elif 500 <= response.status <= 599 and attempt < max_retries:
                    # Server error - retry with backoff
                    print(f'Server error {response.status}, retrying after {backoff} seconds')
                    import time
                    time.sleep(backoff)
                    attempt += 1
                    backoff *= 2
                    continue
                else:
                    raise Exception(f'Box API error: {response.status} {response.data.decode("utf-8")}')
            except Exception as e:
                if attempt < max_retries:
                    print(f'Request error: {str(e)}, retrying after {backoff} seconds')
                    import time
                    time.sleep(backoff)
                    attempt += 1
                    backoff *= 2
                    continue
                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: {str(e)}')
        return {}
    
    def save_state(bucket, key, state):
        """Save state to GCS."""
        try:
            blob = bucket.blob(key)
            blob.upload_from_string(
                json.dumps(state, separators=(',', ':')),
                content_type='application/json'
            )
        except Exception as e:
            print(f'Warning: Could not save state: {str(e)}')
    
    • 第二个文件: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. 提供以下配置详细信息:

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

时间表频率选项

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

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

测试集成

  1. Cloud Scheduler 控制台中,找到您的作业。
  2. 点击强制运行以手动触发作业。
  3. 等待几秒钟。
  4. 前往 Cloud Run > 服务
  5. 点击函数名称 (box-collaboration-collector)。
  6. 点击日志标签页。
  7. 验证函数是否已成功执行。查找以下项:

    Processing events from stream position: ...
    Page 1: Retrieved X events
    Wrote X records to gs://box-collaboration-logs/box/collaboration/...
    Successfully processed X events
    
  8. 前往 Cloud Storage > 存储分区

  9. 点击您的存储分区名称。

  10. 前往前缀文件夹 (box/collaboration/)。

  11. 验证是否已创建具有当前时间戳的新 .json 文件。

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

  • HTTP 401:检查环境变量中的 Box API 凭据
  • HTTP 403:验证 Box 应用是否具有所需权限,并且已在管理控制台中获得授权
  • HTTP 429:速率限制 - 函数将自动重试并进行退避
  • 缺少环境变量:检查是否已设置所有必需的变量

检索 Google SecOps 服务账号

Google SecOps 使用唯一的服务账号从您的 GCS 存储分区中读取数据。您必须授予此服务账号对您的存储分区的访问权限。

获取服务账号电子邮件地址

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

    chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com
    
  8. 复制此电子邮件地址,以便在下一步中使用。

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

Google SecOps 服务账号需要对您的 GCS 存储分区具有 Storage Object Viewer 角色。

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

在 Google SecOps 中配置 Feed 以提取 Box 日志

  1. 依次前往 SIEM 设置 > Feed
  2. 点击添加新 Feed
  3. 点击配置单个 Feed
  4. Feed 名称字段中,输入 Feed 的名称(例如 Box Collaboration)。
  5. 选择 Google Cloud Storage V2 作为来源类型
  6. 选择 Box 作为日志类型
  7. 点击下一步
  8. 为以下输入参数指定值:

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

      gs://box-collaboration-logs/box/collaboration/
      
        • box-collaboration-logs:您的 GCS 存储分区名称。
        • box/collaboration/:存储日志的前缀/文件夹路径。
      • 示例

        • 根存储分区:gs://company-logs/
        • 带前缀:gs://company-logs/box-logs/
        • 使用子文件夹:gs://company-logs/box/collaboration/
    • 来源删除选项:根据您的偏好选择删除选项:

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

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

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

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

  9. 点击下一步

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

UDM 映射表

日志字段 UDM 映射 逻辑
additional_details.ekm_id additional.fields 从 additional_details.ekm_id 中提取的值
additional_details.service_id additional.fields 从 additional_details.service_id 中获取的值
additional_details.service_name additional.fields 从 additional_details.service_name 中获取的值
additional_details.shared_link_id additional.fields 从 additional_details.shared_link_id 中提取的值
additional_details.size target.file.size 从 additional_details.size 中获取的值
additional_details.version_id additional.fields 从 additional_details.version_id 中获取的值
created_at metadata.event_timestamp 从 created_at 中提取的值
created_by.id principal.user.userid 从 created_by.id 中获取的值
created_by.login principal.user.email_addresses 从 created_by.login 中获取的值
created_by.name principal.user.user_display_name 从 created_by.name 中获取的值
event_id metadata.product_log_id 从 event_id 中获取的值
event_type metadata.product_event_type 从 event_type 中获取的值
ip_address principal.ip 从 ip_address 获取的值
source.item_id target.file.product_object_id 从 source.item_id 中获取的值
source.item_name target.file.full_path 从 source.item_name 中获取的值
source.item_type 未映射
source.login target.user.email_addresses 从 source.login 中获取的值
source.name target.user.user_display_name 从 source.name 中获取的值
source.owned_by.id target.user.userid 从 source.owned_by.id 中获取的值
source.owned_by.login target.user.email_addresses 从 source.owned_by.login 中获取的值
source.owned_by.name target.user.user_display_name 从 source.owned_by.name 中获取的值
source.parent.id 未映射
source.parent.name 未映射
source.parent.type 未映射
source.type 未映射
类型 metadata.log_type 从类型中获取的值
metadata.vendor_name 硬编码值
metadata.product_name 硬编码值
security_result.action 派生自 event_type。如果 event_type 为 FAILED_LOGIN,则为 BLOCK;如果 event_type 为 USER_LOGIN,则为 ALLOW;否则为 UNSPECIFIED。
extensions.auth.type 派生自 event_type。如果 event_type 为 USER_LOGIN 或 ADMIN_LOGIN,则为 MACHINE;否则为 UNSPECIFIED。
extensions.auth.mechanism 派生自 event_type。如果 event_type 为 USER_LOGIN 或 ADMIN_LOGIN,则为 USERNAME_PASSWORD;否则为 UNSPECIFIED。

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