收集 Citrix Analytics 日志
本文档介绍了如何使用 Google Cloud Storage 将 Citrix Analytics 日志提取到 Google Security Operations。Citrix Analytics for Performance 提供来自性能数据源的汇总数据,使您能够提取会话、计算机和用户数据。
准备工作
确保您满足以下前提条件:
- Google SecOps 实例
- 已启用 Cloud Storage API 的 GCP 项目
- 创建和管理 GCS 存储分区的权限
- 创建 Cloud Run 服务、Pub/Sub 主题和 Cloud Scheduler 作业的权限
- 对 Citrix Analytics for Performance 租户的特权访问权限
- Citrix Cloud API 凭据(客户端 ID、客户端密钥、客户 ID)
收集 Citrix Analytics API 凭据
- 登录 Citrix Cloud 控制台。在 Citrix Cloud 控制台中,点击屏幕左上角的菜单。从菜单中选择“Identity and Access Management”选项。选择“API 访问权限”标签页。
- 点击创建客户端。
复制以下详细信息并将其保存在安全的位置:
- Client-ID
- 客户端密钥 (Client Secret)
- 客户 ID(位于 Citrix Cloud 网址或 IAM 页面中)
- API 基本网址:
https://api.cloud.com/casodata
创建 Google Cloud Storage 存储分区
- 前往 Google Cloud 控制台。
- 选择您的项目或创建新项目。
- 在导航菜单中,依次前往 Cloud Storage > 存储分区。
- 点击创建存储分区。
提供以下配置详细信息:
设置 值 为存储分区命名 输入一个全局唯一的名称(例如 citrix-analytics-logs)位置类型 根据您的需求进行选择(区域级、双区域级、多区域级) 位置 选择相应位置(例如 us-central1)存储类别 标准(建议用于经常访问的日志) 访问权限控制 统一(推荐) 保护工具 可选:启用对象版本控制或保留政策 点击创建。
为 Cloud Run 函数创建服务账号
Cloud Run 函数需要一个有权写入 GCS 存储分区的服务账号。
创建服务账号
- 在 GCP 控制台中,依次前往 IAM 和管理 > 服务账号。
- 点击创建服务账号。
- 提供以下配置详细信息:
- 服务账号名称:输入
citrix-analytics-collector-sa。 - 服务账号说明:输入
Service account for Cloud Run function to collect Citrix Analytics logs。
- 服务账号名称:输入
- 点击创建并继续。
- 在向此服务账号授予对项目的访问权限部分:
- 点击选择角色。
- 搜索并选择 Storage Object Admin。
- 点击 + 添加其他角色。
- 搜索并选择 Cloud Run Invoker。
- 点击 + 添加其他角色。
- 搜索并选择 Cloud Functions Invoker。
- 点击继续。
- 点击完成。
必须拥有这些角色,才能:
- Storage Object Admin:将日志写入 GCS 存储分区并管理状态文件
- Cloud Run Invoker:允许 Pub/Sub 调用函数
- Cloud Functions Invoker:允许调用函数
授予对 GCS 存储分区的 IAM 权限
向服务账号授予对 GCS 存储分区的写入权限:
- 前往 Cloud Storage > 存储分区。
- 点击您的存储分区名称。
- 前往权限标签页。
- 点击授予访问权限。
- 提供以下配置详细信息:
- 添加主账号:输入服务账号电子邮件地址。
- 分配角色:选择 Storage Object Admin。
- 点击保存。
创建发布/订阅主题
创建一个 Pub/Sub 主题,供 Cloud Scheduler 发布消息,并供 Cloud Run 函数订阅。
- 在 GCP 控制台中,前往 Pub/Sub > 主题。
- 点击创建主题。
- 提供以下配置详细信息:
- 主题 ID:输入
citrix-analytics-trigger。 - 将其他设置保留为默认值。
- 主题 ID:输入
- 点击创建。
创建 Cloud Run 函数以收集日志
Cloud Run 函数由来自 Cloud Scheduler 的 Pub/Sub 消息触发,用于从 Citrix Analytics OData API 中提取日志并将其写入 GCS。
- 在 GCP 控制台中,前往 Cloud Run。
- 点击创建服务。
- 选择函数(使用内嵌编辑器创建函数)。
在配置部分中,提供以下配置详细信息:
设置 值 Service 名称 citrix-analytics-collector区域 选择与您的 GCS 存储分区匹配的区域(例如 us-central1)运行时 选择 Python 3.12 或更高版本 在触发器(可选)部分中:
- 点击 + 添加触发器。
- 选择 Cloud Pub/Sub。
- 在选择 Cloud Pub/Sub 主题部分,选择主题
citrix-analytics-trigger。 - 点击保存。
在身份验证部分中:
- 选择需要进行身份验证。
- 检查 Identity and Access Management (IAM)。
向下滚动并展开容器、网络、安全性。
前往安全标签页:
- 服务账号:选择服务账号
citrix-analytics-collector-sa。
- 服务账号:选择服务账号
前往容器标签页:
- 点击变量和密钥。
- 为每个环境变量点击 + 添加变量:
变量名称 示例值 GCS_BUCKETcitrix-analytics-logsGCS_PREFIXcitrix_analyticsSTATE_KEYcitrix_analytics/state.jsonCITRIX_CLIENT_IDyour-client-idCITRIX_CLIENT_SECRETyour-client-secretCITRIX_CUSTOMER_IDyour-customer-idAPI_BASEhttps://api.cloud.com/casodataENTITIESsessions,machines,usersTOP_N1000LOOKBACK_MINUTES75在变量和密钥标签页中,向下滚动到请求:
- 请求超时:输入
600秒(10 分钟)。
- 请求超时:输入
前往容器中的设置标签页:
- 在资源部分中:
- 内存:选择 512 MiB 或更高值。
- CPU:选择 1。
- 点击完成。
- 在资源部分中:
向下滚动到执行环境:
- 选择默认(推荐)。
在修订版本扩缩部分中:
- 实例数下限:输入
0。 - 实例数上限:输入
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 # Initialize HTTP client http = urllib3.PoolManager() # 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 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', } ) 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.""" 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 while True: url = f"{base_url}&$top={top}&$skip={skip}" response = http.request('GET', url, headers=headers) 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 Console 中,前往 Cloud Scheduler。
- 点击创建作业。
提供以下配置详细信息:
设置 值 名称 citrix-analytics-collector-hourly区域 选择与 Cloud Run 函数相同的区域 频率 0 * * * *(每小时一次,在整点时)时区 选择时区(建议选择世界协调时间 [UTC]) 目标类型 Pub/Sub 主题 选择主题 citrix-analytics-trigger消息正文 {}(空 JSON 对象)点击创建。
时间表频率选项
根据日志量和延迟时间要求选择频次:
频率 Cron 表达式 使用场景 每小时 0 * * * *标准(推荐) 每 2 小时 0 */2 * * *调低音量 每 6 小时 0 */6 * * *量小、批处理
测试调度器作业
- 在 Cloud Scheduler 控制台中,找到您的作业。
- 点击强制运行以手动触发。
- 等待几秒钟,然后依次前往 Cloud Run > 服务 > citrix-analytics-collector > 日志。
- 验证函数是否已成功执行。
- 检查 GCS 存储分区,确认日志已写入。
检索 Google SecOps 服务账号
Google SecOps 使用唯一的服务账号从您的 GCS 存储分区中读取数据。您必须授予此服务账号对您的存储分区的访问权限。
获取服务账号电子邮件地址
- 依次前往 SIEM 设置 > Feed。
- 点击添加新 Feed。
- 点击配置单个 Feed。
- 在Feed 名称字段中,输入 Feed 的名称(例如
Citrix Analytics Performance logs)。 - 选择 Google Cloud Storage V2 作为来源类型。
- 选择 Citrix Analytics 作为日志类型。
点击获取服务账号。系统会显示一个唯一的服务账号电子邮件地址,例如:
chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com复制此电子邮件地址,以便在下一步中使用。
向 Google SecOps 服务账号授予 IAM 权限
Google SecOps 服务账号需要对您的 GCS 存储分区具有 Storage Object Viewer 角色。
- 前往 Cloud Storage > 存储分区。
- 点击您的存储分区名称。
- 前往权限标签页。
- 点击授予访问权限。
- 提供以下配置详细信息:
- 添加主账号:粘贴 Google SecOps 服务账号电子邮件地址。
- 分配角色:选择 Storage Object Viewer。
点击保存。
在 Google SecOps 中配置 Feed 以注入 Citrix Analytics 日志
- 依次前往 SIEM 设置 > Feed。
- 点击添加新 Feed。
- 点击配置单个 Feed。
- 在Feed 名称字段中,输入 Feed 的名称(例如
Citrix Analytics logs)。 - 选择 Google Cloud Storage V2 作为来源类型。
- 选择 Citrix Analytics 作为日志类型。
- 点击下一步。
为以下输入参数指定值:
存储分区网址:输入带有前缀路径的 GCS 存储分区 URI:
gs://citrix-analytics-logs/citrix_analytics/将
citrix-analytics-logs:您的 GCS 存储分区名称。citrix_analytics:存储日志的可选前缀/文件夹路径(留空表示根目录)。
示例:
- 根存储分区:
gs://citrix-analytics-logs/ - 带前缀:
gs://citrix-analytics-logs/citrix_analytics/
- 根存储分区:
来源删除选项:根据您的偏好选择删除选项:
- 永不:永不删除转移后的任何文件(建议用于测试)。
- 删除已转移的文件:在成功转移后删除文件。
删除已转移的文件和空目录:在成功转移后删除文件和空目录。
文件存在时间上限:包含在过去指定天数内修改的文件。默认值为 180 天。
资产命名空间:资产命名空间。
注入标签:要应用于此 Feed 中事件的标签。
点击下一步。
在最终确定界面中查看新的 Feed 配置,然后点击提交。
需要更多帮助?获得社区成员和 Google SecOps 专业人士的解答。