Skip to content

Commit d477972

Browse files
authored
Add origin checks to web sockets (#6048)
* Move splitOnFirstEquals to util I will be making use of this to parse the forwarded header. * Type splitOnFirstEquals with two items Also add some test cases. * Check origin header on web sockets * Update changelog with origin check * Fix web sockets not closing with error code
1 parent a47cd81 commit d477972

17 files changed

+353
-101
lines changed

CHANGELOG.md

+12
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,18 @@ Code v99.99.999
2020
2121
-->
2222

23+
## Unreleased
24+
25+
Code v1.75.1
26+
27+
### Security
28+
29+
Add an origin check to web sockets to prevent a cross-site hijacking attack that
30+
affects those who use older or niche browsers that do not support SameSite
31+
cookies and those who access code-server under a shared domain with other users
32+
on separate sub-domains. The check requires the host header to be set so if you
33+
use a reverse proxy ensure it forwards that information.
34+
2335
## [4.10.0](https://github.com/coder/code-server/releases/tag/v4.10.0) - 2023-02-15
2436

2537
Code v1.75.1

src/common/http.ts

+1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ export enum HttpCode {
44
NotFound = 404,
55
BadRequest = 400,
66
Unauthorized = 401,
7+
Forbidden = 403,
78
LargePayload = 413,
89
ServerError = 500,
910
}

src/node/cli.ts

+9-14
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,15 @@ import { promises as fs } from "fs"
33
import { load } from "js-yaml"
44
import * as os from "os"
55
import * as path from "path"
6-
import { canConnect, generateCertificate, generatePassword, humanPath, paths, isNodeJSErrnoException } from "./util"
6+
import {
7+
canConnect,
8+
generateCertificate,
9+
generatePassword,
10+
humanPath,
11+
paths,
12+
isNodeJSErrnoException,
13+
splitOnFirstEquals,
14+
} from "./util"
715

816
const DEFAULT_SOCKET_PATH = path.join(os.tmpdir(), "vscode-ipc")
917

@@ -292,19 +300,6 @@ export const optionDescriptions = (opts: Partial<Options<Required<UserProvidedAr
292300
})
293301
}
294302

295-
export function splitOnFirstEquals(str: string): string[] {
296-
// we use regex instead of "=" to ensure we split at the first
297-
// "=" and return the following substring with it
298-
// important for the hashed-password which looks like this
299-
// $argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY
300-
// 2 means return two items
301-
// Source: https://stackoverflow.com/a/4607799/3015595
302-
// We use the ? to say the the substr after the = is optional
303-
const split = str.split(/=(.+)?/, 2)
304-
305-
return split
306-
}
307-
308303
/**
309304
* Parse arguments into UserProvidedArgs. This should not go beyond checking
310305
* that arguments are valid types and have values when required.

src/node/http.ts

+74-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,15 @@ import { version as codeServerVersion } from "./constants"
1212
import { Heart } from "./heart"
1313
import { CoderSettings, SettingsProvider } from "./settings"
1414
import { UpdateProvider } from "./update"
15-
import { getPasswordMethod, IsCookieValidArgs, isCookieValid, sanitizeString, escapeHtml, escapeJSON } from "./util"
15+
import {
16+
getPasswordMethod,
17+
IsCookieValidArgs,
18+
isCookieValid,
19+
sanitizeString,
20+
escapeHtml,
21+
escapeJSON,
22+
splitOnFirstEquals,
23+
} from "./util"
1624

1725
/**
1826
* Base options included on every page.
@@ -308,3 +316,68 @@ export const getCookieOptions = (req: express.Request): express.CookieOptions =>
308316
export const self = (req: express.Request): string => {
309317
return normalize(`${req.baseUrl}${req.originalUrl.endsWith("/") ? "/" : ""}`, true)
310318
}
319+
320+
function getFirstHeader(req: http.IncomingMessage, headerName: string): string | undefined {
321+
const val = req.headers[headerName]
322+
return Array.isArray(val) ? val[0] : val
323+
}
324+
325+
/**
326+
* Throw an error if origin checks fail. Call `next` if provided.
327+
*/
328+
export function ensureOrigin(req: express.Request, _?: express.Response, next?: express.NextFunction): void {
329+
if (!authenticateOrigin(req)) {
330+
throw new HttpError("Forbidden", HttpCode.Forbidden)
331+
}
332+
if (next) {
333+
next()
334+
}
335+
}
336+
337+
/**
338+
* Authenticate the request origin against the host.
339+
*/
340+
export function authenticateOrigin(req: express.Request): boolean {
341+
// A missing origin probably means the source is non-browser. Not sure we
342+
// have a use case for this but let it through.
343+
const originRaw = getFirstHeader(req, "origin")
344+
if (!originRaw) {
345+
return true
346+
}
347+
348+
let origin: string
349+
try {
350+
origin = new URL(originRaw).host.trim().toLowerCase()
351+
} catch (error) {
352+
return false // Malformed URL.
353+
}
354+
355+
// Honor Forwarded if present.
356+
const forwardedRaw = getFirstHeader(req, "forwarded")
357+
if (forwardedRaw) {
358+
const parts = forwardedRaw.split(/[;,]/)
359+
for (let i = 0; i < parts.length; ++i) {
360+
const [key, value] = splitOnFirstEquals(parts[i])
361+
if (key.trim().toLowerCase() === "host" && value) {
362+
return origin === value.trim().toLowerCase()
363+
}
364+
}
365+
}
366+
367+
// Honor X-Forwarded-Host if present.
368+
const xHost = getFirstHeader(req, "x-forwarded-host")
369+
if (xHost) {
370+
return origin === xHost.trim().toLowerCase()
371+
}
372+
373+
// A missing host likely means the reverse proxy has not been configured to
374+
// forward the host which means we cannot perform the check. Emit a warning
375+
// so an admin can fix the issue.
376+
const host = getFirstHeader(req, "host")
377+
if (!host) {
378+
logger.warn(`no host headers found; blocking request to ${req.originalUrl}`)
379+
return false
380+
}
381+
382+
return origin === host.trim().toLowerCase()
383+
}

