Arbitrary package tampering in Deno registry + Code Injection in encoding/yaml
blog.ryotak.net
Published on blog.ryotak.net
2021-11-30 1116 字 Deno Vulnerability TypeScript Supply Chain
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
Deno is a runtime for JavaScript and TypeScript built on V8 and Rust. Around it sits an ecosystem of separate projects: the runtime itself (denoland/deno), the Deno standard library (denoland/deno_std), and the code behind deno.land/x (denoland/deno_registry2).
deno.land/x hosts Deno modules and supports automatic updates driven by GitHub releases. The service supports automatic updates driven by GitHub releases, uploading repository files to S3; uploaded files are stored with public-read. Because uploading an entire repository would include extra files and inflate the size, the service exposes a subdir parameter that selects the directory to upload.
Two separate issues are described here: a code injection in the standard library's YAML parser (encoding/yaml), and a path traversal in the subdir parameter of deno.land/x that could lead to arbitrary package tampering.
A note on scope: Deno Land Inc. does not run a bug bounty programme and does not explicitly authorise vulnerability assessments. The findings were reported as potential vulnerabilities and were not actually exploited or demonstrated. The author also notes that some information could not be validated and may be inaccurate.
Setup
The investigation was limited to three repositories, because there was not enough time to cover every Deno-related project:
denoland/deno: the Deno runtimedenoland/deno_std: the Deno standard modulesdenoland/deno_registry2: the code of deno.land/x
No accounts, roles or special tooling are described. The work was source code review of those repositories. A vulnerability in the runtime itself was already a known issue and is not covered in the article.
Finding it
The starting point was the claim on Deno's official website that Deno is "a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust". That prompted a look at how secure it actually is. Quick investigations across the three repositories turned up issues in the runtime, the standard modules and the registry code.
Exploitation
Step 1: reach the extended YAML schema
The standard library ships a YAML parser at encoding/yaml. It includes an extended schema, EXTENDED_SCHEMA, which is not loaded by default. A caller opts in by passing it as the schema option:
import {
EXTENDED_SCHEMA,
parse,
} from "https://deno.land/std@$STD_VERSION/encoding/yaml.ts";
const data = parse(
`
regexp:
simple: !!js/regexp foobar
modifiers: !!js/regexp /foobar/mi
undefined: !!js/undefined ~
function: !!js/function >
function foobar() {
return 'hello world!';
}
`,
{ schema: EXTENDED_SCHEMA },
);
With this schema, YAML documents can embed regular expressions, undefined values and JavaScript functions. The !!js/function tag is the interesting one: the document supplies JavaScript source that the parser turns into a callable.
Step 2: inject code through a function tag
The function reconstruction in the parser looked like this:
function reconstructFunction(code: string) {
const func = new Function(`return ${code}`)();
if (!(func instanceof Function)) {
throw new TypeError(`Expected function but got ${typeof func}: ${code}`);
}
return func;
}
The code argument comes straight from the YAML document and is interpolated into a new Function body. Writing simple JavaScript as the value of a !!js/function node therefore executes arbitrary code as soon as the document is parsed.
This is CVE-2021-42139. It was fixed by removing support for JavaScript functions from EXTENDED_SCHEMA.
Step 3: follow the subdir parameter into the filesystem
In deno.land/x, the subdir parameter is concatenated onto clonePath without any changes until this code:
const path = (subdir === undefined ? clonePath : join(
clonePath,
subdir.replace(
/(^\/|\/$)/g,
"",
),
));
The only transformation is stripping a leading or trailing slash. No normalisation or containment check is applied, so .. segments survive into path.
Step 4: enumerate everything under the resolved path
The resulting path is walked, and every entry is recorded in a directory array:
const entries = [];
for await (
const entry of walk(path, {
includeFiles: true,
includeDirs: true,
})
) {
entries.push(entry);
}
console.log("Total files in repo", entries.length);
const directory: DirectoryListingFile[] = [];
await collectAsyncIterable(pooledMap(100, entries, async (entry) => {
const filename = entry.path.substring(path.length);
if (filename.startsWith("/.git/") || filename === "/.git") return;
if (entry.isFile) {
const stat = await Deno.stat(entry.path);
directory.push({ path: filename, size: stat.size, type: "file" });
} else {
directory.push({ path: filename, size: undefined, type: "dir" });
}
}));
Every file and directory below path is collected, with .git entries skipped. The relative filename is derived by cutting off the prefix path.length.
Step 5: upload the collected files to S3
Each file entry is then opened and uploaded:
await collectAsyncIterable(pooledMap(65, directory, async (entry) => {
if (entry.type === "file") {
const file = await Deno.open(join(path, entry.path));
const body = await Deno.readAll(file);
await uploadVersionRaw(
moduleName,
version,
entry.path,
body,
);
file.close();
}
}));
For every entry of type file, the contents are read and passed to uploadVersionRaw, which stores them in S3 with public-read.
Step 6: read environment variables and take over packages
Because path is not confined to the cloned repository, a subdir value such as ../../../../../../../etc causes all files under /etc to be uploaded. The author notes that this process will likely be interrupted by problems such as permissions, but files uploaded up to that point remain on S3 as they are.
Pointing subdir at ../../../../../../../proc/self reaches /proc/self/environ, which contains all environment variables, including the AWS credentials. Those credentials have access to the S3 buckets used to store modules, so an attacker could tamper with arbitrary packages in deno.land/x.
Root cause
The registry trusted a user-supplied path fragment. subdir was joined onto clonePath with only leading and trailing slashes removed, so traversal sequences were preserved and the walk and upload logic operated outside the intended directory. The upload step stored whatever it found in S3 with public-read, and the credentials in the environment gave access to the module buckets.
In encoding/yaml, the extended schema accepted JavaScript source from the document and passed it to new Function. The type check on the result came after execution, so it offered no protection.
Impact
On deno.land/x, an attacker could read arbitrary files from the system running the service. Pointing subdir at /proc/self reaches /proc/self/environ, which contains the AWS credentials; those credentials have access to the S3 buckets that store modules. which makes arbitrary package tampering in deno.land/x possible. That matters because deno.land/x hosts many modules, including Deno's install script, and is a central part of the Deno ecosystem.
In encoding/yaml, a malicious YAML document could execute arbitrary code once parsed, but only when the caller explicitly opts into EXTENDED_SCHEMA.
After the registry fix, the Deno development team investigated the access log of the AWS credentials and confirmed that the vulnerability was not exploited in the wild.
Fix
The YAML code injection was fixed by removing support for JavaScript functions from EXTENDED_SCHEMA. The registry path traversal was fixed by normalising the subdir parameter.
Variants to test
- Other path parameters joined onto a base directory. Look for parameters like
subdir,path,dirorfolderthat are concatenated onto a clone or upload root. A positive result is a value containing..segments that causes files outside the intended directory to be listed or uploaded. - Sanitisers that only strip slashes. The registry removed leading and trailing slashes but did not normalise. Try values with interior
..segments, mixed separators and encoded traversal to see whether the resolved path escapes the base. - Upload sinks that publish with public read. Wherever collected files are pushed to object storage, check the ACL. A positive result is content from outside the intended tree appearing at a public URL.
- Credential exposure through
/proc/self/environ. On Linux services that read files from disk, check whether the process environment is reachable. A positive result is environment variables, including cloud credentials, appearing in output or storage. - Deserialisers with opt-in extended schemas. Look for YAML or similar parsers where an extended schema enables function, regex or type tags. A positive result is a document that causes code to run during parsing when the extended schema is selected.
- Constructors that evaluate input. Search for
new Function,evaland similar calls where the argument is derived from parsed data. A positive result is execution of attacker-controlled source before any validation of the result.
Timeline
| Date (JST) | Event |
|---|---|
| September 13, 2021 | Found vulnerabilities |
| September 14, 2021 | Reported vulnerabilities |
| September 14, 2021 | Vulnerabilities fixed |
| September 15, 2021 | Checked if I can disclose details of vulnerabilities |
| October 7, 2021 | Disclose approved |
| November 30, 2021 | Published this article |
What happened, in plain words
Deno is a piece of software that runs JavaScript and TypeScript programs. Around it there is a whole ecosystem of separate projects: the runtime itself, a collection of ready-made modules called the standard library, and a website called deno.land/x that hosts modules other people have written so anyone can download and use them.
Two separate problems were found in that ecosystem. The first was in a YAML parser that ships with the standard library: a specially crafted YAML document could make the parser run JavaScript code written by whoever supplied the document. The second was in deno.land/x: a parameter called subdir, meant to say which folder of a repository to upload, could be pointed outside the repository. That made it possible to read files from the server running the service, including a file that holds the server's environment variables. Those variables contained AWS credentials, and those credentials had access to the S3 buckets used to store modules, so arbitrary packages in deno.land/x could be tampered with.
A few things to know before reading on. Deno Land Inc. the company behind Deno, does not run a bug bounty programme, so it does not explicitly allow people to test its services for vulnerabilities. The author reported these findings as potential vulnerabilities and did not actually exploit or demonstrate them. The author also warns that some details could not be validated and may be inaccurate. If you find a problem in a Deno-related service or product, the article asks you to report it to [redacted]
Background: the pieces involved
Before the findings, here is what each piece is, in everyday terms.
- A runtime is the program that reads your code and actually executes it. A browser is a runtime for web pages; Deno is a runtime for JavaScript and TypeScript programs run outside the browser.
- TypeScript is JavaScript with optional type annotations, which help catch mistakes before the program runs.
- V8 is the JavaScript engine, the component that turns JavaScript into something the computer can execute. Rust is a programming language known for safety and speed. Deno is built on both.
- A module is a reusable chunk of code that other programs can import, like a recipe you borrow from a cookbook instead of writing yourself.
- A repository is a project's folder of source code, usually hosted on a service like GitHub, with a history of every change.
- A release is a labelled version of a project that its authors publish, for example version 1.2.0.
- S3 is Amazon's cloud file storage: you put files in named containers called buckets and can make them readable by anyone on the internet.
- A YAML parser is a program that reads YAML, a human-friendly text format for structured data (indentation instead of brackets), and turns it into objects a program can use.
- A schema in a parser is a set of rules for which special tags and data types are allowed. A parser can ship a stricter default schema and an extended one you must switch on yourself.
- Code injection means tricking a program into running code that the person who wrote the program never intended to run.
- Path traversal means using
..(which in file paths means "go up one folder") to escape the folder a program meant you to stay in. - Environment variables are named values a running program inherits from the system, often used to pass in configuration and secrets such as cloud credentials.
- Credentials are the username-and-key equivalent for a program: proof of identity that lets it access a service.
public-readis an access setting on stored files that lets anyone on the internet download them.
Why the investigation started
Deno's official website describes it as Deno is a simple, modern and secure runtime for JavaScript and TypeScript that uses V8 and is built in Rust. The word "secure" made the author curious about how secure it really is, so the decision was to look at the code.
What was in scope
There was not enough time to examine every Deno-related project, so the review was limited to three repositories:
denoland/deno: the Deno runtimedenoland/deno_std: the Deno standard modulesdenoland/deno_registry2: the code of deno.land/x
This was source code review: reading the code, not running attacks against live systems. No accounts, roles or special tools are described. A vulnerability in the runtime itself was already a known issue, so the article does not explain it; the other two findings are covered below.
Finding 1: code injection in the YAML parser
The standard library contains a YAML parser at encoding/yaml. It has an extended schema called EXTENDED_SCHEMA that is not loaded by default. A program that wants the extra features has to ask for it explicitly by passing it as the schema option, as in this example from the article:
import {
EXTENDED_SCHEMA,
parse,
} from "https://deno.land/std@$STD_VERSION/encoding/yaml.ts";
const data = parse(
`
regexp:
simple: !!js/regexp foobar
modifiers: !!js/regexp /foobar/mi
undefined: !!js/undefined ~
function: !!js/function >
function foobar() {
return 'hello world!';
}
`,
{ schema: EXTENDED_SCHEMA },
);
Line by line:
import { EXTENDED_SCHEMA, parse } from "https://deno.land/std@$STD_VERSION/encoding/yaml.ts";loads two things from the standard library's YAML file: the extended schema and theparsefunction.$STD_VERSIONis a placeholder for a version number.const data = parse(starts a call to the parser and stores the result indata.- The backtick block is the YAML document itself. Inside it,
!!js/regexpmarks a value as a regular expression (a pattern for matching text),!!js/undefinedmarks a value as undefined (no value at all), and!!js/functionmarks a value as a JavaScript function. - Under
function:, the>symbol means the following indented lines are one block of text, and that text is JavaScript source: a function calledfoobarthat returns the string'hello world!'. { schema: EXTENDED_SCHEMA }is the option that switches on the extended schema, which is what makes those!!js/...tags meaningful.
With this schema, a YAML document can carry regular expressions, undefined values and JavaScript functions. The function tag is the dangerous one: the document supplies JavaScript source, and the parser turns it into a callable function.
The code that did that conversion looked like this:
function reconstructFunction(code: string) {
const func = new Function(`return ${code}`)();
if (!(func instanceof Function)) {
throw new TypeError(`Expected function but got ${typeof func}: ${code}`);
}
return func;
}
Line by line:
function reconstructFunction(code: string) {defines a function that takes a piece of text calledcode.const func = new Function(return ${code})();builds a brand-new function from a string. The string is the wordreturnfollowed by whatevercodecontains, and the trailing()immediately calls the result.new Functionis JavaScript's way of turning text into executable code at runtime, which is exactly what makes this dangerous: ifcodeis attacker-supplied, the attacker's code runs.if (!(func instanceof Function)) {checks whether the result is actually a function.throw new TypeError(...)raises an error if it is not, including the offending text in the message.return func;hands the function back to the caller.
The code argument comes straight from the YAML document and is pasted into the body of new Function. So writing simple JavaScript as the value of a !!js/function node executes that code as soon as the document is parsed.
This issue is tracked as CVE-2021-42139. It was fixed by removing support for JavaScript functions from EXTENDED_SCHEMA.
Finding 2: reading files through the subdir parameter
deno.land/x hosts Deno modules and can update them automatically when a new GitHub release appears. When a release is published, the service copies the files of the repository into S3 and serves them with public-read, so anyone can download them. Uploading an entire repository would include extra files and make the stored size bigger, so the service offers a subdir parameter that says which folder to upload.
That parameter was appended to a base path without being properly cleaned, which made it possible to read arbitrary files on the system running the service.
The subdir value is joined onto clonePath (the folder where the repository was cloned) and stays unchanged until this code:
const path = (subdir === undefined ? clonePath : join(
clonePath,
subdir.replace(
/(^\/|\/$)/g,
"",
),
));
Line by line:
const path = (starts computing the folder to work with.subdir === undefined ? clonePath : ...means: if nosubdirwas given, just useclonePath.- Otherwise,
join(clonePath, ...)gluesclonePathand the cleanedsubdirtogether into one path. subdir.replace(/(^\/|\/$)/g, "")removes a slash at the very start or the very end ofsubdir. That is the only cleaning applied.
No normalisation or containment check happens, so .. segments inside subdir survive into path. In file paths, .. means "the folder above this one", so a value full of .. can climb out of the cloned repository.
The resulting path is then walked, and every entry found is recorded in an array called directory:
const entries = [];
for await (
const entry of walk(path, {
includeFiles: true,
includeDirs: true,
})
) {
entries.push(entry);
}
console.log("Total files in repo", entries.length);
const directory: DirectoryListingFile[] = [];
await collectAsyncIterable(pooledMap(100, entries, async (entry) => {
const filename = entry.path.substring(path.length);
if (filename.startsWith("/.git/") || filename === "/.git") return;
if (entry.isFile) {
const stat = await Deno.stat(entry.path);
directory.push({ path: filename, size: stat.size, type: "file" });
} else {
directory.push({ path: filename, size: undefined, type: "dir" });
}
}));
Line by line:
const entries = [];creates an empty list to hold everything found.for await (const entry of walk(path, { includeFiles: true, includeDirs: true }))walks the folderpathand visits every file and every folder inside it.entries.push(entry);adds each visited item to the list.console.log("Total files in repo", entries.length);prints how many items were found.const directory: DirectoryListingFile[] = [];creates a second, empty list for the cleaned-up descriptions.pooledMap(100, entries, async (entry) => { ... })processes the entries, up to 100 at a time, running the inner function for each one.const filename = entry.path.substring(path.length);cuts off the firstpath.lengthcharacters, leaving the path relative to the starting folder.if (filename.startsWith("/.git/") || filename === "/.git") return;skips Git's internal bookkeeping folder.- If the entry is a file,
Deno.statreads its size and a{ path, size, type: "file" }record is added; otherwise a{ path, size: undefined, type: "dir" }record is added.
So every file and folder below path is collected, with .git skipped, and each one is described by its relative name, its size and whether it is a file or a folder.
Each file entry is then opened and uploaded:
await collectAsyncIterable(pooledMap(65, directory, async (entry) => {
if (entry.type === "file") {
const file = await Deno.open(join(path, entry.path));
const body = await Deno.readAll(file);
await uploadVersionRaw(
moduleName,
version,
entry.path,
body,
);
file.close();
}
}));
Line by line:
pooledMap(65, directory, ...)goes through the collected entries, up to 65 at a time.if (entry.type === "file")ignores folders and only handles files.Deno.open(join(path, entry.path))opens the file at its full location.Deno.readAll(file)reads the whole contents intobody.uploadVersionRaw(moduleName, version, entry.path, body)sends the contents to storage under the module name and version, with the relative path as the file name.file.close();closes the file.
uploadVersionRaw stores the contents in S3 with public-read, so whatever was read becomes downloadable by anyone.
Because path is not confined to the cloned repository, a subdir value such as ../../../../../../../etc makes all files under /etc get uploaded. The author notes that this process will probably be interrupted by problems such as permissions, but files uploaded up to that point stay on S3 as they are.
By pointing subdir at ../../../../../../../proc/self, an attacker reaches /proc/self/environ. On Linux, /proc is a special folder that exposes information about running processes, and /proc/self refers to the process doing the reading; its environ file lists all of that process's environment variables. Those variables included the AWS credentials. Those credentials had access to the S3 buckets used to store modules, so an attacker could tamper with arbitrary packages in deno.land/x.
This vulnerability was fixed by normalising the subdir parameter. After the fix, the Deno development team checked the access log of the AWS credentials and confirmed that the vulnerability was not exploited in the wild.
Why it worked
The registry trusted a piece of text supplied by the user. subdir was joined onto clonePath with only leading and trailing slashes removed, so .. sequences were kept and the walk and upload logic ended up outside the intended folder. The upload step stored whatever it found in S3 with public-read, and the credentials in the environment gave access to the module buckets.
In encoding/yaml, the extended schema accepted JavaScript source from the document and passed it to new Function. The type check on the result came after execution, so it offered no protection.
What the impact was
On deno.land/x, an attacker could read arbitrary files from the system running the service. Pointing subdir at /proc/self reaches /proc/self/environ, which contains the AWS credentials; those credentials have access to the S3 buckets that store modules. which makes arbitrary package tampering in deno.land/x possible. That matters because deno.land/x hosts many modules, including Deno's install script, and is a central part of the Deno ecosystem.
In encoding/yaml, a malicious YAML document could execute arbitrary code once parsed, but only when the caller explicitly opts into EXTENDED_SCHEMA.
How it was fixed
The YAML code injection was fixed by removing support for JavaScript functions from EXTENDED_SCHEMA. The registry path traversal was fixed by normalising the subdir parameter.
Similar things to look for
- Other path parameters joined onto a base folder. Look for parameters like
subdir,path,dirorfolderthat are glued onto a clone or upload root. A positive result is a value containing..segments that causes files outside the intended folder to be listed or uploaded. - Cleaners that only strip slashes. The registry removed leading and trailing slashes but did not normalise. Try values with
..in the middle, mixed separators and encoded traversal to see whether the resolved path escapes the base. - Upload steps that publish with public read. Wherever collected files are pushed to object storage, check the access setting. A positive result is content from outside the intended tree appearing at a public URL.
- Credential exposure through
/proc/self/environ. On Linux services that read files from disk, check whether the process environment is reachable. A positive result is environment variables, including cloud credentials, appearing in output or storage. - Parsers with opt-in extended schemas. Look for YAML or similar parsers where an extended schema enables function, regex or type tags. A positive result is a document that causes code to run during parsing when the extended schema is selected.
- Constructors that evaluate input. Search for
new Function,evaland similar calls where the argument comes from parsed data. A positive result is execution of attacker-controlled source before any validation of the result.
Timeline
| Date (JST) | Event |
|---|---|
| September 13, 2021 | Found vulnerabilities |
| September 14, 2021 | Reported vulnerabilities |
| September 14, 2021 | Vulnerabilities fixed |
| September 15, 2021 | Checked if I can disclose details of vulnerabilities |
| October 7, 2021 | Disclose approved |
| November 30, 2021 | Published this article |
Glossary
- Runtime: the program that reads code and executes it; Deno is a runtime for JavaScript and TypeScript.
- TypeScript: JavaScript with optional type annotations that help catch mistakes before running.
- V8: the JavaScript engine that turns JavaScript into something the computer can execute.
- Rust: a programming language known for safety and speed; Deno is built on it.
- Module: a reusable chunk of code that other programs can import.
- Repository: a project's folder of source code, usually with a full history of changes.
- Release: a labelled version of a project that its authors publish.
- S3: Amazon's cloud file storage, organised into buckets.
- Bucket: a named container in S3 that holds files.
- YAML: a human-friendly text format for structured data, using indentation instead of brackets.
- Parser: a program that reads a text format and turns it into objects a program can use.
- Schema: a set of rules for which special tags and data types a parser accepts.
- Extended schema: an optional, more permissive set of parser rules that must be switched on explicitly.
- Code injection: tricking a program into running code its authors never intended.
- Path traversal: using
..in a file path to escape the folder a program meant you to stay in. ..: in a file path, the folder one level above the current one./etc: on Linux, the folder that holds system configuration files./proc: on Linux, a special folder that exposes information about running processes./proc/self: inside/proc, a shortcut to the process doing the reading./proc/self/environ: a file listing all environment variables of the current process.- Environment variables: named values a running program inherits from the system, often used for configuration and secrets.
- Credentials: proof of identity that lets a program access a service, such as a cloud key.
public-read: an access setting that lets anyone on the internet download a stored file.new Function: a JavaScript feature that turns text into an executable function at runtime.- Regular expression: a pattern for matching text.
- CVE: a public identifier assigned to a known vulnerability, here CVE-2021-42139.
- Bug bounty programme: a scheme where a company pays people for reporting vulnerabilities; Deno Land Inc. does not run one.
- Normalisation: cleaning a file path so that
..and similar segments are resolved before the path is used. - Access log: a record of who used a credential and when, used here to check for abuse.