漏洞来源

漏洞描述

n8n 是一个开源工作流自动化平台。在 2.14.1、2.13.3 和 1.123.27 版本之前,拥有创建或修改工作流权限的已认证用户可以利用 XML 和 GSuiteAdmin 节点中的原型污染漏洞。攻击者通过在节点配置中提供精心构造的参数,可以将攻击者控制的值写入 `Object.prototype`。攻击者可以利用这种原型污染漏洞在 n8n 实例上执行远程代码。该问题已在 n8n 版本 2.14.1、2.13.3 和 1.123.27 中修复。用户应升级到这些版本或更高版本以修复此漏洞。如果无法立即升级,管理员应考虑以下临时缓解措施:将工作流的创建和编辑权限限制为仅限完全信任的用户,和/或通过将 `n8n-nodes-base.xml` 添加到 `NODES_EXCLUDE` 环境变量来禁用 XML 节点。这些变通办法并不能完全消除风险,只能作为短期缓解措施。

漏洞分析

首先分析xml 节点中的原型链污染

漏洞文件在:packages/nodes-base/nodes/Xml/Xml.node.ts

import { Builder, Parser } from 'xml2js';
import { IExecuteFunctions } from 'n8n-core';
import {
	IDataObject,
	INodeExecutionData,
	INodeType,
	INodeTypeDescription,
	NodeOperationError,
} from 'n8n-workflow';

export class Xml implements INodeType {
	description: INodeTypeDescription = {
		displayName: 'XML',
		name: 'xml',
		icon: 'fa:file-code',
		group: ['transform'],
		version: 1,
		subtitle: '={{$parameter["mode"]==="jsonToxml" ? "JSON to XML" : "XML to JSON"}}',
		description: 'Convert data from and to XML',
		defaults: {
			name: 'XML',
			color: '#333377',
		},
		inputs: ['main'],
		outputs: ['main'],
		properties: [
			{
				displayName: 'Mode',
				name: 'mode',
				type: 'options',
				options: [
					{
						name: 'JSON to XML',
						value: 'jsonToxml',
						description: 'Converts data from JSON to XML',
					},
					{
						name: 'XML to JSON',
						value: 'xmlToJson',
						description: 'Converts data from XML to JSON',
					},
				],
				default: 'xmlToJson',
				description: 'From and to what format the data should be converted',
			},

			// ----------------------------------
			//         option:jsonToxml
			// ----------------------------------
			{
				displayName: 'Property Name',
				name: 'dataPropertyName',
				type: 'string',
				displayOptions: {
					show: {
						mode: ['jsonToxml'],
					},
				},
				default: 'data',
				required: true,
				description: 'Name of the property to which to contains the converted XML data',
			},
			{
				displayName: 'Options',
				name: 'options',
				type: 'collection',
				placeholder: 'Add Option',
				displayOptions: {
					show: {
						mode: ['jsonToxml'],
					},
				},
				default: {},
				options: [
					{
						displayName: 'Allow Surrogate Chars',
						name: 'allowSurrogateChars',
						type: 'boolean',
						default: false,
						description: 'Whether to allow using characters from the Unicode surrogate blocks',
					},
					{
						displayName: 'Attribute Key',
						name: 'attrkey',
						type: 'string',
						default: '$',
						description: 'Prefix that is used to access the attributes',
					},
					{
						displayName: 'Cdata',
						name: 'cdata',
						type: 'boolean',
						default: false,
						description:
							'Whether to wrap text nodes in <![CDATA[ ... ]]> instead of escaping when necessary. Does not add <![CDATA[ ... ]]> if it is not required.',
					},
					{
						displayName: 'Character Key',
						name: 'charkey',
						type: 'string',
						default: '_',
						description: 'Prefix that is used to access the character content',
					},
					{
						displayName: 'Headless',
						name: 'headless',
						type: 'boolean',
						default: false,
						description: 'Whether to omit the XML header',
					},
					{
						displayName: 'Root Name',
						name: 'rootName',
						type: 'string',
						default: 'root',
						description: 'Root element name to be used',
					},
				],
			},

			// ----------------------------------
			//         option:xmlToJson
			// ----------------------------------
			{
				displayName: 'Property Name',
				name: 'dataPropertyName',
				type: 'string',
				displayOptions: {
					show: {
						mode: ['xmlToJson'],
					},
				},
				default: 'data',
				required: true,
				description: 'Name of the property which contains the XML data to convert',
			},
			{
				displayName: 'Options',
				name: 'options',
				type: 'collection',
				placeholder: 'Add Option',
				displayOptions: {
					show: {
						mode: ['xmlToJson'],
					},
				},
				default: {},
				options: [
					{
						displayName: 'Attribute Key',
						name: 'attrkey',
						type: 'string',
						default: '$',
						description: 'Prefix that is used to access the attributes',
					},
					{
						displayName: 'Character Key',
						name: 'charkey',
						type: 'string',
						default: '_',
						description: 'Prefix that is used to access the character content',
					},
					{
						displayName: 'Explicit Array',
						name: 'explicitArray',
						type: 'boolean',
						default: false,
						description:
							'Whether to always put child nodes in an array if true; otherwise an array is created only if there is more than one',
					},
					{
						displayName: 'Explicit Root',
						name: 'explicitRoot',
						type: 'boolean',
						default: true,
						description:
							'Whether to set this if you want to get the root node in the resulting object',
					},
					{
						displayName: 'Ignore Attributes',
						name: 'ignoreAttrs',
						type: 'boolean',
						default: false,
						description: 'Whether to ignore all XML attributes and only create text nodes',
					},
					{
						displayName: 'Merge Attributes',
						name: 'mergeAttrs',
						type: 'boolean',
						default: true,
						description:
							'Whether to merge attributes and child elements as properties of the parent, instead of keying attributes off a child attribute object. This option is ignored if ignoreAttrs is true.',
					},
					{
						displayName: 'Normalize',
						name: 'normalize',
						type: 'boolean',
						default: false,
						description: 'Whether to trim whitespaces inside text nodes',
					},
					{
						displayName: 'Normalize Tags',
						name: 'normalizeTags',
						type: 'boolean',
						default: false,
						description: 'Whether to normalize all tag names to lowercase',
					},
					{
						displayName: 'Trim',
						name: 'trim',
						type: 'boolean',
						default: false,
						description: 'Whether to trim the whitespace at the beginning and end of text nodes',
					},
				],
			},
		],
	};

