收集 Citrix Analytics 記錄
剖析器版本:1.0
本文說明如何使用 Google Cloud Storage,將 Citrix Analytics 記錄檔擷取至 Google Security Operations。Citrix Analytics for Performance (Cloud Software Group) 提供 Citrix Virtual Apps and Desktops 環境的匯總成效資料,讓您透過 OData API 擷取工作階段、機器和使用者資料。Citrix Analytics for Security 提供風險洞察和資料來源事件,可透過以 Kafka 為基礎的 SIEM 整合功能匯出。
事前準備
請確認您符合下列必要條件:
- Google SecOps 執行個體
- 已啟用 Cloud Storage API 的 GCP 專案
- 建立及管理 GCS bucket 的權限
- 建立 Cloud Run 服務、Pub/Sub 主題和 Cloud Scheduler 工作的權限
- Citrix Analytics for Performance 租戶的特殊存取權
- Citrix Cloud API 憑證 (用戶端 ID、用戶端密鑰、客戶 ID)
收集 Citrix Analytics API 憑證
取得 Citrix Cloud API 憑證
- 登入 Citrix Cloud 控制台。
- 按一下畫面左上角的選單圖示。
- 從選單中選取「Identity and Access Management」。
- 選取「API 存取權」分頁標籤。
- 按一下「Create Client」(建立用戶端)。
- 複製下列詳細資料,並儲存至安全位置:
- 用戶端 ID
- 用戶端密鑰
- 客戶 ID (位於 Citrix Cloud 網址或 IAM 頁面)
判斷 API 基準網址
OData API 基準網址取決於 Citrix Cloud 區域:
| 區域 | API 基準網址 |
|---|---|
| 美國 | https://api.cloud.com/casodata |
| 歐盟 | https://api.eu.cloud.com/casodata |
| 亞太地區南部 | https://api.ap-s.cloud.com/casodata |
驗證權限
如要確認帳戶具備必要權限,請按照下列步驟操作:
- 登入 Citrix Cloud。
- 依序前往「Identity and Access Management」>「Administrators」。
- 確認用於建立 API 憑證的帳戶具備「完整存取權」或「自訂存取權」,且已啟用 Citrix Analytics for Performance 權限。
- 如果看不到必要權限,請與 Citrix Cloud 管理員聯絡,要求對方授予存取權。
測試 API 存取權
請先測試憑證,再繼續整合:
CITRIX_CUSTOMER_ID="your-customer-id" CITRIX_CLIENT_ID="your-client-id" CITRIX_CLIENT_SECRET="your-client-secret" # Get bearer token TOKEN=$(curl -s -X POST \ "https://api.cloud.com/cctrustoauth2/${CITRIX_CUSTOMER_ID}/tokens/clients" \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials&client_id=${CITRIX_CLIENT_ID}&client_secret=${CITRIX_CLIENT_SECRET}" \ | python3 -c "import sys,json; print(json.load(sys.stdin)['access_token'])") # Test OData API access curl -v -H "Authorization: CwsAuth bearer=${TOKEN}" \ -H "Citrix-CustomerId: ${CITRIX_CUSTOMER_ID}" \ -H "Accept: application/json" \ "https://api.cloud.com/casodata/sessions?\$top=1"
建立 Google Cloud Storage bucket
- 前往 Google Cloud 控制台。
- 選取專案或建立新專案。
- 在導覽選單中,依序前往「Cloud Storage」>「Bucket」。
- 按一下「建立值區」。
提供下列設定詳細資料:
設定 值 為 bucket 命名 輸入全域不重複的名稱 (例如 citrix-analytics-logs)位置類型 請根據需求選擇 (單一區域、雙區域、多區域) 位置 選取位置 (例如 us-central1)儲存空間級別 標準 (建議用於經常存取的記錄) 存取控管 統一 (建議) 保護工具 選用:啟用物件版本管理或資料保留政策 點選「建立」。
建立 Cloud Run 函式的服務帳戶
Cloud Run 函式需要服務帳戶,且該帳戶須具備寫入 GCS bucket 的權限,並可由 Pub/Sub 叫用。
建立服務帳戶
- 在 GCP 控制台中,依序前往「IAM & Admin」(IAM 與管理) >「Service Accounts」(服務帳戶)。
- 按一下「Create Service Account」(建立服務帳戶)。
- 提供下列設定詳細資料:
- 服務帳戶名稱:輸入
citrix-analytics-collector-sa - 服務帳戶說明:輸入
Service account for Cloud Run function to collect Citrix Analytics 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 名稱。
- 前往「權限」分頁。
- 按一下「授予存取權」。
- 提供下列設定詳細資料:
- 新增主體:輸入服務帳戶電子郵件地址 (例如
citrix-analytics-collector-sa@PROJECT_ID.iam.gserviceaccount.com) - 指派角色:選取「Storage 物件管理員」
- 新增主體:輸入服務帳戶電子郵件地址 (例如
- 按一下「儲存」。
建立 Pub/Sub 主題
建立 Pub/Sub 主題,Cloud Scheduler 會發布至該主題,Cloud Run 函式則會訂閱該主題。
- 在 GCP 控制台中,依序前往「Pub/Sub」>「主題」。
- 按一下「建立主題」。
- 提供下列設定詳細資料:
- 主題 ID:輸入
citrix-analytics-trigger - 其他設定保留預設值
- 主題 ID:輸入
- 點選「建立」。
建立 Cloud Run 函式來收集記錄
Cloud Scheduler 的 Pub/Sub 訊息會觸發 Cloud Run 函式,從 Citrix Analytics OData API 擷取記錄,並寫入 GCS。
- 在 GCP 控制台中,前往「Cloud Run」。
- 按一下「Create service」(建立服務)。
- 選取「函式」(使用直接修改建立函式)。
在「Configure」(設定) 部分,提供下列設定詳細資料:
設定 值 服務名稱 citrix-analytics-collector區域 選取與 GCS bucket 相符的區域 (例如 us-central1)執行階段 選取「Python 3.12」或更新版本 在「Trigger (optional)」(觸發條件 (選用)) 部分:
- 按一下「+ 新增觸發條件」。
- 選取「Cloud Pub/Sub」。
- 在「Select a Cloud Pub/Sub topic」(選取 Cloud Pub/Sub 主題) 中,選擇主題
citrix-analytics-trigger。 - 按一下「儲存」。
在「Authentication」(驗證) 部分:
- 選取「需要驗證」。
- Identity and Access Management (IAM)。
向下捲動並展開「容器、網路、安全性」。
前往「安全性」分頁:
- 服務帳戶:選取服務帳戶
citrix-analytics-collector-sa
- 服務帳戶:選取服務帳戶
前往「容器」分頁:
- 按一下「Variables & Secrets」(變數與密鑰)。
- 針對每個環境變數,按一下「+ 新增變數」:
變數名稱 範例值 說明 GCS_BUCKETcitrix-analytics-logsGCS bucket 名稱 GCS_PREFIXcitrix_analytics記錄檔的前置字串 STATE_KEYcitrix_analytics/state.json狀態檔案路徑 CITRIX_CLIENT_IDyour-client-idCitrix Cloud 用戶端 ID CITRIX_CLIENT_SECRETyour-client-secretCitrix Cloud 用戶端密鑰 CITRIX_CUSTOMER_IDyour-customer-idCitrix Cloud 客戶 ID API_BASEhttps://api.cloud.com/casodataOData API 基準網址 ENTITIESsessions,machines,users要收集的實體類型 TOP_N1000每頁記錄數 LOOKBACK_MINUTES75初始回溯期 在「Variables & Secrets」部分,向下捲動至「Requests」:
- 要求逾時:輸入
600秒 (10 分鐘)
- 要求逾時:輸入
前往「設定」分頁:
- 在「Resources」(資源) 部分:
- 「記憶體」:選取「512 MiB」或以上
- CPU:選取「1」
- 在「Resources」(資源) 部分:
在「Revision scaling」(修訂版本資源調度) 部分:
- 「執行個體數量下限」:輸入
0 - 「Maximum number of instances」(執行個體數量上限):輸入
100(或根據預期負載調整)
- 「執行個體數量下限」:輸入
點選「建立」。
等待服務建立完成 (1 至 2 分鐘)。
服務建立後,內嵌程式碼編輯器會自動開啟。
新增函式程式碼
- 在「進入點」欄位中輸入 main。
在內嵌程式碼編輯器中,建立兩個檔案:
main.py:
import functions_framework from google.cloud import storage import json import os import urllib3 from datetime import datetime, timedelta, timezone import urllib.parse 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() CITRIX_TOKEN_URL_TMPL = "https://api.cloud.com/cctrustoauth2/{customerid}/tokens/clients" DEFAULT_API_BASE = "https://api.cloud.com/casodata" @functions_framework.cloud_event def main(cloud_event): """ Cloud Run function triggered by Pub/Sub to fetch logs from Citrix Analytics OData API 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', 'citrix_analytics').strip('/') state_key = os.environ.get('STATE_KEY') or f"{prefix}/state.json" customer_id = os.environ.get('CITRIX_CUSTOMER_ID') client_id = os.environ.get('CITRIX_CLIENT_ID') client_secret = os.environ.get('CITRIX_CLIENT_SECRET') api_base = os.environ.get('API_BASE', DEFAULT_API_BASE) entities = [e.strip() for e in os.environ.get('ENTITIES', 'sessions,machines,users').split(',') if e.strip()] top_n = int(os.environ.get('TOP_N', '1000')) lookback_minutes = int(os.environ.get('LOOKBACK_MINUTES', '75')) if not all([bucket_name, customer_id, client_id, client_secret]): print('Error: Missing required environment variables') return try: # Get GCS bucket bucket = storage_client.bucket(bucket_name) # Determine target hour to collect now = datetime.now(timezone.utc) fallback_target = (now - timedelta(minutes=lookback_minutes)).replace(minute=0, second=0, microsecond=0) # Load state (last processed timestamp) state = load_state(bucket, state_key) last_processed_str = state.get('last_hour_utc') if last_processed_str: last_processed = datetime.fromisoformat(last_processed_str.replace('Z', '+00:00')).replace(tzinfo=None) target_hour = last_processed + timedelta(hours=1) else: target_hour = fallback_target print(f'Processing logs for hour: {target_hour.isoformat()}Z') # Get authentication token token = get_citrix_token(customer_id, client_id, client_secret) headers = { 'Authorization': f'CwsAuth bearer={token}', 'Citrix-CustomerId': customer_id, 'Accept': 'application/json', 'Content-Type': 'application/json', } total_records = 0 # Process each entity type for entity in entities: records = [] for row in fetch_odata_entity(entity, target_hour, top_n, headers, api_base): enriched_record = { 'citrix_entity': entity, 'citrix_hour_utc': target_hour.isoformat() + 'Z', 'collection_timestamp': datetime.now(timezone.utc).isoformat() + 'Z', 'raw': row } records.append(enriched_record) # Write in batches to avoid memory issues if len(records) >= 1000: blob_name = f"{prefix}/{entity}/year={target_hour.year:04d}/month={target_hour.month:02d}/day={target_hour.day:02d}/hour={target_hour.hour:02d}/part-{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S%f')}.ndjson" write_ndjson_to_gcs(bucket, blob_name, records) total_records += len(records) records = [] # Write remaining records if records: blob_name = f"{prefix}/{entity}/year={target_hour.year:04d}/month={target_hour.month:02d}/day={target_hour.day:02d}/hour={target_hour.hour:02d}/part-{datetime.now(timezone.utc).strftime('%Y%m%d%H%M%S%f')}.ndjson" write_ndjson_to_gcs(bucket, blob_name, records) total_records += len(records) # Update state file save_state(bucket, state_key, {'last_hour_utc': target_hour.isoformat() + 'Z'}) print(f'Successfully processed {total_records} records for hour {target_hour.isoformat()}Z') except Exception as e: print(f'Error processing logs: {str(e)}') raise def get_citrix_token(customer_id, client_id, client_secret): """Get Citrix Cloud authentication token.""" url = CITRIX_TOKEN_URL_TMPL.format(customerid=customer_id) payload = { 'grant_type': 'client_credentials', 'client_id': client_id, 'client_secret': client_secret, } data = urllib.parse.urlencode(payload).encode('utf-8') response = http.request( 'POST', url, body=data, headers={ 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', } ) if response.status != 200: print(f'Token request failed with status {response.status}') print(f'Response: {response.data.decode("utf-8")}') raise Exception(f'Failed to get Citrix token: HTTP {response.status}') token_response = json.loads(response.data.decode('utf-8')) return token_response['access_token'] def fetch_odata_entity(entity, when_utc, top, headers, api_base): """Fetch data from Citrix Analytics OData API with pagination and rate limiting.""" year = when_utc.year month = when_utc.month day = when_utc.day hour = when_utc.hour base_url = f"{api_base.rstrip('/')}/{entity}?year={year:04d}&month={month:02d}&day={day:02d}&hour={hour:02d}" skip = 0 backoff = 1.0 while True: url = f"{base_url}&$top={top}&$skip={skip}" 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'HTTP Error: {response.status}') response_text = response.data.decode('utf-8') print(f'Response body: {response_text}') return data = json.loads(response.data.decode('utf-8')) items = data.get('value', []) if not items: break for item in items: yield item if len(items) < top: break skip += top 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)}') def write_ndjson_to_gcs(bucket, key, records): """Write records as NDJSON to GCS.""" body_lines = [] for record in records: json_line = json.dumps(record, separators=(',', ':'), ensure_ascii=False) body_lines.append(json_line) body = ('\n'.join(body_lines) + '\n').encode('utf-8') blob = bucket.blob(key) blob.upload_from_string(body, content_type='application/x-ndjson')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」。
- 點選「建立工作」。
提供下列設定詳細資料:
設定 值 名稱 citrix-analytics-collector-hourly區域 選取與 Cloud Run 函式相同的區域 頻率 0 * * * *(每小時整點)時區 選取時區 (建議選取世界標準時間) 目標類型 Pub/Sub 主題 選取主題「 citrix-analytics-trigger」郵件內文 {}(空白 JSON 物件)點選「建立」。
排程頻率選項
根據記錄量和延遲時間需求選擇頻率:
| 頻率 | Cron 運算式 | 用途 |
|---|---|---|
| 每小時 | 0 * * * * |
標準 (建議) |
| 每 2 小時 | 0 */2 * * * |
調低音量 |
| 每 6 小時 | 0 */6 * * * |
低量、批次處理 |
測試整合
- 在 Cloud Scheduler 控制台中找到您的工作。
- 按一下「強制執行」,手動觸發工作。
- 稍等幾秒鐘。
- 依序前往「Cloud Run」>「服務」。
- 按一下函式名稱
citrix-analytics-collector。 - 點選「記錄」分頁標籤。
確認函式是否執行成功。尋找:
Processing logs for hour: YYYY-MM-DDTHH:00:00Z Successfully processed X records for hour YYYY-MM-DDTHH:00:00Z依序前往「Cloud Storage」>「Bucket」。
按一下 bucket 名稱。
前往前置字元資料夾
citrix_analytics/。確認系統已建立新的
.ndjson檔案,且時間戳記為目前時間。
如果記錄中顯示錯誤:
- HTTP 401:檢查環境變數中的 API 憑證
- HTTP 403:確認帳戶在 Citrix Cloud 中具備必要權限
- HTTP 429:頻率限制 - 函式會自動重試,並採用輪詢機制
- 缺少環境變數:確認已設定所有必要變數
在 Google SecOps 中設定動態饋給,以擷取 Citrix Analytics 記錄
- 依序前往「設定」>「資料管理」>「動態饋給」。如果使用的是 SIEM 專用平台,請依序前往「設定」>「動態饋給」。
- 按一下「新增動態饋給」。
- 按一下「設定單一動態饋給」。
- 在「Feed name」(動態饋給名稱) 欄位中,輸入動態饋給名稱 (例如
Citrix Analytics logs)。 - 選取「Google Cloud Storage V2」做為「來源類型」。
- 選取「Citrix Analytics」做為「記錄類型」。
按一下「Get Service Account」。系統會顯示專屬服務帳戶電子郵件地址,例如:
chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com複製這個電子郵件地址,下一個步驟將會用到。
點選「下一步」。
指定下列輸入參數的值:
Storage bucket URL:輸入 GCS bucket URI,並加上前置字元路徑:
gs://citrix-analytics-logs/citrix_analytics/- 取代:
citrix-analytics-logs:GCS bucket 名稱。citrix_analytics:儲存記錄檔的選用前置字元/資料夾路徑 (留空則為根目錄)。
- 取代:
來源刪除選項:根據偏好選取刪除選項:
- Never:轉移後一律不刪除任何檔案 (建議用於測試)。
- 刪除已轉移的檔案:在成功轉移後刪除檔案。
- 刪除已轉移的檔案和空白目錄:成功轉移後,刪除檔案和空白目錄。
檔案存在時間上限:納入過去幾天內修改過的檔案 (預設為 180 天)
資產命名空間:資產命名空間
擷取標籤:要套用至這個動態饋給事件的標籤
點選「下一步」。
在「完成」畫面中檢查新的新聞動態消息設定,然後按一下「提交」。
將 IAM 權限授予 Google SecOps 服務帳戶
Google SecOps 服務帳戶需要 GCS bucket 的 Storage 物件檢視者角色。
- 依序前往「Cloud Storage」>「Bucket」。
- 按一下 bucket 名稱。
- 前往「權限」分頁。
- 按一下「授予存取權」。
- 提供下列設定詳細資料:
- 新增主體:貼上 Google SecOps 服務帳戶電子郵件地址
- 指派角色:選取「Storage 物件檢視者」
按一下「儲存」。
UDM 對應表
| 記錄欄位 | UDM 對應 | 邏輯 |
|---|---|---|
occurrence_event_type |
extensions.auth.type |
對應:Session.Logon → AUTHTYPE_UNSPECIFIED,Session.End → AUTHTYPE_UNSPECIFIED |
server_name |
intermediary.asset.hostname |
直接對應 |
server_name |
intermediary.hostname |
直接對應 |
event_type |
metadata.description |
直接對應 |
timestamp |
metadata.event_timestamp |
剖析為 ISO8601 |
udm_event_type |
metadata.event_type |
對應:"USER_LOGIN", "USER_LOGOUT" → GENERIC_EVENT |
tenant_id |
metadata.product_deployment_id |
直接對應 |
occurrence_event_type |
metadata.product_event_type |
直接對應 |
event_id |
metadata.product_log_id |
直接對應 |
product |
metadata.product_name |
直接對應 |
product_version |
metadata.product_version |
直接對應 |
ui_link |
metadata.url_back_to_product |
直接對應 |
session_key |
network.session_id |
直接對應 |
domain |
principal.administrative_domain |
直接對應 |
device_id |
principal.asset.hostname |
直接對應 |
client_ip |
principal.asset.ip |
已合併 |
vulnerability |
principal.asset.vulnerabilities |
已合併 |
device_id |
principal.hostname |
直接對應 |
client_ip |
principal.ip |
已合併 |
os_name |
principal.platform |
對應值 (共 6 個,例如 (?i)windows → WINDOWS、(?i)windows → MAC、(?i)windows... |
os_extra_info |
principal.platform_patch_level |
直接對應 |
os_version |
principal.platform_version |
直接對應 |
entity_id |
principal.user.email_addresses |
對應:^.+@.+$ → entity_id |
entity_type |
principal.user.email_addresses |
對應:user → entity_id |
session_user_name |
principal.user.user_display_name |
直接對應 |
entity_id |
principal.user.userid |
直接對應 |
session_user_name |
principal.user.userid |
直接對應 |
alert_message |
security_result.action_details |
直接對應 |
analytic |
security_result.analytics_metadata |
已合併 |
category |
security_result.category |
已合併 |
indicator_category |
security_result.category |
對應:Data exfiltration → category |
indicator_name |
security_result.description |
直接對應 |
label |
security_result.detection_fields |
已合併 |
label |
security_result.outcomes |
已合併 |
severity |
security_result.severity |
直接對應 |
app_name |
target.application |
直接對應 |
app_name |
target.process.file.names |
已合併 |
printer_name |
target.resource.name |
直接對應 |
entity_id |
target.user.email_addresses |
對應:^.+@.+$ → entity_id |
entity_type |
target.user.email_addresses |
對應:user → entity_id |
session_user_name |
target.user.user_display_name |
直接對應 |
entity_id |
target.user.userid |
直接對應 |
session_user_name |
target.user.userid |
直接對應 |
| 不適用 | extensions.auth.type |
常數:AUTHTYPE_UNSPECIFIED |
| 不適用 | metadata.event_type |
常數:GENERIC_EVENT |
| 不適用 | metadata.vendor_name |
常數:CITRIX_ANALYTICS |
| 不適用 | principal.platform |
常數:WINDOWS |
| 不適用 | security_result.confidence_score |
常數:risk_probability |
| 不適用 | security_result.risk_score |
常數:cur_riskscore |
變更記錄
還有其他問題嗎?向社群成員和 Google SecOps 專業人員尋求解答。