收集 URLScan IO 記錄
本文說明如何使用 Google Cloud Storage,將 URLScan IO 記錄檔擷取至 Google Security Operations。URLScan IO 是一項服務,可分析網站並提供網站行為、安全性及效能的詳細資訊。這項工具會掃描網址並產生完整報表,包括螢幕截圖、HTTP 交易、DNS 記錄和威脅情報資料。
事前準備
請確認您已完成下列事前準備事項:
- Google SecOps 執行個體
- 已啟用 Cloud Storage API 的 GCP 專案
- 建立及管理 GCS 值區的權限
- 管理 Google Cloud Storage 值區 IAM 政策的權限
- 建立 Cloud Run 服務、Pub/Sub 主題和 Cloud Scheduler 工作的權限
- URLScan IO 租戶的特殊存取權
取得 URLScan IO 的必要條件
- 登入 URLScan IO。
- 按一下個人資料圖示。
- 從選單中選取「API 金鑰」。
- 如果您尚未拿到 API 金鑰:
- 按一下「建立 API 金鑰」按鈕。
- 輸入 API 金鑰的說明 (例如
Google SecOps Integration)。 - 點按「Generate API Key」(產生 API 金鑰)。
- 複製並儲存以下詳細資料,存放在安全的位置:
- API_KEY:產生的 API 金鑰字串 (格式:
xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) - API 基準網址:
https://urlscan.io/api/v1(所有使用者皆相同)
- API_KEY:產生的 API 金鑰字串 (格式:
- 請注意 API 配額限制:
- 免費和專業版帳戶設有每分鐘、每小時和每日限制,各項動作的限制有所不同。如要瞭解確切限制,請查看個人配額或 API 速率限制標頭。
- 詳情請參閱 URLScan IO API 使用頻率限制說明文件。
如要將搜尋範圍限制在貴機構的掃描結果,請記下:
- 使用者 ID:您的使用者名稱或電子郵件地址 (用於
user:搜尋篩選器) - 團隊 ID:如果使用團隊功能 (適用於
team:搜尋篩選器)
- 使用者 ID:您的使用者名稱或電子郵件地址 (用於
驗證 API 存取權
請先測試 API 金鑰,再繼續進行整合:
# Replace with your actual API key API_KEY="your-api-key-here" # Test API access curl -v -H "API-Key: ${API_KEY}" "https://urlscan.io/api/v1/search/?q=date:>now-1h&size=1"
預期回應:HTTP 200,其中包含搜尋結果的 JSON。
如果收到 HTTP 401 或 403 錯誤,請確認 API 金鑰正確無誤且尚未過期。
建立 Google Cloud Storage 值區
- 前往 Google Cloud 控制台。
- 選取專案或建立新專案。
- 在導覽選單中,依序前往「Cloud Storage」>「Bucket」。
- 按一下「建立值區」。
請提供下列設定詳細資料:
設定 值 為 bucket 命名 輸入全域不重複的名稱 (例如 urlscan-logs-bucket)位置類型 根據需求選擇 (區域、雙區域、多區域) 位置 選取位置 (例如 us-central1)儲存空間級別 標準 (建議用於經常存取的記錄) 存取控管 統一 (建議) 保護工具 選用:啟用物件版本管理或保留政策 點選「建立」。
為 Cloud Run 函式建立服務帳戶
Cloud Run 函式需要具備 GCS bucket 寫入權限的服務帳戶,並由 Pub/Sub 叫用。
建立服務帳戶
- 在 GCP 主控台中,依序前往「IAM & Admin」(IAM 與管理) >「Service Accounts」(服務帳戶)。
- 按一下 [Create Service Account] (建立服務帳戶)。
- 請提供下列設定詳細資料:
- 服務帳戶名稱:輸入
urlscan-collector-sa。 - 服務帳戶說明:輸入
Service account for Cloud Run function to collect URLScan IO logs。
- 服務帳戶名稱:輸入
- 按一下「建立並繼續」。
- 在「將專案存取權授予這個服務帳戶」部分,新增下列角色:
- 按一下「選擇角色」。
- 搜尋並選取「Storage 物件管理員」。
- 點選「+ 新增其他角色」。
- 搜尋並選取「Cloud Run Invoker」。
- 點選「+ 新增其他角色」。
- 搜尋並選取「Cloud Functions Invoker」(Cloud Functions 叫用者)。
- 按一下「繼續」。
- 按一下 [完成]。
這些角色適用於:
- Storage 物件管理員:將記錄檔寫入 GCS 值區,並管理狀態檔案
- Cloud Run 叫用者:允許 Pub/Sub 叫用函式
- Cloud Functions 叫用者:允許函式叫用
授予 GCS 值區的 IAM 權限
授予服務帳戶 GCS bucket 的寫入權限:
- 依序前往「Cloud Storage」>「Buckets」。
- 按一下 bucket 名稱。
- 前往「權限」分頁標籤。
- 按一下「授予存取權」。
- 請提供下列設定詳細資料:
- 新增主體:輸入服務帳戶電子郵件地址 (例如
urlscan-collector-sa@PROJECT_ID.iam.gserviceaccount.com)。 - 指派角色:選取「Storage 物件管理員」。
- 新增主體:輸入服務帳戶電子郵件地址 (例如
- 按一下 [儲存]。
建立 Pub/Sub 主題
建立 Pub/Sub 主題,Cloud Scheduler 會將訊息發布至該主題,而 Cloud Run 函式會訂閱該主題。
- 在 GCP Console 中,前往「Pub/Sub」>「Topics」(主題)。
- 按一下「建立主題」。
- 請提供下列設定詳細資料:
- 主題 ID:輸入
urlscan-logs-trigger。 - 其他設定保留預設值。
- 主題 ID:輸入
- 點選「建立」。
建立 Cloud Run 函式來收集記錄
Cloud Run 函式會由 Cloud Scheduler 的 Pub/Sub 訊息觸發,從 URLScan IO API 擷取記錄,並將記錄寫入 GCS。
- 前往 GCP Console 的「Cloud Run」。
- 按一下「Create service」(建立服務)。
- 選取「函式」 (使用內嵌編輯器建立函式)。
在「設定」部分,提供下列設定詳細資料:
設定 值 服務名稱 urlscan-collector區域 選取與 GCS bucket 相符的區域 (例如 us-central1)執行階段 選取「Python 3.12」以上版本 在「Trigger (optional)」(觸發條件 (選用)) 專區:
- 按一下「+ 新增觸發條件」。
- 選取「Cloud Pub/Sub」。
- 在「選取 Cloud Pub/Sub 主題」中,選擇 Pub/Sub 主題 (
urlscan-logs-trigger)。 - 按一下 [儲存]。
在「Authentication」(驗證) 部分:
- 選取「需要驗證」。
- 檢查 Identity and Access Management (IAM)。
向下捲動並展開「Containers, Networking, Security」。
前往「安全性」分頁:
- 服務帳戶:選取服務帳戶 (
urlscan-collector-sa)。
- 服務帳戶:選取服務帳戶 (
前往「容器」分頁:
- 按一下「變數與密鑰」。
- 針對每個環境變數,按一下「+ 新增變數」:
變數名稱 範例值 說明 GCS_BUCKETurlscan-logs-bucketGCS bucket 名稱 GCS_PREFIXurlscan/記錄檔的前置字串 STATE_KEYurlscan/state.json狀態檔案路徑 API_KEYyour-urlscan-api-keyURLScan IO API 金鑰 API_BASEhttps://urlscan.io/api/v1API 基礎網址 SEARCH_QUERYdate:>now-1h搜尋查詢篩選器 PAGE_SIZE100每頁記錄數 MAX_PAGES10要擷取的頁面數量上限 在「變數與密鑰」部分,向下捲動至「要求」:
- 要求逾時:輸入
600秒 (10 分鐘)。
- 要求逾時:輸入
前往「設定」分頁:
- 在「資源」部分:
- 記憶體:選取 512 MiB 以上。
- CPU:選取 1。
- 在「資源」部分:
在「修訂版本資源調度」部分:
- 執行個體數量下限:輸入
0。 - 「Maximum number of instances」(執行個體數量上限):輸入
100(或根據預期負載調整)。
- 執行個體數量下限:輸入
點選「建立」。
等待服務建立完成 (1 到 2 分鐘)。
服務建立完成後,系統會自動開啟內嵌程式碼編輯器。
新增函式程式碼
- 在「Function entry point」(函式進入點) 中輸入 main
在內嵌程式碼編輯器中建立兩個檔案:
- 第一個檔案:main.py:
import functions_framework from google.cloud import storage import json import os import urllib3 from datetime import datetime, timedelta, timezone 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', 'urlscan/') STATE_KEY = os.environ.get('STATE_KEY', 'urlscan/state.json') API_KEY = os.environ.get('API_KEY') API_BASE = os.environ.get('API_BASE', 'https://urlscan.io/api/v1') SEARCH_QUERY = os.environ.get('SEARCH_QUERY', 'date:>now-1h') PAGE_SIZE = int(os.environ.get('PAGE_SIZE', '100')) MAX_PAGES = int(os.environ.get('MAX_PAGES', '10')) 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 URLScan IO results 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: # Get GCS bucket bucket = storage_client.bucket(GCS_BUCKET) # Load state state = load_state(bucket, STATE_KEY) last_run = state.get('last_run') # Adjust search query based on last run search_query = SEARCH_QUERY if last_run: try: search_time = parse_datetime(last_run) time_diff = datetime.now(timezone.utc) - search_time hours = int(time_diff.total_seconds() / 3600) + 1 search_query = f'date:>now-{hours}h' except Exception as e: print(f'Warning: Could not parse last_run: {e}') print(f'Searching with query: {search_query}') # Fetch logs records, newest_event_time = fetch_logs( api_base=API_BASE, api_key=API_KEY, search_query=search_query, page_size=PAGE_SIZE, max_pages=MAX_PAGES, ) if not records: print("No new log records found.") now = datetime.now(timezone.utc) save_state(bucket, STATE_KEY, now.isoformat()) return # Write to GCS as NDJSON now = datetime.now(timezone.utc) file_key = f"{GCS_PREFIX}year={now.year}/month={now.month:02d}/day={now.day:02d}/hour={now.hour:02d}/urlscan_{now.strftime('%Y%m%d_%H%M%S')}.json" ndjson_content = '\n'.join([json.dumps(r, separators=(',', ':')) for r in records]) blob = bucket.blob(file_key) blob.upload_from_string( ndjson_content, content_type='application/x-ndjson' ) print(f"Uploaded {len(records)} results to gs://{GCS_BUCKET}/{file_key}") # Update state with newest event time 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)} scan results') 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, last_event_time_iso: str): """Save the last event timestamp to GCS state file.""" try: state = {'last_run': 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_run={last_event_time_iso}") except Exception as e: print(f'Warning: Could not save state: {str(e)}') def fetch_logs(api_base: str, api_key: str, search_query: str, page_size: int, max_pages: int): """ Fetch logs from URLScan IO API with pagination and rate limiting. Args: api_base: API base URL api_key: URLScan IO API key search_query: Search query string page_size: Number of records per page max_pages: Maximum total pages to fetch Returns: Tuple of (records list, newest_event_time ISO string) """ headers = { 'API-Key': api_key, 'Accept': 'application/json', 'User-Agent': 'GoogleSecOps-URLScanCollector/1.0' } all_results = [] newest_time = None page_num = 0 backoff = 1.0 offset = 0 while page_num < max_pages: page_num += 1 # Build search URL with pagination search_url = f"{api_base}/search/" params = [ f"q={search_query}", f"size={page_size}", f"offset={offset}" ] url = f"{search_url}?{'&'.join(params)}" try: response = http.request('GET', url, headers=headers) # Handle rate limiting with exponential backoff 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"Search failed: {response.status}") response_text = response.data.decode('utf-8') print(f"Response body: {response_text}") break search_data = json.loads(response.data.decode('utf-8')) results = search_data.get('results', []) if not results: print(f"No more results (empty page)") break print(f"Page {page_num}: Retrieved {len(results)} scan results") # Fetch full result for each scan for result in results: task = result.get('task', {}) uuid = task.get('uuid') if uuid: result_url = f"{api_base}/result/{uuid}/" try: result_response = http.request('GET', result_url, headers=headers) # Handle rate limiting if result_response.status == 429: retry_after = int(result_response.headers.get('Retry-After', '5')) print(f"Rate limited on result fetch. Retrying after {retry_after}s...") time.sleep(retry_after) result_response = http.request('GET', result_url, headers=headers) if result_response.status == 200: full_result = json.loads(result_response.data.decode('utf-8')) all_results.append(full_result) # Track newest event time try: event_time = task.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}") else: print(f"Failed to fetch result for {uuid}: {result_response.status}") except Exception as e: print(f"Error fetching result for {uuid}: {e}") # Check if we have more pages total = search_data.get('total', 0) if offset + len(results) >= total or len(results) < page_size: print(f"Reached last page (offset={offset}, results={len(results)}, total={total})") break offset += len(results) except Exception as e: print(f"Error fetching logs: {e}") return [], None print(f"Retrieved {len(all_results)} total records from {page_num} pages") return all_results, newest_time- 第二個檔案:requirements.txt:
functions-framework==3.* google-cloud-storage==2.* urllib3>=2.0.0點選「部署」來儲存並部署函式。
等待部署作業完成 (2 到 3 分鐘)。
建立 Cloud Scheduler 工作
Cloud Scheduler 會定期將訊息發布至 Pub/Sub 主題,觸發 Cloud Run 函式。
- 前往 GCP 主控台的「Cloud Scheduler」。
- 點選「建立工作」。
請提供下列設定詳細資料:
設定 值 名稱 urlscan-collector-hourly區域 選取與 Cloud Run 函式相同的區域 頻率 0 * * * *(每小時整點)時區 選取時區 (建議使用世界標準時間) 目標類型 Pub/Sub 主題 選取 Pub/Sub 主題 ( urlscan-logs-trigger)郵件內文 {}(空白 JSON 物件)點選「建立」。
排程頻率選項
根據記錄檔量和延遲時間要求選擇頻率:
頻率 Cron 運算式 用途 每 5 分鐘 */5 * * * *高容量、低延遲 每 15 分鐘檢查一次 */15 * * * *普通量 每小時 0 * * * *標準 (建議採用) 每 6 小時 0 */6 * * *少量、批次處理 每日 0 0 * * *歷來資料集合
測試整合項目
- 在 Cloud Scheduler 控制台中,找出您的作業 (
urlscan-collector-hourly)。 - 按一下「強制執行」,手動觸發工作。
- 稍等幾秒鐘。
- 前往「Cloud Run」>「Services」。
- 按一下函式名稱 (
urlscan-collector)。 - 按一下 [Logs] (記錄) 分頁標籤。
確認函式是否已順利執行。請找出以下項目:
Searching with query: date:>now-1h Page 1: Retrieved X scan results Uploaded X results to gs://bucket-name/urlscan/year=YYYY/month=MM/day=DD/hour=HH/urlscan_YYYYMMDD_HHMMSS.json Successfully processed X scan results依序前往「Cloud Storage」>「Buckets」。
按一下 bucket 名稱。
前往前置字元資料夾 (
urlscan/)。確認是否已建立含有目前時間戳記的新
.json檔案。
如果在記錄中發現錯誤:
- HTTP 401:檢查環境變數中的 API 金鑰
- HTTP 403:確認 API 金鑰未過期
- HTTP 429:頻率限制 - 函式會自動重試並延遲
- 缺少環境變數:檢查是否已設定所有必要變數
- 搜尋失敗:確認搜尋查詢語法是否正確
擷取 Google SecOps 服務帳戶
Google SecOps 會使用專屬服務帳戶,從 GCS bucket 讀取資料。您必須授予這個服務帳戶值區存取權。
取得服務帳戶電子郵件地址
- 依序前往「SIEM 設定」>「動態饋給」。
- 按一下「新增動態消息」。
- 按一下「設定單一動態饋給」。
- 在「動態饋給名稱」欄位中輸入動態饋給名稱 (例如
URLScan IO logs)。 - 選取「Google Cloud Storage V2」做為「來源類型」。
- 選取「URLScan IO」做為「記錄類型」。
按一下「取得服務帳戶」。系統會顯示專屬的服務帳戶電子郵件地址,例如:
chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com複製這個電子郵件地址,以便在下一步中使用。
將 IAM 權限授予 Google SecOps 服務帳戶
Google SecOps 服務帳戶需要 GCS bucket 的「Storage 物件檢視者」角色。
- 依序前往「Cloud Storage」>「Buckets」。
- 按一下 bucket 名稱。
- 前往「權限」分頁標籤。
- 按一下「授予存取權」。
- 請提供下列設定詳細資料:
- 新增主體:貼上 Google SecOps 服務帳戶電子郵件地址。
- 指派角色:選取「Storage 物件檢視者」。
按一下 [儲存]。
在 Google SecOps 中設定動態消息,擷取 URLScan IO 記錄
- 依序前往「SIEM 設定」>「動態饋給」。
- 按一下「新增動態消息」。
- 按一下「設定單一動態饋給」。
- 在「動態饋給名稱」欄位中輸入動態饋給名稱 (例如
URLScan IO logs)。 - 選取「Google Cloud Storage V2」做為「來源類型」。
- 選取「URLScan IO」做為「記錄類型」。
- 點選 [下一步]。
指定下列輸入參數的值:
儲存空間 bucket URL:輸入 GCS bucket URI,並加上前置路徑:
gs://urlscan-logs-bucket/urlscan/取代:
urlscan-logs-bucket:您的 GCS bucket 名稱。urlscan/:儲存記錄的選用前置字元/資料夾路徑 (如為根目錄,請留空)。範例:
- 根層級 bucket:
gs://urlscan-logs-bucket/ - 前置字串:
gs://urlscan-logs-bucket/urlscan/
- 根層級 bucket:
來源刪除選項:根據偏好設定選取刪除選項:
- 永不:移轉後一律不刪除任何檔案 (建議用於測試)。
- 刪除已轉移的檔案:成功轉移檔案後刪除檔案。
刪除已轉移的檔案和空白目錄:成功轉移後刪除檔案和空白目錄。
檔案存在時間上限:包含在過去天數內修改的檔案。預設值為 180 天。
資產命名空間:資產命名空間。
擷取標籤:要套用至這個動態饋給事件的標籤。
點選 [下一步]。
在「Finalize」(完成) 畫面中檢查新的動態饋給設定,然後按一下「Submit」(提交)。
需要其他協助嗎?向社群成員和 Google SecOps 專業人員尋求答案。