	async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
		const items = this.getInputData();

		const mode = this.getNodeParameter('mode', 0) as string;
		const dataPropertyName = this.getNodeParameter('dataPropertyName', 0) as string;
		const options = this.getNodeParameter('options', 0, {}) as IDataObject;

		let item: INodeExecutionData;
		const returnData: INodeExecutionData[] = [];
		for (let itemIndex = 0; itemIndex < items.length; itemIndex++) {
			try {
				item = items[itemIndex];

				if (mode === 'xmlToJson') {
					const parserOptions = Object.assign(
						{
							mergeAttrs: true,
							explicitArray: false,
						},
						options,
					);

					const parser = new Parser(parserOptions);

					if (item.json[dataPropertyName] === undefined) {
						throw new NodeOperationError(
							this.getNode(),
							`No json property "${dataPropertyName}" does not exists on item!`,
							{ itemIndex },
						);
					}

					// @ts-ignore
					const json = await parser.parseStringPromise(item.json[dataPropertyName]);
					returnData.push({ json });
				} else if (mode === 'jsonToxml') {
					const builder = new Builder(options);

					returnData.push({
						json: {
							[dataPropertyName]: builder.buildObject(items[itemIndex].json),
						},
						pairedItem: {
							item: itemIndex,
						},
					});
				} else {
					throw new NodeOperationError(this.getNode(), `The operation "${mode}" is not known!`, {
						itemIndex,
					});
				}
			} catch (error) {
				if (this.continueOnFail()) {
					items[itemIndex] = {
						json: {
							error: error.message,
						},
						pairedItem: {
							item: itemIndex,
						},
					};
					continue;
				}
				throw error;
			}
		}

		return this.prepareOutputData(returnData);
	}
}

这里接受了外部传参,然后将参数直接给了Object.assign进行处理

Object.assign 的作用是:遍历源对象的所有可枚举属性,并将它们直接复制到目标对象上。

具体实现可参考:js原型链污染-腾讯云开发者社区-腾讯云

