# https://github.com/newrelic/csec-node-agent 项目说明书

生成时间：2026-06-17 18:56:58 UTC

## 目录

- [概览与系统架构](#page-1)
- [插桩机制与漏洞检测](#page-2)
- [通信协议与事件管理](#page-3)
- [部署、配置与依赖安全](#page-4)

<a id='page-1'></a>

## 概览与系统架构

### 相关页面

相关主题：[插桩机制与漏洞检测](#page-2), [通信协议与事件管理](#page-3)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [lib/nr-security-agent/lib/core/sec-agent-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/sec-agent-constants.js)
- [lib/nr-security-agent/lib/core/event.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/event.js)
- [lib/instrumentation-security/core/event-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/core/event-constants.js)
- [lib/nr-security-agent/lib/core/commonUtils.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/commonUtils.js)
- [lib/instrumentation-security/hooks/http/nr-http.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/http/nr-http.js)
- [lib/instrumentation-security/hooks/crypto/nr-crypto.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/crypto/nr-crypto.js)
- [lib/instrumentation-security/hooks/fs/nr-fs.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/fs/nr-fs.js)
- [CHANGELOG.md](https://github.com/newrelic/csec-node-agent/blob/main/CHANGELOG.md)
- [CONTRIBUTING.md](https://github.com/newrelic/csec-node-agent/blob/main/CONTRIBUTING.md)
</details>

# 概览与系统架构

## 一、项目定位与目标

`newrelic/csec-node-agent` 是 New Relic 推出的 **Node.js 应用安全代理**（Cloud Security Event Collection Agent），它作为 New Relic APM 主代理的伴生模块运行，为 Node.js 应用提供安全检测与防护能力。代理同时支持两种运行模式：**IAST**（Interactive Application Security Testing，交互式应用安全测试）与 **RASP**（Runtime Application Self-Protection，运行时应用自我保护），模式标识定义于 `lib/nr-security-agent/lib/core/sec-agent-constants.js:55-56` 中的 `RASP` 与 `IAST` 常量。

代理的核心职责包括：收集环境与应用信息、与外部 Security Engine 建立安全通道、对 HTTP 请求与响应进行分析、在关键 API（文件系统、加密、子进程等）处检测漏洞并生成安全事件。`CHANGELOG.md` 中 v2.0.0 及以上版本记录了"通过配置支持代理设置、安全 Cookie 事件、IAST 扫描调度"等持续演进的能力。

## 二、系统架构

整个代码库围绕"采集–分析–上报"的数据链路组织，主要由两个子域构成：

- **`lib/nr-security-agent/`**：负责与 Security Engine 通信、初始化、状态管理、健康检查、事件批处理与上报；
- **`lib/instrumentation-security/`**：负责在 Node.js 各核心模块（`http`、`https`、`fs`、`crypto`、`child_process`、`dns` 等）上挂载拦截钩子，提取事件上下文并产出安全事件元数据。

二者通过 `lib/nr-security-api/` 中暴露的统一 API（如 `API.getSecAgent()`、`API.sendEvent()`）解耦：钩子层只负责产生事件，代理层负责通道、限流与持久化。

```mermaid
graph TB
    subgraph App["宿主 Node.js 应用"]
        REQ[HTTP/HTTPS 请求]
        FS[fs 模块调用]
        CR[crypto / child_process 调用]
    end

    subgraph IAST["lib/instrumentation-security"]
        H1[nr-http.js]
        H2[nr-fs.js]
        H3[nr-crypto.js]
    end

    subgraph API["lib/nr-security-api"]
        A1[getSecAgent / sendEvent]
    end

    subgraph Agent["lib/nr-security-agent"]
        S1[Agent 初始化与环境采集]
        S2[安全通道 / 健康检查]
        S3[事件批处理与上报]
    end

    SE[Security Engine / Prevent-Web 服务]

    REQ --> H1
    FS --> H2
    CR --> H3
    H1 --> A1
    H2 --> A1
    H3 --> A1
    A1 --> S3
    S1 --> S2
    S2 --> S3
    S3 --> SE
```

资料来源：[lib/nr-security-agent/lib/core/sec-agent-constants.js:1-15]()、[lib/instrumentation-security/hooks/http/nr-http.js:1-20]()

## 三、核心模块与职责

### 1. 代理核心（`nr-security-agent`）

- **常量与日志键**：`sec-agent-constants.js` 集中管理事件类别（`RASP`/`IAST`）、严重级别（`SEVERE`/`HIGH`/`CRITICAL`）、内容类型枚举与日志模板，例如 `AGENT_INIT_SUCCESSFUL` 用于标识进程附加成功。资料来源：[lib/nr-security-agent/lib/core/sec-agent-constants.js:20-70]()
- **公共工具**：`commonUtils.js` 提供 `getUUID()`、`getKindIdPair()`、`hasWorker()` 等方法。其中 `getKindIdPair()` 可根据环境识别 HOST / CONTAINER / ECS / POD 等不同部署形态，用于精确上报。资料来源：[lib/nr-security-agent/lib/core/commonUtils.js:50-90]()
- **事件类型定义**：`event.js` 列出 `EVENT_TYPE`（HTTP、SQL_DB_COMMAND、FILE_OPERATION 等）与 `VUNERABILITIES`（SQLI、RXSS、RCE、SSRF、CRYPTO、HASH 等），是整个系统的"漏洞词典"。资料来源：[lib/nr-security-agent/lib/core/event.js:1-20]()

### 2. 安全插桩（`instrumentation-security`）

- **HTTP 钩子**：`nr-http.js` 解析请求头、Content-Type、查询参数，并通过 `NR-CSEC-FUZZ-REQUEST-ID` 标识 IAST 模糊测试请求，是 Web 层面攻击面分析的主入口。资料来源：[lib/instrumentation-security/hooks/http/nr-http.js:1-30]()
- **加密与弱随机钩子**：`nr-crypto.js` 拦截 `hash`、`hmac`、`randomBytes`、`Math.random` 等调用，识别弱哈希与弱随机数漏洞。资料来源：[lib/instrumentation-security/hooks/crypto/nr-crypto.js:30-55]()
- **文件系统钩子**：`nr-fs.js` 覆盖 `readFile`、`writeFile`、`unlink`、`copyFile`、`rename` 等高危操作，特殊处理 `copyFile`/`rename` 的双参数场景以避免路径混淆。资料来源：[lib/instrumentation-security/hooks/fs/nr-fs.js:1-30]()

## 四、事件类型一览

代理所识别的漏洞类别与事件类型在两处常量文件中分别维护（注意旧名拼写为 `VUNERABILITIES`）：

| 事件类型（EVENT_TYPE） | 漏洞类别（VUNERABILITIES） | 典型触发点 |
|---|---|---|
| HTTP | RXSS / NOSQLI | nr-http.js |
| SQL_DB_COMMAND | SQLI | SQL 驱动钩子 |
| NOSQL_DB_COMMAND | NOSQLI | MongoDB 驱动钩子 |
| FILE_OPERATION | FILE_ACCESS | nr-fs.js |
| HASH / CRYPTO | CRYPTO / HASH | nr-crypto.js |
| SYSTEM_COMMAND | RCE / RCI | child_process 钩子 |
| REFLECTED_XSS / XPATH / LDAP | RXSS / XPATH / LDAP-I | 各类解析器钩子 |
| WEAKRANDOM | WEAK_RANDOM | cryptoRandomHooks |

资料来源：[lib/nr-security-agent/lib/core/event.js:1-30]()、[lib/instrumentation-security/core/event-constants.js:1-20]()

## 五、社区关注与运维注意事项

社区中较受关注的问题集中在**依赖漏洞与体积**上，例如 `request-ip@^2.1.3` 引入的 `is_js@0.9.0` 受 CVE-2020-26302 影响（issue #55），`sync-request` 经 `form-data` 引入的拒绝服务风险（issue #304），以及 `2.3.0` 版本因 `docker` 依赖触发的任意代码执行告警（issue #282）。`CHANGELOG.md` 的最新条目（v3.0.4）显示维护团队持续在清理依赖链，例如移除 `uuid` 模块以及升级 `protobufjs` 与 `fast-xml-parser`。在升级 New Relic 主代理时，建议同步检查这些传递依赖的版本与安全公告。

资料来源：[CHANGELOG.md:1-20]()

## See Also

- [安装与配置](installation-and-configuration.md)
- [IAST 扫描配置](iast-scan-configuration.md)
- [安全事件格式](security-event-format.md)
- [故障排查与日志](troubleshooting.md)

---

<a id='page-2'></a>

## 插桩机制与漏洞检测

### 相关页面

相关主题：[概览与系统架构](#page-1), [通信协议与事件管理](#page-3)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [lib/instrumentation-security/index.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/index.js)
- [lib/instrumentation-security/core/sec-utils.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/core/sec-utils.js)
- [lib/instrumentation-security/core/sec-trace.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/core/sec-trace.js)
- [lib/instrumentation-security/core/security-metadata.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/core/security-metadata.js)
- [lib/instrumentation-security/hooks/native/nr-vm.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/native/nr-vm.js)
- [lib/instrumentation-security/hooks/http/nr-http.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/http/nr-http.js)
- [lib/instrumentation-security/hooks/crypto/nr-crypto.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/crypto/nr-crypto.js)
- [lib/instrumentation-security/hooks/nextjs/nr-next.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/nextjs/nr-next.js)
- [lib/nr-security-agent/lib/core/sec-agent-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/sec-agent-constants.js)
- [lib/nr-security-agent/lib/core/event.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/event.js)
- [lib/instrumentation-security/core/event-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/core/event-constants.js)
- [lib/nr-security-agent/lib/core/commonUtils.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/commonUtils.js)
- [lib/nr-security-agent/lib/core/xss-utils.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/xss-utils.js)
</details>

# 插桩机制与漏洞检测

## 概览与设计目标

csec-node-agent 是 New Relic 推出的 Node.js 应用安全代理,其核心职责之一是通过 **插桩(Instrumentation)** 机制在应用运行时监控潜在的安全漏洞,实现 IAST(Interactive Application Security Testing)与 RASP(Runtime Application Self-Protection)双模态防护。代理依赖于 New Relic 主代理(`newrelic`)暴露的 `shim` 接口完成对宿主进程关键模块的包装与检测,必须随主代理一同加载。资料来源：[lib/instrumentation-security/index.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/index.js)

插桩入口模块会在进程启动阶段(由 `agent-status` 触发的 IAST 模式下)注册若干安全事件类型,如 `IAST`、`RASP`,并将这些字符串作为事件标识贯穿到后续的事件生成与上报流程。资料来源：[lib/nr-security-agent/lib/core/sec-agent-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/sec-agent-constants.js)

## 事件类型与漏洞分类

代理在 `event-constants.js` 与 `event.js` 中集中维护了事件类型(EVENT_TYPE)与漏洞分类(VULNERABILITIES)的常量定义。前者刻画被监控的代码动作类别,后者刻画命中后对应的攻击类型。资料来源：[lib/instrumentation-security/core/event-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/core/event-constants.js)、[lib/nr-security-agent/lib/core/event.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/event.js)

| 事件类型 (EVENT_TYPE) | 漏洞分类 (VULNERABILITIES) | 监测对象 |
|---|---|---|
| `SYSTEM_COMMAND` / `SYSTEM_EXIT` | `RCE` / `RCI` | 子进程与系统命令执行 |
| `SQL_DB_COMMAND` / `NOSQL_DB_COMMAND` | `SQLI` / `NOSQLI` | SQL 与 NoSQL 查询 |
| `HTTP_REQUEST` | `SSRF` | HTTP 出站请求 |
| `REFLECTED_XSS` | `RXSS` | 反射型跨站脚本 |
| `HASH` / `CRYPTO` | `HASH` / `CRYPTO` | 哈希与加密算法 |
| `RANDOM` | `WEAK_RANDOM` | 不安全随机数 |
| `LDAP` / `XPATH` | `LDAP` / `XPATH` | LDAP 与 XPath 注入 |
| `XXE` | `XXE` | XML 外部实体 |
| `UNVALIDATED_REDIRECT` | `UNVALIDATED_REDIRECT` | 未验证重定向 |
| `FILE_OPERATION` / `FILE_INTEGRITY` | `FILE_ACCESS` | 文件读写与完整性 |

`commonUtils.js` 中还定义了事件类型到漏洞分类的映射字典(`file_access`、`sql_injection` 等),供安全元数据模块进行统一归类。资料来源：[lib/nr-security-agent/lib/core/commonUtils.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/commonUtils.js)

## 插桩架构与执行流程

代理的插桩入口通过 `shim.wrap` 与 `shim.interceptedArgs` 实现。以 HTTP 插桩为例,在 `nr-http.js` 中,代理拦截客户端请求参数,使用 `request-ip` 模块解析客户端 IP,并将 method、URL、请求体、协议头写入 `requestManager` 维护的请求上下文;随后通过 `sec-utils.getTraceObject` 获取当前调用栈,交由 `security-metadata` 构造安全元数据。资料来源：[lib/instrumentation-security/hooks/http/nr-http.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/http/nr-http.js)

```mermaid
flowchart LR
    A[宿主应用启动] --> B[加载 csec-node-agent]
    B --> C[遍历已注册模块]
    C --> D{模块类型}
    D -->|http| E[HTTP 插桩]
    D -->|crypto| F[哈希/随机数插桩]
    D -->|vm| G[VM 插桩]
    E --> H[拦截调用并收集参数]
    F --> H
    G --> H
    H --> I[sec-utils 抓取调用栈]
    I --> J[security-metadata 聚合元数据]
    J --> K{判定漏洞}
    K -->|命中| L[generateSecEvent + sendEvent]
    K -->|未命中| M[继续执行原函数]
    L --> N[generateExitEvent 配对退出]
```

## 核心检测机制

### 调用栈自屏蔽与污点来源识别

在 crypto 插桩中,代理会检查堆栈顶部是否包含 `NRLIB` 或 `SALIB` 标记,若命中则视为代理自身调用,跳过事件生成以避免递归上报。资料来源：[lib/instrumentation-security/hooks/crypto/nr-crypto.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/crypto/nr-crypto.js)

### 元数据聚合与事件生成

`security-metadata.getSecurityMetaData` 将请求上下文、被拦截参数(`interceptedArgs`)、调用栈与执行 ID(`secUtils.getExecutionId()`)聚合为统一的安全元数据,再由 `API.generateSecEvent` 构造标准化事件,通过 `API.sendEvent` 异步推送至后端,并以 `API.generateExitEvent` 完成退出事件配对。资料来源：[lib/instrumentation-security/hooks/crypto/nr-crypto.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/crypto/nr-crypto.js)

### 反射型 XSS 检测

`xss-utils.js` 提供了对响应体的反射型 XSS 检测。它结合 `unescape` 与 `html-entities` 解码请求与响应数据,然后利用正则 `tagNameRegex` 与 `attribRegex` 匹配 HTML 标签与属性,识别潜在的脚本注入结构。`checkForReflectedXSS` 综合请求输入与响应输出进行关联判断。资料来源：[lib/nr-security-agent/lib/core/xss-utils.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/xss-utils.js)

### 框架适配

针对 Next.js,`nr-next.js` 通过 `semver.gte(version, '13.4.13')` 区分新旧路由 API,提取 `match.definition.pathname` 与 `match.params` 后写入 `requestManager` 维护的请求上下文,使得事件能正确关联到动态路由 URL;同时提供 `getAllAPIEndpoints` 扫描 pages 目录以补充 API 路由。资料来源：[lib/instrumentation-security/hooks/nextjs/nr-next.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/nextjs/nr-next.js)

## 常见失败模式与社区关注

社区反馈中,主要影响插桩运行稳定性与安全合规的问题集中在 **依赖漏洞** 上:

- `request-ip@^2.1.3` 间接引入的 `is_js@^0.9.0` 存在 CVE-2020-26302。资料来源：[issue #55](https://github.com/newrelic/csec-node-agent/issues/55)
- `sync-request` 引入的 `form-data` 被报告存在安全公告。资料来源：[issue #304](https://github.com/newrelic/csec-node-agent/issues/304)
- 2.3.0 版本因拉入的 `docker` 依赖被标记为存在任意代码执行风险。资料来源：[issue #282](https://github.com/newrelic/csec-node-agent/issues/282)

上述问题属于依赖治理范畴,不会改变插桩机制本身,但建议生产环境固定至最新稳定版本。当前 v3.0.4 已移除 `uuid` 模块、升级 `protobufjs` 与 `fast-xml-parser`,并修复了 Hapi 插桩与 `shim.argsToArray` 移除。资料来源：[v3.0.4 更新日志](https://github.com/newrelic/csec-node-agent/releases)

## See Also

- 事件与漏洞常量定义
- 安全元数据与调用栈抓取
- HTTP 插桩与 SSRF/RXSS 检测
- Crypto 哈希与随机数插桩
- Next.js 框架适配
- 依赖安全公告(CVE-2020-26302、`form-data`、`docker`)

---

<a id='page-3'></a>

## 通信协议与事件管理

### 相关页面

相关主题：[概览与系统架构](#page-1), [部署、配置与依赖安全](#page-4)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [lib/nr-security-agent/lib/core/sec-agent-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/sec-agent-constants.js)
- [lib/nr-security-agent/lib/core/event.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/event.js)
- [lib/instrumentation-security/core/event-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/core/event-constants.js)
- [lib/instrumentation-security/hooks/http/nr-http.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/http/nr-http.js)
- [lib/instrumentation-security/hooks/fs/nr-fs.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/fs/nr-fs.js)
- [lib/nr-security-agent/lib/core/commonUtils.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/commonUtils.js)
- [lib/nr-security-agent/lib/core/json-file-handler.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/json-file-handler.js)
- [lib/nr-security-agent/lib/core/xss-utils.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/xss-utils.js)
- [third_party_manifest.json](https://github.com/newrelic/csec-node-agent/blob/main/third_party_manifest.json)
- [CONTRIBUTING.md](https://github.com/newrelic/csec-node-agent/blob/main/CONTRIBUTING.md)
</details>

# 通信协议与事件管理

## 概述

New Relic CSEC Node Agent 通过拦截宿主应用的 HTTP、文件系统、数据库等调用，将检测到的事件通过 WebSocket 通道上报至 New Relic 预防（Prevent）服务。本页聚焦"通信协议与事件管理"模块，重点说明事件分类常量、HTTP 拦截器、文件事件钩子以及事件载荷构造所使用的工具方法。

---

## 1. 事件分类与漏洞类型体系

Agent 内部通过两套枚举来描述安全事件：事件类型（`EVENT_TYPE`）与事件分类（`EVENT_CATEGORY`），二者组合形成对漏洞的可读描述。

**主要事件类型**（涵盖系统命令、文件操作、数据库访问、HTTP 请求、反射型 XSS、XXE、LDAP、XPATH、哈希、弱随机数、密码学、命令/代码注入等）定义在 [lib/instrumentation-security/core/event-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/core/event-constants.js) 中；同时 [lib/nr-security-agent/lib/core/event.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/event.js) 进一步把它们映射成可被策略引擎消费的漏洞常量（`SQLI`、`RXSS`、`RCE`、`SSRF` 等）。

资料来源：[lib/instrumentation-security/core/event-constants.js:1-60]()、[lib/nr-security-agent/lib/core/event.js:1-50]()

```mermaid
flowchart LR
  A[Hook 触发点] --> B{事件类型}
  B -->|SQL_DB_COMMAND| C[SQLI]
  B -->|NOSQL_DB_COMMAND| D[NOSQLI]
  B -->|HTTP_REQUEST| E[SSRF]
  B -->|REFLECTED_XSS| F[RXSS]
  B -->|SYSTEM_COMMAND| G[RCE]
  B -->|LDAP| H[LDAP Injection]
  B -->|FILE_OPERATION| I[FILE_ACCESS]
  C & D & E & F & G & H & I --> J[事件载荷 JSON]
  J --> K[WebSocket 上报]
```

**严重程度与策略标签**：[lib/nr-security-agent/lib/core/sec-agent-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/sec-agent-constants.js) 中定义了 `RASP`、`IAST`、`SEVERE`、`HIGH`、`CRITICAL` 等常量，用于在事件元数据中标识检测模式与风险等级，并被 Agent 与策略服务之间的通信协议共用。

---

## 2. HTTP 拦截与反射型 XSS 检测

HTTP 拦截由 `lib/instrumentation-security/hooks/http/nr-http.js` 实现，它通过 `shim.wrap` 包装 Node 的 `http`/`https` 模块，提取请求上下文、响应头与响应体，再调用 `requestManager.getRequest(shim)` 关联到当前 IAST 追踪会话。

**关键流程**：
1. 通过 `unescape-js`、`content-type` 等库解析响应内容类型（`text/html`、`application/json`、`text/plain` 等） 资料来源：[lib/instrumentation-security/hooks/http/nr-http.js:1-30]()
2. 调用 `secUtils.getTraceObject(shim)` 获取追踪栈，构造 `securityMetaData` 载荷 资料来源：[lib/instrumentation-security/hooks/http/nr-http.js:8-15]()
3. 通过 `xss-utils.js` 的 `checkForReflectedXSS` 匹配请求与响应中的脚本构造，命中后生成 `RXSS` 事件 资料来源：[lib/nr-security-agent/lib/core/xss-utils.js:1-40]()
4. 使用 `NR-CSEC-TRACING-DATA` 请求头与 `self-test` 模式在 fuzz 请求下回传检测结果 资料来源：[lib/instrumentation-security/hooks/http/nr-http.js:18-20]()

> 社区反馈：该模块依赖的 `request-ip@^2.1.3` 间接引入了受 CVE-2020-26302 影响的 `is_js@0.9.0`（参见 Issue #55），在升级前应谨慎评估影响。

---

## 3. 文件系统事件与完整性监控

`lib/instrumentation-security/hooks/fs/nr-fs.js` 把 Node `fs` 模块的读、写、改名、复制等函数映射为两类安全事件：

| 钩子函数 | 事件分类 | 典型用途 |
| --- | --- | --- |
| `readFile`、`open`、`createReadStream` | `FILE` / `FILE_OPERATION` | 路径读取审计 |
| `writeFile`、`writeFileSync`（Node > 19） | `FILE_INTEGRITY` | 文件完整性监测 |
| `unlink`、`rm`、`rename`、`copyFile` | `FILE` | 篡改/删除检测 |

实现细节：通过 `functionsProbableToFA` 与 `functionProbableToFI` 两个数组枚举需要包装的函数，运行时通过 `shim.wrap` 注入 `FAWrapper`/`FIWrapper`。当检测到 fuzz 请求头 `NR_CSEC_FUZZ_REQUEST_ID` 时，会额外调用 `callbackHook` 把事件 ID 写回回调链 资料来源：[lib/instrumentation-security/hooks/fs/nr-fs.js:1-80]()。

---

## 4. 事件载荷工具与依赖治理

事件载荷的构造依赖以下基础设施：

- **UUID 与身份标识**：`commonUtils.getUUID()` 优先复用 `process.env.applicationUUID`，否则生成新 UUID 并回写环境变量，确保一次进程仅持有一个 `ApplicationUUID` 资料来源：[lib/nr-security-agent/lib/core/commonUtils.js:1-50]()
- **容器/主机识别**：`getKindIdPair()` 根据 `isContainer`、`isECSContainer`、`isPod` 等标志返回 `(CONTAINER|ECS|HOST, id)`，作为事件 header 的一部分上报 资料来源：[lib/nr-security-agent/lib/core/commonUtils.js:30-50]()
- **本地持久化**：`json-file-handler.js` 以 `fs.readFileSync` / `writeFileSync` 提供同步/异步 JSON 读写，供策略缓存与日志轮转使用 资料来源：[lib/nr-security-agent/lib/core/json-file-handler.js:1-50]()
- **Worker 线程兼容**：`hasWorker()` 在 `require('worker_threads')` 失败时返回 `false`，让事件管理逻辑在旧版 Node 中优雅降级 资料来源：[lib/nr-security-agent/lib/core/commonUtils.js:55-70]()

**依赖治理提示**：第三方清单 [third_party_manifest.json](https://github.com/newrelic/csec-node-agent/blob/main/third_party_manifest.json) 列出了 `request@2.88.2`、`sinon@15.2.0` 等历史版本。社区 Issue #304 指出 `sync-request` 间接引入的 `form-data` 存在已知漏洞；Issue #282 同样提示旧版本会带入易受任意代码执行影响的 Docker 依赖。最新版 v3.0.4 已移除 `uuid` 模块并升级 `protobufjs`、`fast-xml-parser` 等开发依赖，升级前请同步审视构建产物的 SCA 报告 资料来源：[CONTRIBUTING.md:1-20]()。

---

## 5. 常见失败模式

| 场景 | 现象 | 排查建议 |
| --- | --- | --- |
| `request-ip` 触发 CVE 扫描 | CI 阶段 SCA 报警 | 升级至不再传递 `is_js@0.9.0` 的版本，参见 Issue #55 |
| `form-data` 漏洞经 `sync-request` 传递 | 依赖审计失败 | 评估是否可剔除 `sync-request`，参见 Issue #304 |
| 旧版本引入易受 RCE 影响的 Docker 依赖 | 构建被打回 | 升级到 v3.0.4 或更新版本，参见 Issue #282 |
| Node ≥ 19 漏报写文件事件 | 完整性告警缺失 | 确认 `nr-fs.js` 中 `writeFileSync` 已被加入 `functionProbableToFI` |

---

## See Also

- 反射型 XSS 检测：[lib/nr-security-agent/lib/core/xss-utils.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/xss-utils.js)
- Agent 初始化流程：[lib/nr-security-agent/lib/core/sec-agent-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/sec-agent-constants.js)
- 第三方依赖清单：[third_party_manifest.json](https://github.com/newrelic/csec-node-agent/blob/main/third_party_manifest.json)
- 贡献者许可协议：[CONTRIBUTING.md](https://github.com/newrelic/csec-node-agent/blob/main/CONTRIBUTING.md)

---

<a id='page-4'></a>

## 部署、配置与依赖安全

### 相关页面

相关主题：[概览与系统架构](#page-1), [通信协议与事件管理](#page-3)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [package.json](https://github.com/newrelic/csec-node-agent/blob/main/package.json)
- [third_party_manifest.json](https://github.com/newrelic/csec-node-agent/blob/main/third_party_manifest.json)
- [CHANGELOG.md](https://github.com/newrelic/csec-node-agent/blob/main/CHANGELOG.md)
- [CONTRIBUTING.md](https://github.com/newrelic/csec-node-agent/blob/main/CONTRIBUTING.md)
- [lib/nr-security-agent/resources/config.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/resources/config.js)
- [lib/nr-security-agent/lib/core/startup-config.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/startup-config.js)
- [lib/nr-security-agent/lib/core/sec-agent-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/sec-agent-constants.js)
- [lib/nr-security-agent/lib/core/commonUtils.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/commonUtils.js)
- [lib/instrumentation-security/hooks/http/nr-http.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/http/nr-http.js)
</details>

# 部署、配置与依赖安全

## 概述

New Relic CSEC（Cloud Security）Node Agent 是 New Relic APM Agent 的伴生模块，负责在 Node.js 进程内执行 IAST（交互式应用安全测试）与 RASP（运行时应用自我保护）检测。围绕"部署、配置与依赖安全"这一主题，仓库同时提供了：

- **启动常量与默认配置**，定义代理在何种条件下进行 attach、如何分类 IAST/RASP 事件、如何处理日志级别等；
- **依赖与第三方清单**，通过 `package.json` 与 `third_party_manifest.json` 声明直接和传递依赖；
- **变更历史**，记录与安全相关的依赖升级与代理行为变更。

下文按"运行时配置"、"部署前置条件"和"依赖安全风险"三部分展开，并引用社区中已知的几个相关问题作为佐证。

## 运行时配置体系

代理在加载时首先读取一组核心常量，再由 `startup-config.js` 完成启动决策。下列常量在 [lib/nr-security-agent/lib/core/sec-agent-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/sec-agent-constants.js) 中集中定义：

| 类别 | 关键常量 | 作用 |
| --- | --- | --- |
| 启动流程 | `AGENT_INIT_SUCCESSFUL`、`AGENT_INIT_FAILED`、`AGENT_ATTACH_FAIL` | 标识进程 attach 是否成功，区分静态 attach 与 CSEC_GROUP_NAME 缺失场景 |
| 日志 | `LOG_FILE_INITIATED_MSG`、`LOG_CONFIGURED_SUCCESSFULLY_MSG` | 通知用户日志路径与级别（`%s` 占位符填充 level 与 maxSize） |
| 漏洞分类 | `IAST`、`RASP`、`SEVERE / HIGH / CRITICAL` | 决定事件以 IAST 还是 RASP 模式上报，区分严重级别 |
| HTTP 头 | `XFORFOR`、`CONTENT_TYPE` | 用于反射型 XSS 与 SSRF 检测 |

常量中 `CSEC_SEP = ':IAST:'` 等分隔符用于在多模块之间传递事件 ID；`EXITEVENT` 标识 `exit-event`，配合 `requestManager` 在请求结束时回收上下文。`commonUtils.js` 中的 `getUUID()` 进一步保证每个应用进程拥有独立 `applicationUUID` 并写入 `process.env`，从而在横向扩展场景下保持稳定身份（[lib/nr-security-agent/lib/core/commonUtils.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/commonUtils.js)）。

代理还提供 `getKindIdPair()` 区分容器、ECS 任务、Kubernetes Pod 与裸主机，结合 `getExecutionId()` 共同形成事件指纹。

## 部署前置条件与 attach 流程

CSEC 代理的 attach 行为受环境变量严格控制。日志消息中明确出现：

- `AGENT_INIT_SUCCESSFUL` —— `[STEP-3][protection][BEGIN] Node CSEC Agent Attached To Process: PID = %s, With Generated Applicationuid = %s By Static Attachment`；
- `AGENT_ATTACH_FAIL` —— `CSEC_GROUP_NAME Environment Not Present, Agent Attachment Failed`（[sec-agent-constants.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/sec-agent-constants.js)）。

这意味着：**必须设置 `CSEC_GROUP_NAME` 环境变量，代理才能在静态 attach 场景下完成初始化**。若未设置，代理会跳过保护阶段，仅保留基础检测事件流。

容器/Pod 场景下，`getKindIdPair()` 会返回 `CONTAINER`、`ECS` 等 Kind，用作 New Relic 端应用分组的标识。`hasWorker()` 与 `runtimeSupportsFunctionGenerators()` 等工具函数则用于探测运行时的 `worker_threads` 与 generator 支持能力，便于在 Lambda、Serverless 等受限环境中优雅降级（[commonUtils.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/nr-security-agent/lib/core/commonUtils.js)）。

下图为简化的 attach 决策流：

```mermaid
flowchart TD
    A[Node 进程启动] --> B{CSEC_GROUP_NAME 已设置?}
    B -- 否 --> C[仅记录 AGENT_ATTACH_FAIL<br/>跳过 RASP 保护]
    B -- 是 --> D[收集 ENV / APP_INFO]
    D --> E[生成 applicationUUID]
    E --> F[Static Attachment 成功]
    F --> G[加载 IAST / RASP hooks]
    G --> H[进入事件循环]
```

部署侧还需关注 HTTP 层对客户端 IP 的处理：`hooks/http/nr-http.js` 顶部通过 `require('request-ip')` 提取 `x-forwarded-for` 等头（[lib/instrumentation-security/hooks/http/nr-http.js](https://github.com/newrelic/csec-node-agent/blob/main/lib/instrumentation-security/hooks/http/nr-http.js)），从而将请求参与方纳入 IAST 上下文。

## 依赖与第三方组件安全

`third_party_manifest.json` 列出了直接与传递依赖的版本、许可证与上游仓库，是合规审计的主要依据（[third_party_manifest.json](https://github.com/newrelic/csec-node-agent/blob/main/third_party_manifest.json)）。`package.json` 中与安全直接相关的依赖包括 `request-ip`、`sync-request`、`docker` 等。

社区已经记录的多起依赖风险集中在以下方面：

- **CVE-2020-26302（request-ip → is_js）**：`request-ip@^2.1.3` 的传递依赖 `is_js@^0.9.0` 历史上存在原型链污染风险（Issue #55）。`request-ip` 仍被 `hooks/http/nr-http.js` 直接引用以获取客户端 IP。
- **form-data via sync-request**：Issue #304 指出 `sync-request` 引入的旧版 `form-data` 存在已知漏洞，CI/CD 流水线扫描时可能命中。
- **docker 传递依赖任意代码执行**：Issue #282 中报告，2.3.0 版本的发布引入了 `docker` 模块作为传递依赖，被扫描器标记为"可导致任意代码执行"，需要替换或固定版本。

`CHANGELOG.md` 中的 3.0.4 条目亦印证了团队正在持续收紧依赖：

> * remove dependency on uuid module (#357)
> * update hapi instrumentation, remove shim.argsToArray method (#360)
> * (deps-dev): bump protobufjs from 7.2.5 to 7.5.8 (#358)

这表明项目维护方对历史累积的依赖会主动瘦身（移除 `uuid`）并升级存在 CVE 的开发依赖。运营侧建议：

1. 在 CI 阶段对照 `third_party_manifest.json` 做 SCA 扫描，对 `request-ip`、`sync-request`、`docker` 这类已暴露风险的依赖设置例外或替换策略；
2. 通过 npm overrides / Yarn resolutions 锁定 `form-data`、`is_js` 至安全版本；
3. 部署前确认 `CSEC_GROUP_NAME` 等环境变量到位，否则 RASP 保护将不会生效。

## 常见失败模式

- **`AGENT_ATTACH_FAIL`**：未设置 `CSEC_GROUP_NAME`，RASP 阶段被跳过，IAST 仍可工作但缺少运行时拦截；
- **日志级别过细**：`LOG_CONFIGURED_SUCCESSFULLY_MSG` 中 `%s` 替换的是运行时级别，过低的级别会产生大量 `[STEP-x]` 调试日志，建议生产环境调整为 WARN；
- **IP 提取异常**：`nr-http.js` 中 `request-ip` 的旧版在畸形 `x-forwarded-for` 头下可能抛错，必要时可结合反向代理规范化请求头；
- **依赖扫描误报**：Issue #282 表明传递依赖可能拖累上游项目，构建产物前应保留一份精简的 SBOM。

## See Also

- [核心常量与事件模型](core-constants-and-events.md)
- [IAST 检测与 RASP 钩子机制](iast-rasp-instrumentation.md)
- [HTTP 反射型 XSS / SSRF 检测](http-vulnerability-detection.md)

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Doramagic 踩坑日志

项目：newrelic/csec-node-agent

摘要：发现 9 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：安全/权限坑 - 来源证据：[Repolinter] Open Source Policy Issues。

## 1. 安全/权限坑 · 来源证据：[Repolinter] Open Source Policy Issues

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Repolinter] Open Source Policy Issues
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/newrelic/csec-node-agent/issues/26 | 来源类型 github_issue 暴露的待验证使用条件。

## 2. 身份坑 · 仓库名和安装名不一致

- 严重度：medium
- 证据强度：runtime_trace
- 发现：仓库名 `csec-node-agent` 与安装入口 `@newrelic/security-agent@latest` 不完全一致。
- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。
- 复现命令：`npm install @newrelic/security-agent@latest`
- 证据：identity.distribution | https://www.npmjs.com/package/@newrelic/security-agent | repo=csec-node-agent; install=@newrelic/security-agent@latest

## 3. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 证据：capability.assumptions | https://www.npmjs.com/package/@newrelic/security-agent | README/documentation is current enough for a first validation pass.

## 4. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 证据：evidence.maintainer_signals | https://www.npmjs.com/package/@newrelic/security-agent | last_activity_observed missing

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 证据：downstream_validation.risk_items | https://www.npmjs.com/package/@newrelic/security-agent | no_demo; severity=medium

## 6. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 证据：risks.scoring_risks | https://www.npmjs.com/package/@newrelic/security-agent | no_demo; severity=medium

## 7. 安全/权限坑 · 来源证据：Dependency Vulnerability: uuid

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Dependency Vulnerability: uuid
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/newrelic/csec-node-agent/issues/353 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 8. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 证据：evidence.maintainer_signals | https://www.npmjs.com/package/@newrelic/security-agent | issue_or_pr_quality=unknown

## 9. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 证据：evidence.maintainer_signals | https://www.npmjs.com/package/@newrelic/security-agent | release_recency=unknown

<!-- canonical_name: newrelic/csec-node-agent; human_manual_source: deepwiki_human_wiki -->
