Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
10 changes: 10 additions & 0 deletions .changeset/external-targets.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"javascript-excel": minor
---

`read`, `inspect` and `importDataset` now report relationships to targets outside the file (JSE-85), failing closed. Every relationship in any relationships part of the package (root, workbook, sheets, drawings, charts, external links, any other) that is not a hyperlink and that is external (`TargetMode="External"`, any letter case), whatever its kind, gives one `UNSUPPORTED_PART` warning with the new `partKind` `'externalTarget'`. Example: a linked picture, an `image` relationship of a drawing with an `http(s)`, UNC (`\\host\share\…`) or `file:` target, which Excel fetches when the file is opened (a tracking beacon; a UNC target can send the user's NTLM credentials to that host). Before, nothing reported it. Relationships already reported as another kind are reported here too: a linked OLE object gives `'oleObject'` and `'externalTarget'`, an external link `'externalLink'` and, for its path, `'externalTarget'`. Also reported, while the model still reads the target as a part name as before:
- a `TargetMode` that is neither `Internal` nor `External` (`" External"`, `"1"`, `""`, …);
- a second, namespace-prefixed or differently cased `TargetMode`;
- an internal target, or a second, prefixed or differently cased `Target` attribute, that starts with a URI scheme (after leading whitespace) or `//`, or contains a backslash.

Hyperlinks are never reported. The warning's `part` is the first relationships part that holds one, `parts` lists every such relationships part once (bounded by `maxEntries`), and the new `relationshipTypes` field gives the first 16 distinct relationship types, excerpted. Targets are never included, resolved or fetched, and any number of such relationships is one warning. No new refusals: files that read in 2.5.0 still read, with at most this one more warning. `ExcelPartKind` gains `'externalTarget'` (a `switch` over it needs a `default` branch, as documented) and `ExcelWarning` gains the optional `relationshipTypes`. Files this library writes have none: their hyperlinks are not reported.
15 changes: 11 additions & 4 deletions docs/api.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/javascript-excel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ const cell = exact.workbook.sheets[0]?.rows[0]?.[0];
console.log(cell?.type, cell?.value, cell?.rawText); // "number" 50.3 "50.30"
```

Damage the reader can recover from comes back as `warnings`. `isDataLossWarning(w)` tells the ones where data was lost (a cell skipped, rows cut, a part missing, comments or charts not read; `partKind` names the part, including ActiveX controls, embedded files, customUI, web add-ins and parts no relationship reaches, wherever they sit in the package) from informational ones; the warning cap (`limits.maxWarnings`, default 1,000) drops only informational warnings, so filtering `warnings` with it is enough to refuse a damaged file.
Damage the reader can recover from comes back as `warnings`. `isDataLossWarning(w)` tells the ones where data was lost (a cell skipped, rows cut, a part missing, comments or charts not read; `partKind` names the part, including ActiveX controls, embedded files, customUI, web add-ins, parts no relationship reaches and relationships to targets outside the file such as linked pictures, wherever they sit in the package) from informational ones; the warning cap (`limits.maxWarnings`, default 1,000) drops only informational warnings, so filtering `warnings` with it is enough to refuse a damaged file.

To accept or refuse an upload without reading it into the model, `inspect(file, { limits, signal })` checks it part by part without building cells: it refuses every file `read` refuses under the same limits, with the same error, and returns the format, the worksheets with their cell counts, and the part kinds `read` reports (`partKinds`: VBA, external links, OLE objects, …). It also inflates the parts `read` never opens, searches the bytes of every one of them for `<!DOCTYPE` (ASCII-compatible, UTF-16 and UTF-32 forms, whatever the part's name; a declaration inside an XML comment or in an embedded file is refused too), and refuses XML parts whose byte order mark, first bytes or complete declaration show an encoding other than UTF-8 or UTF-16, or whose declaration is malformed or not at the very start. Set `limits.maxItems` (for example 100,000): it bounds the styles and defined names `inspect` still holds, and the shared-formula masters and reference records it keeps. See [docs/api.md §5.2.1](https://github.com/securedeveloper/javascript-excel/blob/main/docs/api.md#521-inspect-inspect-added-in-25).

Expand Down
3 changes: 2 additions & 1 deletion packages/javascript-excel/src/internal/read/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,14 @@ export class ReadContext {
* dropped warning adds WARNINGS_TRUNCATED at that point, as in 2.0.0; its
* `dropped` counts grow until the read ends.
*/
warn(code: ExcelWarningCode, message: string, where?: { part?: string; sheet?: string; ref?: string; partKind?: ExcelPartKind; parts?: string[] }): void {
warn(code: ExcelWarningCode, message: string, where?: { part?: string; sheet?: string; ref?: string; partKind?: ExcelPartKind; parts?: string[]; relationshipTypes?: string[] }): void {
const w: ExcelWarning = { code, message };
if (where?.part !== undefined) w.part = where.part;
if (where?.sheet !== undefined) w.sheet = where.sheet;
if (where?.ref !== undefined) w.ref = where.ref;
if (where?.partKind !== undefined) w.partKind = where.partKind;
if (where?.parts !== undefined) w.parts = where.parts;
if (where?.relationshipTypes !== undefined) w.relationshipTypes = where.relationshipTypes;
this.tap?.(w);
const kept = this.cap.add(w, (dropped) => {
const t: ExcelWarning = { code: "WARNINGS_TRUNCATED", message: `More than maxWarnings (${this.limits.maxWarnings}) warnings; later ones were dropped.`, dropped };
Expand Down
40 changes: 40 additions & 0 deletions packages/javascript-excel/src/internal/read/opc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,45 @@ export interface Relationship {
*/
tooLong?: boolean;
external: boolean;
/**
* Read as internal, but it may point outside the package (JSE-85): its
* TargetMode is neither `Internal` nor `External` (in any case, not
* trimmed); there is a second, prefixed or differently cased TargetMode
* attribute; or the target, or any other Target-named attribute, starts
* with a URI scheme or `//` or contains a backslash. The model still reads
* the target as a part name; the package scan reports it as an external
* target.
*/
outside?: boolean;
}