攻击者构造 options 对象,使其包含键 __proto__。
options = { "__proto__": { "polluted": true } }
当
Object.assign 遍历 options 的属性时,它遇到了键 __proto__。它执行了一个内部操作:target["__proto__"] = source["__proto__"]。

在 JavaScript 中,访问 obj["__proto__"] 并不是在访问一个普通的属性,而是在访问该对象的原型指针。
因此,这行代码实际上执行了:
Object.setPrototypeOf(target, { "polluted": true })

那个原本临时配置对象 { mergeAttrs: true ... },突然变成了 { "polluted": true } 的实例。如果这个对象随后被用于某些检查逻辑,或者其原型链被进一步利用,污染就发生了。

接下来分析GSuiteAdmin 节点

漏洞文件在:packages/nodes-base/nodes/Google/GSuiteAdmin/GSuiteAdmin.node.ts

import { IExecuteFunctions } from 'n8n-core';

import {
	IDataObject,
	ILoadOptionsFunctions,
	INodeExecutionData,
	INodePropertyOptions,
	INodeType,
	INodeTypeDescription,
	NodeOperationError,
} from 'n8n-workflow';

import { googleApiRequest, googleApiRequestAllItems } from './GenericFunctions';

import { userFields, userOperations } from './UserDescription';

import { groupFields, groupOperations } from './GroupDescripion';

export class GSuiteAdmin implements INodeType {
	description: INodeTypeDescription = {
		displayName: 'G Suite Admin',
		name: 'gSuiteAdmin',
		// eslint-disable-next-line n8n-nodes-base/node-class-description-icon-not-svg
		icon: 'file:gSuiteAdmin.png',
		group: ['input'],
		version: 1,
		subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
		description: 'Consume G Suite Admin API',
		defaults: {
			name: 'G Suite Admin',
		},
		inputs: ['main'],
		outputs: ['main'],
		credentials: [
			{
				name: 'gSuiteAdminOAuth2Api',
				required: true,
			},
		],
		properties: [
			{
				displayName: 'Resource',
				name: 'resource',
				type: 'options',
				noDataExpression: true,
				options: [
					{
						name: 'Group',
						value: 'group',
					},
					{
						name: 'User',
						value: 'user',
					},
				],
				default: 'user',
			},
			...groupOperations,
			...groupFields,
			...userOperations,
			...userFields,
		],
	};

