Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(serve): prevent serving unrestricted files #3321

Merged
merged 7 commits into from
May 10, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from 'fs'
import path from 'path'
import { Plugin } from './plugin'
import { BuildOptions, resolveBuildOptions } from './build'
import { ServerOptions } from './server'
import { ResolvedServerOptions, ServerOptions } from './server'
import { CSSOptions } from './plugins/css'
import {
createDebugger,
Expand Down Expand Up @@ -35,6 +35,7 @@ import {
} from './server/pluginContainer'
import aliasPlugin from '@rollup/plugin-alias'
import { build } from 'esbuild'
import { searchForWorkspaceRoot } from './server/searchRoot'

const debug = createDebugger('vite:config')

Expand Down Expand Up @@ -201,7 +202,7 @@ export type ResolvedConfig = Readonly<
alias: Alias[]
}
plugins: readonly Plugin[]
server: ServerOptions
server: ResolvedServerOptions
build: ResolvedBuildOptions
assetsInclude: (file: string) => boolean
logger: Logger
Expand Down Expand Up @@ -369,6 +370,13 @@ export async function resolveConfig(
}
}

const server = config.server || {}
const serverRoot = path.resolve(
resolvedRoot,
server.fsServe?.root || searchForWorkspaceRoot(resolvedRoot)
)
server.fsServe = { root: serverRoot }
underfin marked this conversation as resolved.
Show resolved Hide resolved

const { publicDir } = config
const resolvedPublicDir =
publicDir !== false && publicDir !== ''
Expand All @@ -392,7 +400,7 @@ export async function resolveConfig(
mode,
isProduction,
plugins: userPlugins,
server: config.server || {},
server: server as ResolvedServerOptions,
build: resolvedBuildOptions,
env: {
...userEnv,
Expand Down
8 changes: 6 additions & 2 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ export interface ServerOptions {
fsServe?: FileSystemServeOptions
}

export interface ResolvedServerOptions extends ServerOptions {
fsServe: Required<FileSystemServeOptions>
}

export interface FileSystemServeOptions {
/**
* Restrict accessing files outside this directory will result in a 403.
Expand Down Expand Up @@ -276,7 +280,7 @@ export async function createServer(
): Promise<ViteDevServer> {
const config = await resolveConfig(inlineConfig, 'serve', 'development')
const root = config.root
const serverConfig = config.server || {}
const serverConfig = config.server
const middlewareMode = !!serverConfig.middlewareMode

const middlewares = connect() as Connect.Server
Expand Down Expand Up @@ -550,7 +554,7 @@ async function startServer(
throw new Error('Cannot call server.listen in middleware mode.')
}

const options = server.config.server || {}
const options = server.config.server
let port = inlinePort || options.port || 3000
let hostname: string | undefined
if (options.host === undefined || options.host === 'localhost') {
Expand Down
27 changes: 27 additions & 0 deletions packages/vite/src/node/server/middlewares/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,35 @@ export function errorMiddleware(
if (allowNext) {
next()
} else {
if (err instanceof FileOutSideError) {
res.statusCode = 403
res.write(renderErrorHTML(err.message))
res.end()
}
res.statusCode = 500
res.end()
}
}
}

export class FileOutSideError extends Error {
underfin marked this conversation as resolved.
Show resolved Hide resolved
constructor(msg: string, public url: string, public serveRoot: string) {
super(msg)
}
}

export function renderErrorHTML(msg: string): string {
// to have syntax highlighting and autocompletion in IDE
const html = String.raw
return html`
<body>
<h1>403 Restricted</h1>
<p>${msg.replace(/\n/g, '<br/>')}</p>
<style>
body {
padding: 1em 2em;
}
</style>
</body>
`
}
48 changes: 13 additions & 35 deletions packages/vite/src/node/server/middlewares/static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Connect } from 'types/connect'
import { ResolvedConfig } from '../..'
import { FS_PREFIX } from '../../constants'
import { cleanUrl, fsPathFromId, isImportRequest } from '../../utils'
import { searchForWorkspaceRoot } from '../searchRoot'
import { FileOutSideError } from './error'

const sirvOptions: Options = {
dev: true,
Expand Down Expand Up @@ -80,10 +80,6 @@ export function serveRawFsMiddleware(
): Connect.NextHandleFunction {
const isWin = os.platform() === 'win32'
const serveFromRoot = sirv('/', sirvOptions)
const serveRoot = path.resolve(
config.root,
config.server?.fsServe?.root || searchForWorkspaceRoot(config.root)
)

// Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...`
return function viteServeRawFsMiddleware(req, res, next) {
Expand All @@ -94,12 +90,10 @@ export function serveRawFsMiddleware(
// searching based from fs root.
if (url.startsWith(FS_PREFIX)) {
// restrict files outside of `fsServe.root`
if (!path.resolve(fsPathFromId(url)).startsWith(serveRoot + path.sep)) {
res.statusCode = 403
res.write(renderFsRestrictedHTML(serveRoot))
res.end()
return
}
checkFileOutSide(
path.resolve(fsPathFromId(url)),
config.server.fsServe.root
)

url = url.slice(FS_PREFIX.length)
if (isWin) url = url.replace(/^[A-Z]:/i, '')
Expand All @@ -112,28 +106,12 @@ export function serveRawFsMiddleware(
}
}

function renderFsRestrictedHTML(root: string) {
// to have syntax highlighting and autocompletion in IDE
const html = String.raw
return html`
<body>
<h1>403 Restricted</h1>
<p>
For security concerns, accessing files outside of workspace root
(<code>${root}</code>) is restricted since Vite v2.3.x
</p>
<p>
Refer to docs
<a href="https://vitejs.dev/config/#server-fsserveroot">
https://vitejs.dev/config/#server-fsserveroot
</a>
for configurations and more details.
</p>
<style>
body {
padding: 1em 2em;
}
</style>
</body>
`
export function checkFileOutSide(url: string, serveRoot: string): void {
underfin marked this conversation as resolved.
Show resolved Hide resolved
if (!url.startsWith(serveRoot + path.sep)) {
throw new FileOutSideError(
`The request url "${url}" is outside of vite dev server root "${serveRoot}". \nFor security concerns, accessing files outside of workspace root is restricted since Vite v2.3.x. \nRefer to docs https://vitejs.dev/config/#server-fsserveroot for configurations and more details.`,
underfin marked this conversation as resolved.
Show resolved Hide resolved
url,
serveRoot
)
}
}
4 changes: 4 additions & 0 deletions packages/vite/src/node/server/transformRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
import { checkPublicFile } from '../plugins/asset'
import { ssrTransform } from '../ssr/ssrTransform'
import { injectSourcesContent } from './sourcemap'
import { checkFileOutSide } from './middlewares/static'

const debugLoad = createDebugger('vite:load')
const debugTransform = createDebugger('vite:transform')
Expand Down Expand Up @@ -73,6 +74,9 @@ export async function transformRequest(
// if the file is a binary, there should be a plugin that already loaded it
// as string
try {
if (!options.ssr) {
checkFileOutSide(file, config.server.fsServe.root)
}
code = await fs.readFile(file, 'utf-8')
isDebug && debugLoad(`${timeFrom(loadStart)} [fs] ${prettyUrl}`)
} catch (e) {
Expand Down