/** A URI scheme (RFC 3986) at the start, after spaces; a network-path reference (`//`); or a backslash anywhere. */
export function pointsOutside(target: string): boolean {
if (target.includes("\\")) return true;
const t = target.trimStart();
return t.startsWith("//") || /^[A-Za-z][A-Za-z0-9+.-]*:/.test(t);
}

/**
* Whether the attributes of a `<Relationship>` read as internal may name a
* target outside the package (Relationship.outside). One pass over the
* attributes as written (duplicates included), linear in the tag.
*/
function outsideByAttributes(a: XmlAttrs): boolean {
let modes = 0;
for (const [q, v] of a.entries()) {
const colon = q.indexOf(":");
if (q === "xmlns" || (colon > 0 && q.slice(0, colon) === "xmlns")) continue;
const len = q.length - colon - 1;
if (len !== 10 && len !== 6) continue;
const local = (colon === -1 ? q : q.slice(colon + 1)).toLowerCase();
if (local === "targetmode") {
if (q !== "TargetMode" || ++modes > 1) return true;
const mode = v.toLowerCase();
if (mode !== "internal" && mode !== "external") return true;
} else if (local === "target" && pointsOutside(v)) return true;
}
return false;
}

/**
Expand Down Expand Up @@ -227,6 +266,7 @@ export class Package {
const target = a.get("Target");
const external = (a.get("TargetMode") ?? "").toLowerCase() === "external";
const rel: Relationship = { id: id ?? "", type, kind: type.slice(type.lastIndexOf("/") + 1), target: "", external };
if (!external && outsideByAttributes(a)) rel.outside = true;
if (target === undefined) {
malformed.push(rel); // classified by its type alone
return;
Expand Down
13 changes: 12 additions & 1 deletion packages/javascript-excel/src/internal/read/reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,9 @@ export function warnUnsupportedParts(ctx: Pick<ReadContext, "checkAbort" | "warn
/**
* After the sheets (JSE-72): the kinds in REPORTED_ANYWHERE that the
* workbook's and the read sheets' relationships did not already report,
* wherever the package scan found them, then one `invalidPartName` warning
* wherever the package scan found them, then one `externalTarget` warning
* for all non-hyperlink relationships that point, or may point, outside the
* package, whatever their kind (JSE-85), one `invalidPartName` warning
* for all names OPC forbids and one `unreferencedPart` warning for all parts
* no relationship reaches, each listing every name in `parts`.
*/
Expand All @@ -203,6 +205,15 @@ async function warnScannedParts(pkg: Package, seen: Set<string>): Promise<void>
const what = SCANNED_KINDS.get(f.kind) ?? UNSUPPORTED_RELATIONSHIPS.get(f.kind)!;
ctx.warn("UNSUPPORTED_PART", `The workbook contains ${what}, which are not read.`, { part: f.part, partKind: f.kind });
}
const ext = scan.external;
if (ext.count > 0) {
const first = ext.parts[0]!;
const message =
ext.count === 1
? `The package has 1 relationship to a target outside the file (in "${excerpt(first)}"); it is not read or fetched, but Excel may fetch it when the file is opened.`
: `The package has ${ext.count} relationships to targets outside the file (in ${ext.parts.length} relationships part${ext.parts.length === 1 ? "" : "s"}; first in "${excerpt(first)}"); they are not read or fetched, but Excel may fetch them when the file is opened.`;
ctx.warn("UNSUPPORTED_PART", message, { part: first, partKind: "externalTarget", parts: ext.parts, relationshipTypes: ext.types });
}
const bad = scan.forbidden;
if (bad.length > 0) {
const first = bad[0]!;
Expand Down
52 changes: 51 additions & 1 deletion packages/javascript-excel/src/internal/read/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import { FormatError } from "../../errors";
import type { ExcelPartKind } from "../../warnings";
import { excerpt } from "../excerpt";
import { partKey, relsOwner, type Package, type Relationship } from "./opc";
import { ABORT_EVERY } from "./sheet";

Expand Down Expand Up @@ -127,6 +128,21 @@ export const REPORTED_ANYWHERE: ReadonlySet<ExcelPartKind> = new Set<ExcelPartKi
"webExtension",
]);

