收集 Duo 管理员日志

支持的平台:

本文档介绍了如何使用 Google Cloud Storage 将 Duo 管理员日志提取到 Google Security Operations。解析器会从日志(JSON 格式)中提取字段,并将其映射到统一数据模型 (UDM)。它会以不同的方式处理各种 Duo 操作类型(登录、用户管理、群组管理),并根据操作和可用数据(包括用户详细信息、身份验证因素和安全结果)填充相关的 UDM 字段。它还会执行数据转换,例如合并 IP 地址、转换时间戳和处理错误。

准备工作

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

  • Google SecOps 实例
  • 已启用 Cloud Storage API 的 GCP 项目
  • 创建和管理 GCS 存储分区的权限
  • 管理 GCS 存储分区的 IAM 政策的权限
  • 创建 Cloud Run 函数、Pub/Sub 主题和 Cloud Scheduler 作业的权限
  • 对 Duo 租户(Admin API 应用)的特权访问权限

配置 Duo Admin API 应用

  1. 登录 Duo 管理面板
  2. 前往应用 > 应用目录
  3. 添加 Admin API 应用。
  4. 记录以下值:
    • 集成密钥 (ikey)
    • 密钥 (skey)
    • API 主机名(例如 api-XXXXXXXX.duosecurity.com
  5. 权限中,启用授予读取日志权限(以读取管理员日志)。
  6. 保存应用。

创建 Google Cloud Storage 存储分区

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

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

为 Cloud Run 函数创建服务账号

Cloud Run 函数需要一个有权写入 GCS 存储分区的服务账号。

创建服务账号

  1. GCP 控制台中,依次前往 IAM 和管理 > 服务账号
  2. 点击创建服务账号
  3. 提供以下配置详细信息:
    • 服务账号名称:输入 duo-admin-collector-sa
    • 服务账号说明:输入 Service account for Cloud Run function to collect Duo administrator 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. 提供以下配置详细信息:
    • 添加主账号:输入服务账号电子邮件地址。
    • 分配角色:选择 Storage Object Admin
  6. 点击保存

创建发布/订阅主题

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

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

创建 Cloud Run 函数以收集日志

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

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

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

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

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

  8. 前往安全标签页:

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

    1. 点击变量和密钥
    2. 为每个环境变量点击 + 添加变量
    变量名称 示例值
    GCS_BUCKET duo-admin-logs
    GCS_PREFIX duo/admin
    STATE_KEY duo/admin/state.json
    DUO_IKEY DIXYZ...
    DUO_SKEY ****************
    DUO_API_HOSTNAME api-XXXXXXXX.duosecurity.com
  10. 变量和密钥标签页中,向下滚动到请求

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

    • 资源部分中:
      • 内存:选择 512 MiB 或更高值。
      • CPU:选择 1
    • 点击完成
  12. 滚动到执行环境

    • 选择默认(推荐)。
  13. 修订版本扩缩部分中:

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

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

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

添加函数代码

  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 hmac
    import hashlib
    import base64
    import email.utils
    import urllib.parse
    import time
    
    # Initialize HTTP client
    http = urllib3.PoolManager()
    
    # Initialize Storage client
    storage_client = storage.Client()
    
    @functions_framework.cloud_event
    def main(cloud_event):
        """
        Cloud Run function triggered by Pub/Sub to fetch Duo Admin logs 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', 'duo/admin')
        state_key = os.environ.get('STATE_KEY', 'duo/admin/state.json')
    
        # Duo API credentials
        duo_ikey = os.environ.get('DUO_IKEY')
        duo_skey = os.environ.get('DUO_SKEY')
        duo_api_hostname = os.environ.get('DUO_API_HOSTNAME', '').strip()
    
        if not all([bucket_name, duo_ikey, duo_skey, duo_api_hostname]):
            print('Error: Missing required environment variables')
            return
    
        try:
            # Get GCS bucket
            bucket = storage_client.bucket(bucket_name)
    
            # Load state (last processed timestamp)
            state = load_state(bucket, state_key)
            now = int(time.time())
            mintime = state.get('mintime', now - 3600)
    
            print(f'Processing logs since {mintime}')
    
            # Fetch logs from Duo Admin API
            page = 0
            total = 0
            next_mintime = mintime
            max_seen_ts = mintime
    
            while True:
                page_num = 0
    
                data = duo_api_request(
                    duo_ikey, 
                    duo_skey, 
                    duo_api_hostname,
                    'GET',
                    '/admin/v1/logs/administrator',
                    {'mintime': mintime}
                )
    
                # Write page to GCS
                write_page(bucket, prefix, data, now, page)
                page += 1
    
                # Extract items
                resp = data.get('response')
                items = resp if isinstance(resp, list) else (resp.get('items') if isinstance(resp, dict) else [])
                items = items or []
    
                if not items:
                    break
    
                total += len(items)
    
                # Track the newest timestamp in this batch
                for it in items:
                    ts = epoch_from_item(it)
                    if ts and ts > max_seen_ts:
                        max_seen_ts = ts
    
                # Duo returns only the 1000 earliest events; page by advancing mintime
                if len(items) >= 1000 and max_seen_ts >= mintime:
                    mintime = max_seen_ts
                    next_mintime = max_seen_ts
                    continue
                else:
                    break
    
            # Save checkpoint: newest seen ts, or "now" if nothing new
            if max_seen_ts > next_mintime:
                save_state(bucket, state_key, {'mintime': max_seen_ts})
                next_state = max_seen_ts
            else:
                save_state(bucket, state_key, {'mintime': now})
                next_state = now
    
            print(f'Successfully processed {total} events across {page} pages, next_mintime: {next_state}')
    
        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: {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),
                content_type='application/json'
            )
        except Exception as e:
            print(f'Warning: Could not save state: {str(e)}')
    
    def write_page(bucket, prefix, payload, when, page):
        """Write a page of logs to GCS."""
        try:
            timestamp_str = time.strftime('%Y/%m/%d', time.gmtime(when))
            key = f"{prefix}/{timestamp_str}/duo-admin-{page:05d}.json"
            blob = bucket.blob(key)
            blob.upload_from_string(
                json.dumps(payload, separators=(',', ':')),
                content_type='application/json'
            )
            print(f'Wrote page {page} to {key}')
        except Exception as e:
            print(f'Error writing page {page}: {str(e)}')
            raise
    
    def canon_params(params):
        """Canonicalize parameters for Duo API signature."""
        parts = []
        for k in sorted(params.keys()):
            v = params[k]
            if v is None:
                continue
            parts.append(f"{urllib.parse.quote(str(k), '~')}={urllib.parse.quote(str(v), '~')}")
        return "&".join(parts)
    
    def sign_request(method, host, path, params, ikey, skey):
        """Sign Duo API request."""
        now = email.utils.formatdate()
        canon = "\n".join([
            now,
            method.upper(),
            host.lower(),
            path,
            canon_params(params)
        ])
        sig = hmac.new(skey.encode('utf-8'), canon.encode('utf-8'), hashlib.sha1).hexdigest()
        auth = base64.b64encode(f"{ikey}:{sig}".encode()).decode()
        return {
            'Date': now,
            'Authorization': f'Basic {auth}'
        }
    
    def duo_api_request(ikey, skey, host, method, path, params, timeout=60, max_retries=5):
        """Make a signed request to Duo Admin API with retry logic."""
        assert host.startswith('api-') and host.endswith('.duosecurity.com'), \
            "DUO_API_HOSTNAME must be like api-XXXXXXXX.duosecurity.com"
    
        qs = canon_params(params)
        url = f"https://{host}{path}" + (f"?{qs}" if qs else "")
    
        attempt = 0
        backoff = 1.0
    
        while True:
            headers = sign_request(method, host, path, params, ikey, skey)
            headers['Accept'] = 'application/json'
    
            try:
                response = http.request(method.upper(), url, headers=headers, timeout=timeout)
                return json.loads(response.data.decode('utf-8'))
            except urllib3.exceptions.HTTPError as e:
                # Retry on 429 or 5xx
                if hasattr(e, 'status') and (e.status == 429 or 500 <= e.status <= 599) and attempt < max_retries:
                    time.sleep(backoff)
                    attempt += 1
                    backoff *= 2
                    continue
                raise
            except Exception as e:
                if attempt < max_retries:
                    time.sleep(backoff)
                    attempt += 1
                    backoff *= 2
                    continue
                raise
    
    def epoch_from_item(item):
        """Extract epoch timestamp from log item."""
        # Prefer numeric 'timestamp' (seconds); fallback to ISO8601 'ts'
        ts_num = item.get('timestamp')
        if isinstance(ts_num, (int, float)):
            return int(ts_num)
    
        ts_iso = item.get('ts')
        if isinstance(ts_iso, str):
            try:
                # Accept "...Z" or with offset
                return int(datetime.fromisoformat(ts_iso.replace('Z', '+00:00')).timestamp())
            except Exception:
                return None
        return None
    
    • 第二个文件: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. 提供以下配置详细信息:

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

时间表频率选项

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

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

测试调度器作业

  1. Cloud Scheduler 控制台中,找到您的作业。
  2. 点击强制运行以手动触发。
  3. 等待几秒钟,然后依次前往 Cloud Run > 服务 > duo-admin-collector > 日志
  4. 验证函数是否已成功执行。
  5. 检查 GCS 存储分区,确认日志已写入。

检索 Google SecOps 服务账号

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

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

  1. 依次前往 SIEM 设置 > Feed
  2. 点击添加新 Feed
  3. 点击配置单个 Feed
  4. Feed 名称字段中,输入 Feed 的名称(例如 Duo Administrator Logs)。
  5. 选择 Google Cloud Storage V2 作为来源类型
  6. 选择 Duo 管理员日志作为日志类型
  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 以注入 Duo 管理员日志

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

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

      gs://duo-admin-logs/duo/admin/
      
        • duo-admin-logs:您的 GCS 存储分区名称。
        • duo/admin:存储日志的可选前缀/文件夹路径(留空表示根目录)。
      • 示例

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

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

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

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

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

  9. 点击下一步

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

UDM 映射表

日志字段 UDM 映射 逻辑
action metadata.product_event_type 原始日志中 action 字段的值。
降序 metadata.description 原始日志的说明对象中 desc 字段的值。
description._status target.group.attribute.labels.value 原始日志中说明对象内 _status 字段的值,尤其是在处理与群组相关的操作时。此值放置在“labels”数组中,并具有相应的“key”(即“status”)。
description.desc metadata.description 原始日志的说明对象中 desc 字段的值。
description.email target.user.email_addresses 原始日志的说明对象中电子邮件字段的值。
description.error security_result.summary 原始日志的说明对象中的错误字段的值。
description.factor extensions.auth.auth_details 原始日志的说明对象中 factor 字段的值。
description.groups.0._status target.group.attribute.labels.value 原始日志的说明对象中 groups 数组内第一个元素的 _status 字段的值。此值放置在“labels”数组中,并具有相应的“key”(即“status”)。
description.groups.0.name target.group.group_display_name 原始日志的说明对象中 groups 数组内第一个元素的 name 字段的值。
description.ip_address principal.ip 原始日志的说明对象中 ip_address 字段的值。
description.name target.group.group_display_name 原始日志的说明对象中“name”字段的值。
description.realname target.user.user_display_name 原始日志的说明对象中 realname 字段的值。
description.status target.user.attribute.labels.value 原始日志的说明对象中“status”字段的值。此值放置在“labels”数组中,并具有相应的“key”(即“status”)。
description.uname target.user.email_addresses 或 target.user.userid 原始日志的说明对象中 uname 字段的值。如果与电子邮件地址格式匹配,则映射到 email_addresses;否则,映射到 userid。
主机 principal.hostname 原始日志中 host 字段的值。
isotimestamp metadata.event_timestamp.seconds 原始日志中 isotimestamp 字段的值,已转换为纪元秒数。
对象 target.group.group_display_name 原始日志中对象字段的值。
时间戳 metadata.event_timestamp.seconds 原始日志中时间戳字段的值。
username target.user.userid 或 principal.user.userid 如果操作字段包含“login”,则该值会映射到 target.user.userid。否则,它会映射到 principal.user.userid。
- extensions.auth.mechanism 如果操作字段包含“login”,则设置为“USERNAME_PASSWORD”。
- metadata.event_type 由解析器根据操作字段确定。可能的值:USER_LOGIN、GROUP_CREATION、USER_UNCATEGORIZED、GROUP_DELETION、USER_CREATION、GROUP_MODIFICATION、GENERIC_EVENT。
- metadata.product_name 始终设置为“DUO_ADMIN”。
- metadata.product_version 始终设置为“MULTI-FACTOR_AUTHENTICATION”。
- metadata.vendor_name 始终设置为“DUO_SECURITY”。
- principal.user.user_role 如果 eventtype 字段包含“admin”,则设置为“ADMINISTRATOR”。
- security_result.action 由解析器根据操作字段确定。如果操作字段包含“error”,则设置为“BLOCK”;否则,设置为“ALLOW”。
- target.group.attribute.labels.key 填充 target.group.attribute.labels 时,始终设置为“status”。
- target.user.attribute.labels.key 填充 target.user.attribute.labels 时,始终设置为“status”。

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