src/node/routes/domainProxy.ts

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Request, Router } from "express"
22
import { HttpCode, HttpError } from "../../common/http"
3-
import { authenticated, ensureAuthenticated, redirect, self } from "../http"
3+
import { authenticated, ensureAuthenticated, ensureOrigin, redirect, self } from "../http"
44
import { proxy } from "../proxy"
55
import { Router as WsRouter } from "../wsRouter"
66

@@ -78,10 +78,8 @@ wsRouter.ws("*", async (req, _, next) => {
7878
if (!port) {
7979
return next()
8080
}
81-
82-
// Must be authenticated to use the proxy.
81+
ensureOrigin(req)
8382
await ensureAuthenticated(req)
84-
8583
proxy.ws(req, req.ws, req.head, {
8684
ignorePath: true,
8785
target: `http://0.0.0.0:${port}${req.originalUrl}`,

src/node/routes/errors.ts

+7-1
Original file line numberDiff line numberDiff line change
@@ -63,5 +63,11 @@ export const errorHandler: express.ErrorRequestHandler = async (err, req, res, n
6363

6464
export const wsErrorHandler: express.ErrorRequestHandler = async (err, req, res, next) => {
6565
logger.error(`${err.message} ${err.stack}`)
66-
;(req as WebsocketRequest).ws.end()
66+
let statusCode = 500
67+
if (errorHasStatusCode(err)) {
68+
statusCode = err.statusCode
69+
} else if (errorHasCode(err) && notFoundCodes.includes(err.code)) {
70+
statusCode = HttpCode.NotFound
71+
}
72+
;(req as WebsocketRequest).ws.end(`HTTP/1.1 ${statusCode} ${err.message}\r\n\r\n`)
6773
}

src/node/routes/pathProxy.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import * as path from "path"
33
import * as qs from "qs"
44
import * as pluginapi from "../../../typings/pluginapi"
55
import { HttpCode, HttpError } from "../../common/http"
6-
import { authenticated, ensureAuthenticated, redirect, self } from "../http"
6+
import { authenticated, ensureAuthenticated, ensureOrigin, redirect, self } from "../http"
77
import { proxy as _proxy } from "../proxy"
88

99
const getProxyTarget = (req: Request, passthroughPath?: boolean): string => {
@@ -50,6 +50,7 @@ export async function wsProxy(
5050
passthroughPath?: boolean
5151
},
5252
): Promise<void> {
53+
ensureOrigin(req)
5354
await ensureAuthenticated(req)
5455
_proxy.ws(req, req.ws, req.head, {
5556
ignorePath: true,

src/node/routes/vscode.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { WebsocketRequest } from "../../../typings/pluginapi"
77
import { logError } from "../../common/util"
88
import { CodeArgs, toCodeArgs } from "../cli"
99
import { isDevMode } from "../constants"
10-
import { authenticated, ensureAuthenticated, redirect, replaceTemplates, self } from "../http"
10+
import { authenticated, ensureAuthenticated, ensureOrigin, redirect, replaceTemplates, self } from "../http"
1111
import { SocketProxyProvider } from "../socket"
1212
import { isFile, loadAMDModule } from "../util"
1313
import { Router as WsRouter } from "../wsRouter"
@@ -173,7 +173,7 @@ export class CodeServerRouteWrapper {
173173
this.router.get("/", this.ensureCodeServerLoaded, this.$root)
174174
this.router.get("/manifest.json", this.manifest)
175175
this.router.all("*", ensureAuthenticated, this.ensureCodeServerLoaded, this.$proxyRequest)
176-
this._wsRouterWrapper.ws("*", ensureAuthenticated, this.ensureCodeServerLoaded, this.$proxyWebsocket)
176+
this._wsRouterWrapper.ws("*", ensureOrigin, ensureAuthenticated, this.ensureCodeServerLoaded, this.$proxyWebsocket)
177177
}
178178

179179
dispose() {

src/node/util.ts

+10
Original file line numberDiff line numberDiff line change
@@ -541,3 +541,13 @@ export const loadAMDModule = async <T>(amdPath: string, exportName: string): Pro
541541

542542
return module[exportName] as T
543543
}
544+
545+
/**
546+
* Split a string on the first equals. The result will always be an array with
547+
* two items regardless of how many equals there are. The second item will be
548+
* undefined if empty or missing.
549+
*/
550+
export function splitOnFirstEquals(str: string): [string, string | undefined] {
551+
const split = str.split(/=(.+)?/, 2)
552+
return [split[0], split[1]]
553+
}

src/node/wsRouter.ts

+3
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ export class WebsocketRouter {
3232
/**
3333
* Handle a websocket at this route. Note that websockets are immediately
3434
* paused when they come in.
35+
*
36+
* If the origin header exists it must match the host or the connection will
37+
* be prevented.
3538
*/
3639
public ws(route: expressCore.PathParams, ...handlers: pluginapi.WebSocketHandler[]): void {
3740
this.router.get(

test/unit/node/cli.test.ts

-26
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import {
1111
readSocketPath,
1212
setDefaults,
1313
shouldOpenInExistingInstance,
14-
splitOnFirstEquals,
1514
toCodeArgs,
1615
optionDescriptions,
1716
options,
@@ -535,31 +534,6 @@ describe("cli", () => {
535534
})
536535
})
537536

538-
describe("splitOnFirstEquals", () => {
539-
it("should split on the first equals", () => {
540-
const testStr = "enabled-proposed-api=test=value"
541-
const actual = splitOnFirstEquals(testStr)
542-
const expected = ["enabled-proposed-api", "test=value"]
543-
expect(actual).toEqual(expect.arrayContaining(expected))
544-
})
545-
it("should split on first equals regardless of multiple equals signs", () => {
546-
const testStr =
547-
"hashed-password=$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY"
548-
const actual = splitOnFirstEquals(testStr)
549-
const expected = [
550-
"hashed-password",
551-
"$argon2i$v=19$m=4096,t=3,p=1$0qR/o+0t00hsbJFQCKSfdQ$oFcM4rL6o+B7oxpuA4qlXubypbBPsf+8L531U7P9HYY",
552-
]
553-
expect(actual).toEqual(expect.arrayContaining(expected))
554-
})
555-
it("should always return the first element before an equals", () => {
556-
const testStr = "auth="
557-
const actual = splitOnFirstEquals(testStr)
558-
const expected = ["auth"]
559-
expect(actual).toEqual(expect.arrayContaining(expected))
560-
})
561-
})
562-
563537
describe("shouldSpawnCliProcess", () => {
564538
it("should return false if no 'extension' related args passed in", async () => {
565539
const args = {}

0 commit comments

Comments
 (0)