收集 Sonrai Security 記錄
本文說明如何使用 Google Cloud Storage V2,將 Sonrai Security 記錄檔擷取至 Google Security Operations。
Sonrai Security 是企業雲端安全平台,可跨多雲端環境管理身分、資料和存取權管理。並透過 GraphQL API 提供安全性發現項目、票證和稽核資料。
事前準備
請確認您符合下列必要條件:
- Google SecOps 執行個體
- 已啟用 Cloud Storage API 的 GCP 專案
- 建立及管理 GCS bucket 的權限
- 具備管理 GCS bucket IAM 政策的權限
- 建立 Cloud Run 服務、Pub/Sub 主題和 Cloud Scheduler 工作的權限
- 具備管理員權限和 API 金鑰存取權,可特殊存取 Sonrai Security
建立 Google Cloud Storage bucket
- 前往 Google Cloud 控制台。
- 選取專案或建立新專案。
- 在導覽選單中,依序前往「Cloud Storage」>「Bucket」。
- 按一下「建立值區」。
提供下列設定詳細資料:
設定 值 為 bucket 命名 輸入全域不重複的名稱 (例如 sonrai-security-logs)位置類型 請根據需求選擇 (單一區域、雙區域、多區域) 位置 選取位置 (例如 us-central1)儲存空間級別 標準 (建議用於經常存取的記錄) 存取控管 統一 (建議) 保護工具 選用:啟用物件版本管理或資料保留政策 點選「建立」。
收集 Sonrai Security API 憑證
產生 API 金鑰
- 以管理員身分登入 Sonrai Security 平台。
- 依序前往「Settings」>「API Keys」。
- 點選「建立 API 金鑰」。
- 輸入金鑰名稱 (例如
Google Security Operations Integration)。 - 複製產生的 API 金鑰,並儲存在安全的位置。
判斷機構網址
API 端點取決於您的 Sonrai Security 組織。格式為:
| 元件 | 值 |
|---|---|
| GraphQL 端點 | https://YOUR_ORG.sonraisecurity.com/graphql |
驗證權限
如要確認 API 金鑰具備必要存取權,請按照下列步驟操作:
- 登入 Sonrai Security 平台。
- 依序前往「Settings」>「API Keys」。
- 確認 API 金鑰已列出且有效。
- 確認金鑰具備查詢支援單、發現項目和稽核資料的權限。
- 如果權限受限,請與 Sonrai Security 管理員聯絡。
測試 API 存取權
請先測試憑證,再繼續整合:
# Replace with your actual credentials API_KEY="your-api-key" ORG_URL="https://YOUR_ORG.sonraisecurity.com" # Test API access - query tickets curl -v -X POST \ -H "Authorization: Bearer ${API_KEY}" \ -H "Content-Type: application/json" \ -d '{"query": "{ Tickets(where: {createdDate: {op: GT, value: \"2024-01-01T00:00:00Z\"}}) { count } }"}' \ "${ORG_URL}/graphql"
建立 Cloud Run 函式的服務帳戶
Cloud Run 函式需要服務帳戶,且該帳戶須具備寫入 GCS bucket 的權限,並可由 Pub/Sub 叫用。
建立服務帳戶
- 在 GCP 控制台中,依序前往「IAM & Admin」(IAM 與管理) >「Service Accounts」(服務帳戶)。
- 按一下「Create Service Account」(建立服務帳戶)。
- 提供下列設定詳細資料:
- 服務帳戶名稱:輸入
sonrai-collector-sa。 - 「Service account description」(服務帳戶說明):輸入
Service account for Cloud Run function to collect Sonrai Security logs。
- 服務帳戶名稱:輸入
- 按一下「建立並繼續」。
- 在「將專案存取權授予這個服務帳戶」部分,新增下列角色:
- 按一下「請選擇角色」。
- 搜尋並選取「Storage 物件管理員」。
- 點選「+ 新增其他角色」。
- 搜尋並選取「Cloud Run Invoker」。
- 點選「+ 新增其他角色」。
- 搜尋並選取「Cloud Functions 叫用者」。
- 按一下「繼續」。
- 按一下「完成」。
這些角色適用於:
- Storage 物件管理員:將記錄檔寫入 GCS bucket 並管理狀態檔案
- Cloud Run 叫用者:允許 Pub/Sub 叫用函式
- Cloud Functions 叫用者:允許叫用函式
授予 GCS bucket 的 IAM 權限
授予服務帳戶 GCS bucket 的寫入權限:
- 依序前往「Cloud Storage」>「Bucket」。
- 按一下 bucket 名稱 (例如
sonrai-security-logs)。 - 前往「權限」分頁。
- 按一下「授予存取權」。
- 提供下列設定詳細資料:
- 新增主體:輸入服務帳戶電子郵件地址 (例如
sonrai-collector-sa@your-project.iam.gserviceaccount.com)。 - 指派角色:選取「Storage 物件管理員」。
- 新增主體:輸入服務帳戶電子郵件地址 (例如
- 按一下「儲存」。
建立 Pub/Sub 主題
建立 Pub/Sub 主題,Cloud Scheduler 會發布至該主題,Cloud Run 函式則會訂閱該主題。
- 在 GCP 控制台中,依序前往「Pub/Sub」>「主題」。
- 按一下「建立主題」。
- 提供下列設定詳細資料:
- 主題 ID:輸入
sonrai-trigger。 - 其他設定保留預設值。
- 主題 ID:輸入
- 點選「建立」。
建立 Cloud Run 函式來收集記錄
Cloud Scheduler 傳送 Pub/Sub 訊息時,會觸發 Cloud Run 函式,從 Sonrai Security GraphQL API 擷取記錄,並寫入 GCS。
- 在 GCP 控制台中,前往「Cloud Run」。
- 按一下「Create service」(建立服務)。
- 選取「函式」(使用直接修改建立函式)。
在「Configure」(設定) 部分,提供下列設定詳細資料:
設定 值 服務名稱 sonrai-collector區域 選取與 GCS bucket 相符的區域 (例如 us-central1)執行階段 選取「Python 3.12」或更新版本 在「Trigger (optional)」(觸發條件 (選用)) 部分:
- 按一下「+ 新增觸發條件」。
- 選取「Cloud Pub/Sub」。
- 在「Select a Cloud Pub/Sub topic」(選取 Cloud Pub/Sub 主題) 中,選擇主題
sonrai-trigger。 - 按一下「儲存」。
在「Authentication」(驗證) 部分:
- 選取「需要驗證」。
- Identity and Access Management (IAM)。
向下捲動並展開「容器、網路、安全性」。
前往「安全性」分頁:
- 「Service account」(服務帳戶):選取服務帳戶
sonrai-collector-sa。
- 「Service account」(服務帳戶):選取服務帳戶
前往「容器」分頁:
- 按一下「Variables & Secrets」(變數與密鑰)。
- 針對每個環境變數,按一下「+ 新增變數」:
變數名稱 範例值 說明 GCS_BUCKETsonrai-security-logsGCS bucket 名稱 GCS_PREFIXsonrai記錄檔的前置字串 STATE_KEYsonrai/state.json狀態檔案路徑 API_KEYyour-api-keySonrai Security API 金鑰 ORG_URLhttps://YOUR_ORG.sonraisecurity.comSonrai 組織網址 MAX_RECORDS10000每次執行的記錄數上限 PAGE_SIZE500每頁記錄數 LOOKBACK_HOURS24初始回溯期 在「變數與密鑰」分頁中,向下捲動至「要求」:
- 要求逾時:輸入
600秒 (10 分鐘)。
- 要求逾時:輸入
前往「容器」的「設定」分頁:
- 在「Resources」(資源) 部分:
- 「記憶體」:選取「512 MiB」或以上。
- CPU:選取「1」。
- 在「Resources」(資源) 部分:
在「Revision scaling」(修訂版本資源調度) 部分:
- 「Minimum number of instances」(執行個體數量下限):輸入
0。 - 「執行個體數量上限」:輸入
100(或依預期負載調整)。
- 「Minimum number of instances」(執行個體數量下限):輸入
點選「建立」。
等待服務建立完成 (1 至 2 分鐘)。
服務建立後,內嵌程式碼編輯器會自動開啟。
新增函式程式碼
- 在「函式進入點」中輸入 main。
在內嵌程式碼編輯器中,建立兩個檔案:
第一個檔案: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', 'sonrai') STATE_KEY = os.environ.get('STATE_KEY', 'sonrai/state.json') API_KEY = os.environ.get('API_KEY', '') ORG_URL = os.environ.get('ORG_URL', '').rstrip('/') MAX_RECORDS = int(os.environ.get('MAX_RECORDS', '10000')) PAGE_SIZE = int(os.environ.get('PAGE_SIZE', '500')) LOOKBACK_HOURS = int(os.environ.get('LOOKBACK_HOURS', '24')) 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 Sonrai Security logs and write to GCS. Args: cloud_event: CloudEvent object containing Pub/Sub message """ if not all([GCS_BUCKET, API_KEY, ORG_URL]): print('Error: Missing required environment variables') return try: bucket = storage_client.bucket(GCS_BUCKET) # Load state state = load_state(bucket, STATE_KEY) # Determine time window now = datetime.now(timezone.utc) last_time = None if isinstance(state, dict) and state.get("last_event_time"): try: last_time = parse_datetime(state["last_event_time"]) last_time = last_time - timedelta(minutes=2) except Exception as e: print(f"Warning: Could not parse last_event_time: {e}") if last_time is None: last_time = now - timedelta(hours=LOOKBACK_HOURS) print(f"Fetching tickets from {last_time.isoformat()} to {now.isoformat()}") # Fetch tickets/findings records, newest_event_time = fetch_tickets( start_time=last_time, end_time=now, page_size=PAGE_SIZE, max_records=MAX_RECORDS, ) if not records: print("No new records found.") save_state(bucket, STATE_KEY, now.isoformat()) return # Write to GCS as NDJSON timestamp = now.strftime('%Y%m%d_%H%M%S') object_key = f"{GCS_PREFIX}/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}") 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)} records") 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_event_time_iso: str): """Save the last event timestamp to GCS state file.""" try: state = {'last_event_time': 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_event_time={last_event_time_iso}") except Exception as e: print(f"Warning: Could not save state: {e}") def graphql_query(query: str): """Execute a GraphQL query against Sonrai Security API with rate limiting.""" endpoint = f"{ORG_URL}/graphql" headers = { 'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json', 'Accept': 'application/json', 'User-Agent': 'GoogleSecOps-SonraiCollector/1.0' } body = json.dumps({'query': query}) backoff = 1.0 max_retries = 3 for attempt in range(max_retries): response = http.request('POST', endpoint, body=body.encode('utf-8'), 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 data = json.loads(response.data.decode('utf-8')) if 'errors' in data: print(f"GraphQL errors: {json.dumps(data['errors'])}") return None return data.get('data') print(f"Failed after {max_retries} retries due to rate limiting") return None def fetch_tickets(start_time: datetime, end_time: datetime, page_size: int, max_records: int): """ Fetch tickets from Sonrai Security GraphQL API with pagination and rate limiting. """ records = [] newest_time = None page_num = 0 offset = 0 start_iso = start_time.strftime('%Y-%m-%dT%H:%M:%SZ') while True: page_num += 1 if len(records) >= max_records: print(f"Reached max_records limit ({max_records})") break current_limit = min(page_size, max_records - len(records)) query = f"""{{ Tickets( where: {{createdDate: {{op: GT, value: \"{start_iso}\"}}}} limit: {current_limit} offset: {offset} ) {{ count items {{ srn title severity status createdDate updatedDate resourceSrn eventName actionType sourceIp actor {{ profile {{ srn name }} }} message }} }} }}""" data = graphql_query(query) if not data: break tickets_data = data.get('Tickets', {}) page_results = tickets_data.get('items', []) if not page_results: print(f"No more results (empty page)") break print(f"Page {page_num}: Retrieved {len(page_results)} tickets") records.extend(page_results) # Track newest event time for ticket in page_results: try: event_time = ticket.get('createdDate') 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}") if len(page_results) < current_limit: print(f"Reached last page (size={len(page_results)} < limit={current_limit})") break offset += len(page_results) print(f"Retrieved {len(records)} total records from {page_num} pages") return records, 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」。
- 點選「建立工作」。
提供下列設定詳細資料:
設定 值 名稱 sonrai-collector-hourly區域 選取與 Cloud Run 函式相同的區域 頻率 0 * * * *(每小時整點)時區 選取時區 (建議選取世界標準時間) 目標類型 Pub/Sub 主題 選取主題「 sonrai-trigger」郵件內文 {}(空白 JSON 物件)點選「建立」。
排程頻率選項
根據記錄量和延遲時間需求選擇頻率:
| 頻率 | Cron 運算式 | 用途 |
|---|---|---|
| 每 5 分鐘 | */5 * * * * |
高流量、低延遲 |
| 每 15 分鐘 | */15 * * * * |
中等音量 |
| 每小時 | 0 * * * * |
標準 (建議) |
| 每 6 小時 | 0 */6 * * * |
低量、批次處理 |
| 每天 | 0 0 * * * |
歷來資料集合 |
測試整合
- 在 Cloud Scheduler 控制台中,找到您的工作 (
sonrai-collector-hourly)。 - 按一下「強制執行」,手動觸發。
- 稍候幾秒,然後依序前往「Cloud Run」>「服務」>「sonrai-collector」>「記錄」。
確認函式是否執行成功。尋找:
Fetching tickets from YYYY-MM-DDTHH:MM:SS+00:00 to YYYY-MM-DDTHH:MM:SS+00:00 Page 1: Retrieved X tickets Wrote X records to gs://sonrai-security-logs/sonrai/logs_YYYYMMDD_HHMMSS.ndjson Successfully processed X records檢查 GCS bucket (
sonrai-security-logs),確認記錄已寫入。
如果記錄中顯示錯誤:
- HTTP 401:檢查環境變數中的 API 金鑰
- HTTP 403:確認 API 金鑰在 Sonrai Security 平台中具備必要權限
- HTTP 429:頻率限制 - 函式會自動重試,並採用輪詢機制
- GraphQL 錯誤:確認查詢語法和可用欄位
在 Google SecOps 設定動態饋給,擷取 Sonrai Security 記錄
- 依序前往「設定」>「資料管理」>「動態饋給」。如果使用的是 SIEM 專用平台,請依序前往「設定」>「動態饋給」。
- 按一下「新增動態饋給」。
- 按一下「設定單一動態饋給」。
- 在「Feed name」(動態饋給名稱) 欄位中,輸入動態饋給名稱 (例如
Sonrai Security Logs)。 - 選取「Google Cloud Storage V2」做為「來源類型」。
- 選取「Sonrai Enterprise Cloud Security Solution」做為「記錄類型」。
按一下「Get Service Account」。系統會顯示專屬服務帳戶電子郵件地址,例如:
chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com複製這個電子郵件地址。後續步驟會用到。
點選「下一步」。
指定下列輸入參數的值:
Storage bucket URL:輸入 GCS bucket URI,並加上前置字元路徑:
gs://sonrai-security-logs/sonrai/- 取代:
sonrai-security-logs:GCS bucket 名稱。sonrai:儲存記錄檔的選用前置字元/資料夾路徑 (留空則為根目錄)。
- 取代:
來源刪除選項:根據偏好選取刪除選項:
- Never:轉移後一律不刪除任何檔案 (建議用於測試)。
- 刪除已轉移的檔案:在成功轉移後刪除檔案。
刪除已轉移的檔案和空白目錄:成功轉移後,刪除檔案和空白目錄。
檔案存在時間上限:納入過去幾天內修改過的檔案 (預設為 180 天)。
Asset namespace:資產命名空間。
擷取標籤:要套用至這個動態饋給事件的標籤。
點選「下一步」。
在「完成」畫面中檢查新的新聞動態消息設定,然後按一下「提交」。
將 IAM 權限授予 Google SecOps 服務帳戶
Google SecOps 服務帳戶需要 GCS bucket 的 Storage 物件檢視者角色。
- 依序前往「Cloud Storage」>「Bucket」。
- 按一下 bucket 名稱 (
sonrai-security-logs)。 - 前往「權限」分頁。
- 按一下「授予存取權」。
- 提供下列設定詳細資料:
- 新增主體:貼上 Google SecOps 服務帳戶電子郵件地址。
- 指派角色:選取「Storage 物件檢視者」。
按一下「儲存」。
UDM 對應表
| 記錄欄位 | UDM 對應 | 邏輯 |
|---|---|---|
| actor.profile | principal.resource.attribute.labels | 與資源相關聯的標籤 |
| actor.profile.srn | target.user.product_object_id | 使用者的產品專屬物件 ID |
| actor.profile.srn | target.user.userid | 使用者 ID |
| actorSrn、variables、gql、type | additional.fields | UDM 結構定義中其他地方未擷取的額外欄位 |
| actionType | security_result.action_details | 所採取行動的詳細資料 |
| createdDate | metadata.event_timestamp | 事件的時間戳記 |
| event_type | metadata.event_type | 事件類型 (例如 USER_LOGIN、NETWORK_CONNECTION) |
| eventName | metadata.product_event_type | 產品專屬事件類型 |
| 訊息 | security_result.summary | 安全性結果摘要 |
| 中繼資料 | 中繼資料 | 事件的中繼資料 |
| 主體 | 主體 | 主體 (操作者) 相關資訊 |
| resourceSrn | principal.resource.name | 資源名稱 |
| security_result | security_result | 安全性結果資訊 |
| sourceIp | principal.asset.ip | 資產的 IP 位址 |
| sourceIp | principal.ip | 與主體相關聯的 IP 位址 |
| 目標 | 目標 | 目標相關資訊 |
| extensions.auth.type | 事件中使用的驗證類型 | |
| metadata.product_name | 產品名稱 | |
| metadata.vendor_name | 供應商/公司名稱 |
變更記錄
還有其他問題嗎?向社群成員和 Google SecOps 專業人員尋求解答。