	methods = {
		loadOptions: {
			// Get all the domains to display them to user so that he can
			// select them easily
			async getDomains(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
				const returnData: INodePropertyOptions[] = [];
				const domains = await googleApiRequestAllItems.call(
					this,
					'domains',
					'GET',
					'/directory/v1/customer/my_customer/domains',
				);
				for (const domain of domains) {
					const domainName = domain.domainName;
					const domainId = domain.domainName;
					returnData.push({
						name: domainName,
						value: domainId,
					});
				}
				return returnData;
			},
			// Get all the schemas to display them to user so that he can
			// select them easily
			async getSchemas(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> {
				const returnData: INodePropertyOptions[] = [];
				const schemas = await googleApiRequestAllItems.call(
					this,
					'schemas',
					'GET',
					'/directory/v1/customer/my_customer/schemas',
				);
				for (const schema of schemas) {
					const schemaName = schema.displayName;
					const schemaId = schema.schemaName;
					returnData.push({
						name: schemaName,
						value: schemaId,
					});
				}
				return returnData;
			},
		},
	};

	async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
		const items = this.getInputData();
		const returnData: INodeExecutionData[] = [];
		const length = items.length;
		const qs: IDataObject = {};
		let responseData;
		const resource = this.getNodeParameter('resource', 0) as string;
		const operation = this.getNodeParameter('operation', 0) as string;
		for (let i = 0; i < length; i++) {
			if (resource === 'group') {
				//https://developers.google.com/admin-sdk/directory/v1/reference/groups/insert
				if (operation === 'create') {
					const email = this.getNodeParameter('email', i) as string;

					const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;

					const body: IDataObject = {
						email,
					};

					Object.assign(body, additionalFields);

					responseData = await googleApiRequest.call(this, 'POST', `/directory/v1/groups`, body);
				}

				//https://developers.google.com/admin-sdk/directory/v1/reference/groups/delete
				if (operation === 'delete') {
					const groupId = this.getNodeParameter('groupId', i) as string;

					responseData = await googleApiRequest.call(
						this,
						'DELETE',
						`/directory/v1/groups/${groupId}`,
						{},
					);

					responseData = { success: true };
				}

				//https://developers.google.com/admin-sdk/directory/v1/reference/groups/get
				if (operation === 'get') {
					const groupId = this.getNodeParameter('groupId', i) as string;

					responseData = await googleApiRequest.call(
						this,
						'GET',
						`/directory/v1/groups/${groupId}`,
						{},
					);
				}

				//https://developers.google.com/admin-sdk/directory/v1/reference/groups/list
				if (operation === 'getAll') {
					const returnAll = this.getNodeParameter('returnAll', i) as boolean;

					const options = this.getNodeParameter('options', i) as IDataObject;

					Object.assign(qs, options);

					if (qs.customer === undefined) {
						qs.customer = 'my_customer';
					}

					if (returnAll) {
						responseData = await googleApiRequestAllItems.call(
							this,
							'groups',
							'GET',
							`/directory/v1/groups`,
							{},
							qs,
						);
					} else {
						qs.maxResults = this.getNodeParameter('limit', i) as number;

						responseData = await googleApiRequest.call(this, 'GET', `/directory/v1/groups`, {}, qs);

						responseData = responseData.groups;
					}
				}

				//https://developers.google.com/admin-sdk/directory/v1/reference/groups/update
				if (operation === 'update') {
					const groupId = this.getNodeParameter('groupId', i) as string;

					const updateFields = this.getNodeParameter('updateFields', i) as IDataObject;

					const body: IDataObject = {};

					Object.assign(body, updateFields);

					responseData = await googleApiRequest.call(
						this,
						'PUT',
						`/directory/v1/groups/${groupId}`,
						body,
					);
				}
			}

			if (resource === 'user') {
				//https://developers.google.com/admin-sdk/directory/v1/reference/users/insert
				if (operation === 'create') {
					const domain = this.getNodeParameter('domain', i) as string;

					const firstName = this.getNodeParameter('firstName', i) as string;

					const lastName = this.getNodeParameter('lastName', i) as string;

					const password = this.getNodeParameter('password', i) as string;

					const username = this.getNodeParameter('username', i) as string;

					const makeAdmin = this.getNodeParameter('makeAdmin', i) as boolean;

					const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;

					const body: IDataObject = {
						name: {
							familyName: lastName,
							givenName: firstName,
						},
						password,
						primaryEmail: `${username}@${domain}`,
					};

					Object.assign(body, additionalFields);

					if (additionalFields.phoneUi) {
						const phones = (additionalFields.phoneUi as IDataObject).phoneValues as IDataObject[];

						body.phones = phones;

						delete body.phoneUi;
					}

					if (additionalFields.emailUi) {
						const emails = (additionalFields.emailUi as IDataObject).emailValues as IDataObject[];

						body.emails = emails;

						delete body.emailUi;
					}

					responseData = await googleApiRequest.call(this, 'POST', `/directory/v1/users`, body, qs);

					if (makeAdmin) {
						await googleApiRequest.call(
							this,
							'POST',
							`/directory/v1/users/${responseData.id}/makeAdmin`,
							{ status: true },
						);

						responseData.isAdmin = true;
					}
				}

				//https://developers.google.com/admin-sdk/directory/v1/reference/users/delete
				if (operation === 'delete') {
					const userId = this.getNodeParameter('userId', i) as string;

					responseData = await googleApiRequest.call(
						this,
						'DELETE',
						`/directory/v1/users/${userId}`,
						{},
					);

					responseData = { success: true };
				}

				//https://developers.google.com/admin-sdk/directory/v1/reference/users/get
				if (operation === 'get') {
					const userId = this.getNodeParameter('userId', i) as string;

					const projection = this.getNodeParameter('projection', i) as string;

					const options = this.getNodeParameter('options', i) as IDataObject;

					qs.projection = projection;

					Object.assign(qs, options);

					if (qs.customFieldMask) {
						qs.customFieldMask = (qs.customFieldMask as string[]).join(' ');
					}

					if (qs.projection === 'custom' && qs.customFieldMask === undefined) {
						throw new NodeOperationError(
							this.getNode(),
							'When projection is set to custom, the custom schemas field must be defined',
							{ itemIndex: i },
						);
					}

					responseData = await googleApiRequest.call(
						this,
						'GET',
						`/directory/v1/users/${userId}`,
						{},
						qs,
					);
				}

				//https://developers.google.com/admin-sdk/directory/v1/reference/users/list
				if (operation === 'getAll') {
					const returnAll = this.getNodeParameter('returnAll', i) as boolean;

					const projection = this.getNodeParameter('projection', i) as string;

					const options = this.getNodeParameter('options', i) as IDataObject;

					qs.projection = projection;

					Object.assign(qs, options);

					if (qs.customer === undefined) {
						qs.customer = 'my_customer';
					}

					if (qs.customFieldMask) {
						qs.customFieldMask = (qs.customFieldMask as string[]).join(' ');
					}

					if (qs.projection === 'custom' && qs.customFieldMask === undefined) {
						throw new NodeOperationError(
							this.getNode(),
							'When projection is set to custom, the custom schemas field must be defined',
							{ itemIndex: i },
						);
					}

					if (returnAll) {
						responseData = await googleApiRequestAllItems.call(
							this,
							'users',
							'GET',
							`/directory/v1/users`,
							{},
							qs,
						);
					} else {
						qs.maxResults = this.getNodeParameter('limit', i) as number;

						responseData = await googleApiRequest.call(this, 'GET', `/directory/v1/users`, {}, qs);

						responseData = responseData.users;
					}
				}

				//https://developers.google.com/admin-sdk/directory/v1/reference/users/update
				if (operation === 'update') {
					const userId = this.getNodeParameter('userId', i) as string;

					const updateFields = this.getNodeParameter('updateFields', i) as IDataObject;

					const body: {
						name: { givenName?: string; familyName?: string };
						emails?: IDataObject[];
						phones?: IDataObject[];
					} = { name: {} };

					Object.assign(body, updateFields);

					if (updateFields.firstName) {
						body.name.givenName = updateFields.firstName as string;
						//@ts-ignore
						delete body.firstName;
					}

					if (updateFields.lastName) {
						body.name.familyName = updateFields.lastName as string;
						//@ts-ignore
						delete body.lastName;
					}

					if (Object.keys(body.name).length === 0) {
						//@ts-ignore
						delete body.name;
					}

					if (updateFields.phoneUi) {
						const phones = (updateFields.phoneUi as IDataObject).phoneValues as IDataObject[];

						body.phones = phones;

						//@ts-ignore
						delete body.phoneUi;
					}

					if (updateFields.emailUi) {
						const emails = (updateFields.emailUi as IDataObject).emailValues as IDataObject[];

						body.emails = emails;

						//@ts-ignore
						delete body.emailUi;
					}

					//@ts-ignore
					body['customSchemas'] = { testing: { hasdog: true } };

					responseData = await googleApiRequest.call(
						this,
						'PUT',
						`/directory/v1/users/${userId}`,
						body,
						qs,
					);
				}
			}

			const executionData = this.helpers.constructExecutionMetaData(
				this.helpers.returnJsonArray(responseData),
				{ itemData: { item: i } },
			);

			returnData.push(...executionData);
		}

		return this.prepareOutputData(returnData);
	}
}

接下来逐帧分析漏洞

这里接收用户的传参

const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject;
const body: IDataObject = { email };
Object.assign(body, additionalFields);

再看下sink点

这里 body 是发送给 API 的数据体。
如果
additionalFields = { "__proto__": { "isAdmin": true } }
它将
additionalFields 的属性赋值给 body。执行:body["__proto__"] = { "isAdmin": true }。

最终body 的原型被修改了。如果 body 是 {}(空对象字面量),它直接继承自 Object.prototype。
执行
body["__proto__"] = ... 等同于:Object.prototype["isAdmin"] = true,之后,n8n 进程中创建的每一个普通对象({}),都会自动拥有 isAdmin: true 属性。

所以将控制的值写入到 GSuiteAdmin 节点Object.prototype中,就可以进行远程命令执行了

漏洞修复

该问题已在 n8n 版本 2.14.1、2.13.3 和 1.123.27 中修复。用户应升级到这些版本之一或更高版本以修复该漏洞。

  • 仅允许完全信任的用户创建和编辑工作流程。
  • n8n-nodes-base.xml通过向环境变量中添加内容来禁用 XML 节点NODES_EXCLUDE。

参考