收集 ThreatLocker 平台日志
本文档介绍了如何使用 Google Cloud Storage V2 将 ThreatLocker 平台日志注入到 Google Security Operations。
ThreatLocker 是一个零信任端点安全平台,可提供应用许可名单、围栏和存储控制功能。Cloud Run 函数会按计划轮询 ThreatLocker API,以 NDJSON 格式将日志写入 GCS 存储桶,然后 Google SecOps 会通过 GCS V2 Feed 提取这些日志。
准备工作
请确保满足以下前提条件:
- Google SecOps 实例
- 已启用 Cloud Storage API 的 GCP 项目
- 创建和管理 GCS 存储分区的权限
- 管理 GCS 存储分区的 IAM 政策的权限
- 创建 Cloud Run 服务、Pub/Sub 主题和 Cloud Scheduler 作业的权限
- 对 ThreatLocker 门户网站的管理员权限
- ThreatLocker 支持团队提供的 ThreatLocker API 密钥和区域性 API 网址
创建 Google Cloud Storage 存储桶
- 前往 Google Cloud 控制台。
- 选择您的项目或创建新项目。
- 在导航菜单中,依次前往 Cloud Storage > 存储分区。
- 点击创建存储分区。
提供以下配置详细信息:
设置 值 为存储桶命名 输入一个全局唯一的名称(例如 threatlocker-logs)位置类型 根据您的需求进行选择(区域级、双区域、多区域) 位置 选择营业地点(例如 us-central1)存储类别 标准(建议用于经常访问的日志) 访问权限控制 均匀(推荐) 保护工具 可选:启用对象版本控制或保留政策 点击创建。
收集 ThreatLocker API 凭据
获取 API 密钥
- 请与 ThreatLocker 支持团队或您的 ThreatLocker 客户经理联系,以获取 API 凭据。
- 您将收到:
- API 密钥:用于 API 身份验证的令牌。
- API 基本网址:区域性 API 主机名(例如
https://api.g.threatlocker.com)。
请将这些凭据保存在安全的位置。
验证权限
如需验证账号是否具有所需权限,请执行以下操作:
- 使用管理员账号登录 ThreatLocker 门户。
- 前往左侧菜单中的统一审核。
- 如果您能看到审核数据,则说明您拥有必需的管理员权限。
- 如果您看不到此选项,请与 ThreatLocker 管理员联系,以获取管理员访问权限。
测试 API 访问权限
在继续进行集成之前,请先测试您的凭据:
# Replace with your actual credentials API_KEY="your-api-key" API_BASE="https://api.g.threatlocker.com" # Test API access curl -v -H "Authorization: Bearer ${API_KEY}" \ -H "Content-Type: application/json" \ "${API_BASE}/audit/v1/events?startDate=2024-01-01&endDate=2024-01-02&limit=1"
为 Cloud Run 函数创建服务账号
Cloud Run 函数需要一个服务账号,该账号具有写入 GCS 存储桶的权限,并且可以由 Pub/Sub 调用。
创建服务账号
- 在 GCP 控制台中,依次前往 IAM 和管理 > 服务账号。
- 点击创建服务账号。
- 提供以下配置详细信息:
- 服务账号名称:输入
threatlocker-collector-sa。 - 服务账号说明:输入
Service account for Cloud Run function to collect ThreatLocker Platform 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 > 存储分区。
- 点击您的存储桶名称(例如
threatlocker-logs)。 - 前往权限标签页。
- 点击授予访问权限。
- 提供以下配置详细信息:
- 添加主账号:输入服务账号电子邮件地址(例如
threatlocker-collector-sa@your-project.iam.gserviceaccount.com)。 - 分配角色:选择 Storage Object Admin。
- 添加主账号:输入服务账号电子邮件地址(例如
- 点击保存。
创建 Pub/Sub 主题
创建一个 Pub/Sub 主题,Cloud Scheduler 将向该主题发布消息,而 Cloud Run 函数将订阅该主题。
- 在 GCP 控制台中,前往 Pub/Sub > 主题。
- 点击创建主题。
- 提供以下配置详细信息:
- 主题 ID:输入
threatlocker-trigger。 - 将其他设置保留为默认值。
- 主题 ID:输入
- 点击创建。
创建 Cloud Run 函数以收集日志
Cloud Run 函数将由来自 Cloud Scheduler 的 Pub/Sub 消息触发,以从 ThreatLocker API 中提取日志并将其写入 GCS。
- 在 GCP 控制台中,前往 Cloud Run。
- 点击创建服务。
- 选择函数(使用内嵌编辑器创建函数)。
在配置部分中,提供以下配置详细信息:
设置 值 Service 名称 threatlocker-collector区域 选择与您的 GCS 存储桶匹配的区域(例如 us-central1)运行时 选择 Python 3.12 或更高版本 在触发器(可选)部分中:
- 点击 + 添加触发器。
- 选择 Cloud Pub/Sub。
- 在选择 Cloud Pub/Sub 主题部分,选择主题
threatlocker-trigger。 - 点击保存。
在身份验证部分中:
- 选择需要进行身份验证。
- 检查 Identity and Access Management (IAM)。
向下滚动并展开容器、网络、安全性。
前往安全性标签页:
- 服务账号:选择服务账号
threatlocker-collector-sa。
- 服务账号:选择服务账号
前往容器标签页:
- 点击变量和密钥。
- 为每个环境变量点击+ 添加变量:
变量名称 示例值 说明 GCS_BUCKETthreatlocker-logsGCS 存储桶名称 GCS_PREFIXthreatlocker日志文件的前缀 STATE_KEYthreatlocker/state.json状态文件路径 TL_API_KEYyour-api-keyThreatLocker API 密钥 TL_API_BASEhttps://api.g.threatlocker.comThreatLocker 区域性 API 网址 MAX_RECORDS10000每次运行的记录数上限 PAGE_SIZE1000每页记录数 LOOKBACK_HOURS24初始回溯期 在变量和密钥标签页中,向下滚动到请求:
- 请求超时:输入
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, 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', 'threatlocker') STATE_KEY = os.environ.get('STATE_KEY', 'threatlocker/state.json') API_KEY = os.environ.get('TL_API_KEY') API_BASE = os.environ.get('TL_API_BASE', 'https://api.g.threatlocker.com') MAX_RECORDS = int(os.environ.get('MAX_RECORDS', '10000')) PAGE_SIZE = int(os.environ.get('PAGE_SIZE', '1000')) 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 ThreatLocker Platform audit logs and write to GCS. Args: cloud_event: CloudEvent object containing Pub/Sub message """ if not all([GCS_BUCKET, API_KEY, API_BASE]): 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 logs from {last_time.isoformat()} to {now.isoformat()}") # Fetch logs records, newest_event_time = fetch_logs( start_time=last_time, end_time=now, page_size=PAGE_SIZE, max_records=MAX_RECORDS, ) if not records: print("No new log 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}") # 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)} 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 fetch_logs(start_time: datetime, end_time: datetime, page_size: int, max_records: int): """ Fetch audit logs from ThreatLocker API with pagination and rate limiting. Args: start_time: Start time for log query end_time: End time for log query page_size: Number of records per page max_records: Maximum total records to fetch Returns: Tuple of (records list, newest_event_time ISO string) """ base_url = API_BASE.rstrip('/') endpoint = f"{base_url}/audit/v1/events" headers = { 'Authorization': f'Bearer {API_KEY}', 'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'GoogleSecOps-ThreatLockerCollector/1.0' } records = [] newest_time = None page_num = 0 backoff = 1.0 offset = 0 start_date = start_time.strftime('%Y-%m-%d') end_date = end_time.strftime('%Y-%m-%d') 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)) url = f"{endpoint}?startDate={start_date}&endDate={end_date}&limit={current_limit}&offset={offset}" 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"HTTP Error: {response.status}") response_text = response.data.decode('utf-8') print(f"Response body: {response_text}") return [], None data = json.loads(response.data.decode('utf-8')) page_results = data if isinstance(data, list) else data.get('events', data.get('data', [])) if not page_results: print(f"No more results (empty page)") break print(f"Page {page_num}: Retrieved {len(page_results)} events") records.extend(page_results) # Track newest event time for event in page_results: try: event_time = event.get('timestamp') or event.get('dateTime') or event.get('createdAt') 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}") # Check for more results if len(page_results) < page_size: print(f"Reached last page (size={len(page_results)} < limit={page_size})") break offset += len(page_results) except Exception as e: print(f"Error fetching logs: {e}") return [], None 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 Console 中,前往 Cloud Scheduler。
- 点击创建作业。
提供以下配置详细信息:
设置 值 名称 threatlocker-collector-hourly区域 选择与 Cloud Run 函数相同的区域 频率 0 * * * *(每小时一次,整点时)时区 选择时区(建议选择世界协调时间 [UTC]) 目标类型 Pub/Sub 主题 选择主题 threatlocker-trigger消息正文 {}(空 JSON 对象)点击创建。
时间表频率选项
根据日志量和延迟时间要求选择频次:
| 频率 | Cron 表达式 | 使用场景 |
|---|---|---|
| 每隔 5 分钟 | */5 * * * * |
大批量、低延迟 |
| 每隔 15 分钟 | */15 * * * * |
搜索量中等 |
| 每小时 | 0 * * * * |
标准(推荐) |
| 每 6 小时 | 0 */6 * * * |
低成交量、批处理 |
| 每天 | 0 0 * * * |
历史数据收集 |
测试集成
- 在 Cloud Scheduler 控制台中,找到您的作业 (
threatlocker-collector-hourly)。 - 点击强制运行以手动触发。
- 等待几秒钟,然后前往 Cloud Run > 服务 > threatlocker-collector > 日志。
验证函数是否已成功执行。请查找以下内容:
Fetching logs from YYYY-MM-DDTHH:MM:SS+00:00 to YYYY-MM-DDTHH:MM:SS+00:00 Page 1: Retrieved X events Wrote X records to gs://threatlocker-logs/threatlocker/logs_YYYYMMDD_HHMMSS.ndjson Successfully processed X records检查 GCS 存储桶 (
threatlocker-logs) 以确认日志是否已写入。
如果您在日志中看到错误,请执行以下操作:
- HTTP 401:检查环境变量中的 API 密钥
- HTTP 403:验证账号在 ThreatLocker 门户中是否具有管理员权限
- HTTP 429:速率限制 - 函数将自动重试并进行退避
- 缺少环境变量:检查是否已设置所有必需的变量
在 Google SecOps 中配置 Feed 以注入 ThreatLocker 平台日志
- 依次前往 SIEM 设置 > Feed。
- 点击添加新 Feed。
- 点击配置单个 Feed。
- 在 Feed 名称字段中,输入 Feed 的名称(例如
ThreatLocker Logs)。 - 选择 Google Cloud Storage V2 作为来源类型。
- 选择 ThreatLocker 平台作为日志类型。
点击获取服务账号。系统会显示一个唯一的服务账号电子邮件地址,例如:
chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com复制此电子邮件地址。您将在下一步骤中用到它。
点击下一步。
为以下输入参数指定值:
存储桶网址:输入带有前缀路径的 GCS 存储桶 URI:
gs://threatlocker-logs/threatlocker/- 替换:
threatlocker-logs:您的 GCS 存储桶名称。threatlocker/:存储日志的前缀/文件夹路径。
- 替换:
来源删除选项:根据您的偏好选择删除选项:
- 永不:转移后永不删除任何文件(建议用于测试)。
- 删除已转移的文件:在成功转移后删除文件。
删除已转移的文件和空目录:成功转移后删除文件和空目录。
文件存在时间上限:包含在过去指定天数内修改的文件(默认值为 180 天)。
资产命名空间:资产命名空间。
提取标签:要应用于相应 Feed 中事件的标签。
点击下一步。
在最终确定界面中查看新的 Feed 配置,然后点击提交。
向 Google SecOps 服务账号授予 IAM 权限
Google SecOps 服务账号需要您的 GCS 存储桶的 Storage Object Viewer 角色。
- 前往 Cloud Storage > 存储分区。
- 点击您的存储桶名称 (
threatlocker-logs)。 - 前往权限标签页。
- 点击授予访问权限。
- 提供以下配置详细信息:
- 添加主账号:粘贴 Google SecOps 服务账号电子邮件地址。
- 分配角色:选择 Storage Object Viewer。
点击保存。
UDM 映射表
| 日志字段 | UDM 映射 | 逻辑 |
|---|---|---|
| rp | extensions.auth.mechanism | 如果存在 rp,则设置为“REMOTE” |
| n | metadata.description | 直接复制值 |
| at, src_ip, dest_ip, ip_protocol, fp, pn | metadata.event_type | 如果 at == "network" 或 (src_ip、dest_ip、ip_protocol 存在),则设置为 NETWORK_CONNECTION;如果 fp 和 pn 存在,则设置为 PROCESS_UNCATEGORIZED;如果 at 位于 ["execute","install"] 中,则设置为 PROCESS_LAUNCH;如果 at == "newprocess",则设置为 PROCESS_OPEN;如果 at 位于 ["write","move"] 中,则设置为 FILE_MODIFICATION;如果 at == "read",则设置为 FILE_READ;如果 at == "delete",则设置为 FILE_DELETION;如果 at == "registry",则设置为 REGISTRY_UNCATEGORIZED |
| p | metadata.product_event_type | 直接复制值 |
| metadata.product_name | 设置为“THREATLOCKER” | |
| metadata.vendor_name | 设置为“THREATLOCKER” | |
| sn | network.ip_protocol | 如果 sn 与 Tcp 匹配,则设置为“TCP” |
| computerId | principal.asset.asset_id | 串联为“ComputerId: %{computerId}” |
| dt | principal.asset.category | 直接复制值 |
| 主机名 | principal.hostname | 直接复制值 |
| fp | principal.ip | 如果 at == "network",则使用 grok 模式提取 src_ip |
| pn | principal.process.file.full_path | 直接复制值 |
| pid | principal.process.pid | 已转换为字符串 |
| organizationId | principal.resource.id | 直接复制值 |
| u | principal.user.user_display_name | 直接复制值 |
| u | principal.user.userid | 使用网域后的 Grok 模式提取的用户部分 |
| e、mid、rf | security_result.about.resource.attribute.labels | 合并了加密状态 (e)、维护 ID (mid)、围栏 (rf) 的标签 |
| a | security_result.action | 如果 a=1,则设置为“ALLOW”;如果 a=2,则设置为“BLOCK”;如果 a=3,则设置为“CHALLENGE”;如果 a=4,则设置为“ALLOW_WITH_MODIFICATION”;如果 a=5,则设置为“UNKNOWN_ACTION”;如果 a=6,则设置为“QUARANTINE” |
| 在哪个商家处 | security_result.action_details | 直接复制值 |
| 月 | security_result.outcomes | 设置为监控模式状态(如果 mo ==“true”,则为“监控模式开启”;如果 mo ==“false”,则为“监控模式关闭”) |
| pyid | security_result.rule_id | 直接复制值 |
| p | security_result.rule_name | 直接复制值 |
| ap、dan | target.application | 如果 dan 不为空,则返回 dan 中的值,否则返回 ap 中的值 |
| fp | target.file.full_path | 设置是否在 ["write","read","delete","move"] 中 |
| 小时 | target.file.sha1 | 如果匹配十六进制模式,则转换为小写并设置 |
| s256 | target.file.sha256 | 如果匹配十六进制模式,则转换为小写并设置 |
| 秒 | target.file.size | 转换为字符串,然后再转换为无符号整数 |
| fp | target.hostname | 如果 at == "network",则使用 grok 模式提取 dest_host |
| fp | target.ip | 如果 at == "network",则使用 grok 模式提取 dest_ip |
| fp | target.port | 如果 at == "network",则使用 grok 模式提取 dest_port,并将其转换为整数 |
| fp | target.process.file.full_path | 如果 at 在 ["execute","install","newprocess"] 中,则进行设置 |
| s256 | target.process.file.sha256 | 如果匹配十六进制模式,则转换为小写并设置 |
| fp | target.registry.registry_key | 如果 at == "registry",则进行设置 |