收集 Duo 管理員記錄

支援的國家/地區:

本文說明如何使用 Google Cloud Storage,將 Duo 管理員記錄檔擷取至 Google Security Operations。剖析器會從記錄 (JSON 格式) 擷取欄位,並對應至統合式資料模型 (UDM)。系統會根據動作和可用資料 (包括使用者詳細資料、驗證因素和安全性結果),以不同方式處理各種 Duo 動作類型 (登入、使用者管理、群組管理),並填入相關 UDM 欄位。此外,這項服務還會執行資料轉換作業,例如合併 IP 位址、轉換時間戳記及處理錯誤。

事前準備

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

  • Google SecOps 執行個體
  • 已啟用 Cloud Storage API 的 GCP 專案
  • 建立及管理 GCS 值區的權限
  • 管理 Google Cloud Storage 值區 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. 在「Permissions」(權限) 中,啟用「Grant read log」(授予讀取記錄權限) (讀取管理員記錄)。
  6. 儲存應用程式。

建立 Google Cloud Storage 值區

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

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

為 Cloud Run 函式建立服務帳戶

Cloud Run 函式需要具備 GCS bucket 寫入權限的服務帳戶。

建立服務帳戶

  1. GCP 主控台中,依序前往「IAM & Admin」(IAM 與管理) >「Service Accounts」(服務帳戶)
  2. 按一下 [Create Service Account] (建立服務帳戶)
  3. 請提供下列設定詳細資料:
    • 服務帳戶名稱:輸入 duo-admin-collector-sa
    • 服務帳戶說明:輸入 Service account for Cloud Run function to collect Duo administrator logs
  4. 按一下「建立並繼續」
  5. 在「將專案存取權授予這個服務帳戶」部分:
    1. 按一下「選擇角色」
    2. 搜尋並選取「Storage 物件管理員」
    3. 點選「+ 新增其他角色」
    4. 搜尋並選取「Cloud Run Invoker」
    5. 點選「+ 新增其他角色」
    6. 搜尋並選取「Cloud Functions Invoker」(Cloud Functions 叫用者)
  6. 按一下「繼續」
  7. 按一下 [完成]。

這些角色適用於:

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

授予 GCS 值區的 IAM 權限

授予服務帳戶 GCS bucket 的寫入權限:

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

建立 Pub/Sub 主題

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

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

建立 Cloud Run 函式來收集記錄

Cloud Run 函式會由 Cloud Scheduler 的 Pub/Sub 訊息觸發,從 Duo Admin API 擷取記錄並寫入 GCS。

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

    設定
    服務名稱 duo-admin-collector
    區域 選取與 GCS bucket 相符的區域 (例如 us-central1)
    執行階段 選取「Python 3.12」以上版本
  5. 在「Trigger (optional)」(觸發條件 (選用)) 專區:

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

    1. 選取「需要驗證」
    2. 檢查 Identity and Access Management (IAM)
  7. 向下捲動並展開「Containers, Networking, Security」

  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
    • 「Maximum number of instances」(執行個體數量上限):輸入 100 (或根據預期負載調整)。
  14. 點選「建立」

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

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

新增函式程式碼

  1. 在「Function entry point」(函式進入點) 中輸入 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 主控台的「Cloud Scheduler」
  2. 點選「建立工作」
  3. 請提供下列設定詳細資料:

    設定
    名稱 duo-admin-collector-hourly
    區域 選取與 Cloud Run 函式相同的區域
    頻率 0 * * * * (每小時整點)
    時區 選取時區 (建議使用世界標準時間)
    目標類型 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 bucket 讀取資料。您必須授予這個服務帳戶值區存取權。

取得服務帳戶電子郵件地址

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

    chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com
    
  8. 複製這個電子郵件地址,以便在下一步中使用。

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

Google SecOps 服務帳戶需要 GCS bucket 的「Storage 物件檢視者」角色。

  1. 依序前往「Cloud Storage」>「Buckets」
  2. 按一下 bucket 名稱。
  3. 前往「權限」分頁標籤。
  4. 按一下「授予存取權」
  5. 請提供下列設定詳細資料:
    • 新增主體:貼上 Google SecOps 服務帳戶電子郵件地址。
    • 指派角色:選取「Storage 物件檢視者」
  6. 按一下 [儲存]

在 Google SecOps 中設定動態饋給,擷取 Duo 管理員記錄

  1. 依序前往「SIEM 設定」>「動態饋給」
  2. 按一下「新增動態消息」
  3. 按一下「設定單一動態饋給」
  4. 在「動態饋給名稱」欄位中輸入動態饋給名稱 (例如 Duo Administrator Logs)。
  5. 選取「Google Cloud Storage V2」做為「來源類型」
  6. 選取「Duo 管理員記錄」做為「記錄類型」
  7. 點選 [下一步]。
  8. 指定下列輸入參數的值:

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

      gs://duo-admin-logs/duo/admin/
      
      • 取代:

        • duo-admin-logs:您的 GCS bucket 名稱。
        • duo/admin:儲存記錄的選用前置字元/資料夾路徑 (如為根目錄,請留空)。
      • 範例:

        • 根層級 bucket:gs://company-logs/
        • 前置字串:gs://company-logs/duo-logs/
        • 有子資料夾:gs://company-logs/duo/admin/
    • 來源刪除選項:根據偏好設定選取刪除選項:

      • 永不:移轉後一律不刪除任何檔案 (建議用於測試)。
      • 刪除已轉移的檔案:成功轉移檔案後刪除檔案。
      • 刪除已轉移的檔案和空白目錄:成功轉移後刪除檔案和空白目錄。

    • 檔案存在時間上限:包含在過去天數內修改的檔案。預設值為 180 天。

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

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

  9. 點選 [下一步]。

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

UDM 對應表

記錄欄位 UDM 對應 邏輯
動作 metadata.product_event_type 原始記錄中的動作欄位值。
遞減 metadata.description 原始記錄說明物件中 desc 欄位的值。
description._status target.group.attribute.labels.value 原始記錄中說明物件內的 _status 欄位值,特別是在處理群組相關動作時。這個值會放在「labels」陣列中,並對應「status」的「key」。
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」陣列中,並對應「status」的「key」。
description.groups.0.name target.group.group_display_name 原始記錄說明物件中,群組陣列第一個元素名稱欄位的值。
description.ip_address principal.ip 原始記錄說明物件中的 ip_address 欄位值。
description.name target.group.group_display_name 原始記錄說明物件中「名稱」欄位的值。
description.realname target.user.user_display_name 原始記錄說明物件中的 realname 欄位值。
description.status target.user.attribute.labels.value 原始記錄說明物件的狀態欄位值。這個值會放在「labels」陣列中,並對應「status」的「key」。
description.uname target.user.email_addresses 或 target.user.userid 原始記錄描述物件中的 uname 欄位值。如果符合電子郵件地址格式,則會對應至 email_addresses;否則會對應至 userid。
主機 principal.hostname 原始記錄中的主機欄位值。
isotimestamp metadata.event_timestamp.seconds 原始記錄中 isotimestamp 欄位的值,已轉換為 Epoch 秒數。
物件 target.group.group_display_name 原始記錄中的物件欄位值。
時間戳記 metadata.event_timestamp.seconds 原始記錄中的時間戳記欄位值。
使用者名稱 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 專業人員尋求答案。