/**
* Hyperlink relationship types (lower case), transitional and strict: their
* external targets open only when a user follows the link, so they are not
* reported as `externalTarget` (JSE-85). Compared as whole URIs, not by last
* segment, so a made-up type ending in `/hyperlink` is reported.
*/
const HYPERLINK_TYPES: ReadonlySet<string> = new Set([
"http://schemas.openxmlformats.org/officedocument/2006/relationships/hyperlink",
"http://purl.oclc.org/ooxml/officedocument/relationships/hyperlink",
]);
const HYPERLINK_TYPE_LENGTH = Math.max(...[...HYPERLINK_TYPES].map((t) => t.length));

/** At most this many distinct relationship types are listed for external targets (each excerpted). */
export const MAX_EXTERNAL_TYPES = 16;

/** One part (or external target) of a kind the model does not represent. */
export interface ScannedPart {
kind: ExcelPartKind;
Expand Down Expand Up @@ -161,6 +177,18 @@ export interface PackageScan {
* a name, in walk order. Each is a zip entry name, listed once.
*/
forbidden: string[];
/**
* Relationships that are not hyperlinks and are external
* (TargetMode="External") or may point outside the package
* (Relationship.outside), whatever their kind, so also those reported as
* another kind (a linked OLE object, an external link's path) (JSE-85).
* `count` is how many
* there are; `parts` the relationships parts (zip entry names) that hold
* them, each once, in walk order, so at most maxEntries; `types` the first
* MAX_EXTERNAL_TYPES distinct relationship types (compared without regard
* to case), each excerpted. The targets are never kept, resolved or fetched.
*/
external: { count: number; parts: string[]; types: string[] };
}

/**
Expand Down Expand Up @@ -214,6 +242,8 @@ export async function scanPackageParts(pkg: Package): Promise<PackageScan> {
const parsed = new Set<string>();
// Sources to read, with whether what they reach counts as reached.
const queue: Array<{ source: string; counts: boolean }> = [{ source: "", counts: true }];
const external = { count: 0, parts: [] as string[], types: [] as string[] };
const externalTypes = new Set<string>();
const visit = (target: string, counts: boolean): void => {
const entry = pkg.part(target);
if (!entry) return;
Expand Down Expand Up @@ -256,11 +286,26 @@ export async function scanPackageParts(pkg: Package): Promise<PackageScan> {
const malformed = pkg.malformedRels.get(relsEntry.name) ?? [];
if (malformed.length) forbidden.add(relsEntry.name);
const all = malformed.length ? [...rels, ...malformed] : rels;
let externalHere = false;
for (let i = 0; i < all.length; i++) {
if ((i & ABORT_EVERY) === ABORT_EVERY) ctx.checkAbort();
const rel = all[i]!;
if (rel.forbidden) forbidden.add(relsEntry.name);
classify(rel, source, relsEntry.name);
if ((rel.external || rel.outside) && !isHyperlink(rel)) {
external.count++;
if (!externalHere) {
externalHere = true;
external.parts.push(relsEntry.name);
}
if (external.types.length < MAX_EXTERNAL_TYPES) {
const t = rel.type.toLowerCase();
if (!externalTypes.has(t)) {
externalTypes.add(t);
external.types.push(excerpt(rel.type));
}
}
}
if (rel.external || rel.tooLong) continue;
visit(rel.target, counts);
if (rel.altTarget !== undefined) visit(rel.altTarget, counts);
Expand Down Expand Up @@ -288,5 +333,10 @@ export async function scanPackageParts(pkg: Package): Promise<PackageScan> {
if (e.name.endsWith("/")) continue; // directory entries
if (!reached.has(pkg.keyOf(e))) unreferenced.push(e.name);
}
return { found, unreferenced, forbidden: [...forbidden] };
return { found, unreferenced, forbidden: [...forbidden], external };
}

/** A hyperlink relationship (HYPERLINK_TYPES): never reported as `externalTarget`. */
function isHyperlink(rel: Relationship): boolean {
return rel.type.length <= HYPERLINK_TYPE_LENGTH && HYPERLINK_TYPES.has(rel.type.toLowerCase());
}
23 changes: 20 additions & 3 deletions packages/javascript-excel/src/warnings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,12 @@ export type ExcelWarningCode =
* adds are named for what they are: `'activeX'` (ActiveX controls),
* `'embeddedPackage'` (embedded files), `'customUI'` (ribbon customisation),
* `'webExtension'` (Office web add-ins), `'invalidPartName'` (a part name,
* relationship target, Override PartName or relationship OPC forbids) and `'unreferencedPart'` (a part no relationship reaches). Kinds may be added in a minor
* relationship target, Override PartName or relationship OPC forbids) and `'unreferencedPart'` (a part no relationship reaches).
* `'externalTarget'` (since 2.6) is any relationship that is not a hyperlink
* and is external, or may be read as external (an odd or duplicate
* TargetMode, an internal target with a URI scheme, `//` or a backslash),
* whatever its kind, such as a linked picture Excel fetches when the file
* is opened. Kinds may be added in a minor
* release, so a `switch` over it needs a `default` branch.
*/
export type ExcelPartKind =
Expand Down Expand Up @@ -81,7 +86,9 @@ export type ExcelPartKind =
| "customUI"
| "webExtension"
| "invalidPartName"
| "unreferencedPart";
| "unreferencedPart"
// a relationship to a target outside the package (UNSUPPORTED_PART, since 2.6)
| "externalTarget";

/** What the warning cap left out; on `WARNINGS_TRUNCATED` only. */
export interface DroppedWarnings {
Expand Down Expand Up @@ -111,10 +118,20 @@ export interface ExcelWarning {
/**
* On `UNSUPPORTED_PART` with `partKind` `'unreferencedPart'` or
* `'invalidPartName'` (since 2.5): every such name, in the order found
* (`part` is the first). Each is a zip entry name, at most once, so the
* (`part` is the first). With `'externalTarget'` (since 2.6): every
* relationships part that holds such a relationship, in the order the
* package scan reads them. Each is a zip entry name, at most once, so the
* list is bounded by `maxEntries`.
*/
parts?: string[] | undefined;
/**
* On `UNSUPPORTED_PART` with `partKind` `'externalTarget'` (since 2.6): the
* relationship types of those relationships, the first 16 distinct ones
* (compared without regard to case), each as written when it is at most
* 128 characters, else its first 64, `…` and its length. Targets are never
* included.
*/
relationshipTypes?: string[] | undefined;
/**
* On `WARNINGS_TRUNCATED`: counts of the warnings that were not recorded. The
* counts are final in the returned `warnings` only. `read` calls `onWarning`
Expand Down
Loading