Skip to content

Commit 533ee1b

Browse files
committed
fix(linux): escape app metadata in desktop entries, AppStream and install.sh
Values are escaped per format (desktop entry strings, quoted Exec= with %%, XML), install.sh shell-quotes the name and fills Exec= literally, and the app id must be a reverse-DNS name: an empty id made install.sh rm -rf the whole XDG data dir.
1 parent 430ea82 commit 533ee1b

3 files changed

Lines changed: 198 additions & 31 deletions

File tree

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
/**
2+
* Desktop integration files of Linux builds: the desktop entry, AppStream
3+
* metainfo and install.sh, filled from App_Resources/Linux templates.
4+
*/
5+
6+
/** Reverse-DNS style id; it names files (`<id>.desktop`) and the install folder. */
7+
const APP_ID = /^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$/;
8+
9+
export function assertLinuxAppId(appId: string): void {
10+
if (!appId || !APP_ID.test(appId)) {
11+
throw new Error(
12+
`Invalid Linux app id '${appId ?? ""}': set "id" (or "linux.id") in nativescript.config to a reverse-DNS name such as org.example.MyApp.`,
13+
);
14+
}
15+
}
16+
17+
/** A desktop entry string value: no line breaks, so it can't start new keys. */
18+
export function desktopString(value: string): string {
19+
return value
20+
.replace(/\\/g, "\\\\")
21+
.replace(/\n/g, "\\n")
22+
.replace(/\r/g, "\\r")
23+
.replace(/\t/g, "\\t")
24+
.replace(/^ /, "\\s");
25+
}
26+
27+
/** A quoted `Exec=` argument (Desktop Entry spec: quoting, then string escapes, `%%` for `%`). */
28+
export function desktopExecArg(value: string): string {
29+
if (/[\r\n]/.test(value)) {
30+
throw new Error(`The path ${JSON.stringify(value)} has a line break.`);
31+
}
32+
const quoted = value.replace(/["`$\\]/g, "\\$&");
33+
return `"${desktopString(quoted).replace(/%/g, "%%")}"`;
34+
}
35+
36+
export function xmlEscape(value: string): string {
37+
return value.replace(
38+
/[&<>"']/g,
39+
(c) =>
40+
({
41+
"&": "&amp;",
42+
"<": "&lt;",
43+
">": "&gt;",
44+
'"': "&quot;",
45+
"'": "&apos;",
46+
})[c],
47+
);
48+
}
49+
50+
/** Replaces `__KEY__` placeholders with already escaped values. */
51+
export function fillTemplate(
52+
template: string,
53+
values: Record<string, string>,
54+
): string {
55+
return Object.entries(values).reduce(
56+
(text, [key, value]) => text.split(`__${key}__`).join(value),
57+
template,
58+
);
59+
}
60+
61+
/** A POSIX shell single-quoted word. */
62+
export function shellQuote(value: string): string {
63+
return `'${value.replace(/'/g, `'\\''`)}'`;
64+
}
65+
66+
/**
67+
* install.sh of release packages: copies the app into $XDG_DATA_HOME/<id> and
68+
* fills the desktop entry's `__EXEC__` with the quoted executable path.
69+
*/
70+
export function installScript(appId: string, name: string): string {
71+
assertLinuxAppId(appId);
72+
return [
73+
"#!/bin/sh",
74+
"# Installs the app for the current user (~/.local).",
75+
"set -e",
76+
`id=${shellQuote(appId)}`,
77+
`name=${shellQuote(name)}`,
78+
'src="$(cd "$(dirname "$0")" && pwd)"',
79+
'data="${XDG_DATA_HOME:-$HOME/.local/share}"',
80+
'dest="$data/$id"',
81+
'case "$dest" in *"',
82+
'"*) echo "Unsupported install path: $dest" >&2; exit 1 ;; esac',
83+
'rm -rf "$dest" && mkdir -p "$dest" "$data/applications" "$data/icons"',
84+
'cp -r "$src/." "$dest/"',
85+
// Exec= quoting, then desktop string escapes; awk replaces literally
86+
"exec_arg=\"\\\"$(printf '%s' \"$dest/$name\" | sed -e 's/[\\\\\"`$]/\\\\&/g' -e 's/\\\\/\\\\\\\\/g' -e 's/%/%%/g')\\\"\"",
87+
`NS_EXEC="$exec_arg" awk '{ s = $0; out = ""; while ((i = index(s, "__EXEC__")) > 0) { out = out substr(s, 1, i - 1) ENVIRON["NS_EXEC"]; s = substr(s, i + 8) } print out s }' "$src/$id.desktop" > "$data/applications/$id.desktop"`,
88+
'[ -d "$src/icons" ] && cp -r "$src/icons/." "$data/icons/"',
89+
'echo "Installed $name to $dest"',
90+
"",
91+
].join("\n");
92+
}

‎lib/services/linux-project-service.ts‎

Lines changed: 28 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,14 @@ import {
3232
writeTypingsIndex,
3333
} from "./linux-native-code";
3434
import { LinuxAppBundler } from "./linux-app-bundle";
35+
import {
36+
assertLinuxAppId,
37+
desktopExecArg,
38+
desktopString,
39+
fillTemplate,
40+
installScript,
41+
xmlEscape,
42+
} from "./linux-desktop-entry";
3543

3644
/** App_Resources/Linux files consumed by the build (desktop entry, icon, AppStream, metadata filters). */
3745
const BUILD_INPUTS = [
@@ -426,22 +434,18 @@ export class LinuxProjectService
426434
);
427435
const appId =
428436
projectData.projectIdentifiers?.linux || projectData.projectId;
437+
assertLinuxAppId(appId);
429438
const name = projectData.projectName;
430439
const version =
431440
this.$fs.readJson(path.join(projectData.projectDir, "package.json"))
432441
?.version || "1.0.0";
433-
const fill = (template: string, exec: string) =>
434-
template
435-
.split("__APP_ID__")
436-
.join(appId)
437-
.split("__APP_NAME__")
438-
.join(name)
439-
.split("__APP_VERSION__")
440-
.join(version)
441-
.split("__APP_DATE__")
442-
.join(new Date().toISOString().slice(0, 10))
443-
.split("__EXEC__")
444-
.join(exec);
442+
const values = (escape: (v: string) => string, exec: string) => ({
443+
APP_ID: escape(appId),
444+
APP_NAME: escape(name),
445+
APP_VERSION: escape(String(version)),
446+
APP_DATE: new Date().toISOString().slice(0, 10),
447+
EXEC: exec,
448+
});
445449

446450
const icon = ["icon.svg", "icon.png"]
447451
.map((f) => path.join(resources, f))
@@ -461,36 +465,29 @@ export class LinuxProjectService
461465
// debug builds point at this folder, install.sh rewrites release entries
462466
fs.writeFileSync(
463467
path.join(stage, `${appId}.desktop`),
464-
fill(desktop, release ? "__EXEC__" : path.join(stage, name)),
468+
fillTemplate(
469+
desktop,
470+
values(
471+
desktopString,
472+
release ? "__EXEC__" : desktopExecArg(path.join(stage, name)),
473+
),
474+
),
465475
);
466476

467477
const metainfo = path.join(resources, "app.metainfo.xml");
468478
if (this.$fs.exists(metainfo)) {
469479
fs.writeFileSync(
470480
path.join(stage, `${appId}.metainfo.xml`),
471-
fill(this.$fs.readText(metainfo), name),
481+
fillTemplate(
482+
this.$fs.readText(metainfo),
483+
values(xmlEscape, xmlEscape(name)),
484+
),
472485
);
473486
}
474487

475488
if (release) {
476489
const script = path.join(stage, "install.sh");
477-
fs.writeFileSync(
478-
script,
479-
[
480-
"#!/bin/sh",
481-
"# Installs the app for the current user (~/.local).",
482-
"set -e",
483-
'src="$(cd "$(dirname "$0")" && pwd)"',
484-
'data="${XDG_DATA_HOME:-$HOME/.local/share}"',
485-
`dest="$data/${appId}"`,
486-
'rm -rf "$dest" && mkdir -p "$dest" "$data/applications" "$data/icons"',
487-
'cp -r "$src/." "$dest/"',
488-
`sed "s|__EXEC__|$dest/${name}|g" "$src/${appId}.desktop" > "$data/applications/${appId}.desktop"`,
489-
'[ -d "$src/icons" ] && cp -r "$src/icons/." "$data/icons/"',
490-
`echo "Installed ${name} to $dest"`,
491-
"",
492-
].join("\n"),
493-
);
490+
fs.writeFileSync(script, installScript(appId, name));
494491
fs.chmodSync(script, 0o755);
495492
}
496493
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import * as fs from "fs";
2+
import * as os from "os";
3+
import * as path from "path";
4+
import { execFileSync } from "child_process";
5+
import { assert } from "chai";
6+
import {
7+
assertLinuxAppId,
8+
desktopExecArg,
9+
desktopString,
10+
fillTemplate,
11+
installScript,
12+
xmlEscape,
13+
} from "../../lib/services/linux-desktop-entry";
14+
15+
describe("linuxDesktopEntry", () => {
16+
it("rejects app ids that aren't file names", () => {
17+
for (const id of ["", "../evil", "a/b", "a b", "a\nb", ".a", "a..b"]) {
18+
assert.throws(() => assertLinuxAppId(id), /Invalid Linux app id/);
19+
}
20+
assertLinuxAppId("org.nativescript.my_app-1");
21+
});
22+
23+
it("keeps values on one line", () => {
24+
assert.equal(desktopString("My\nExec=evil\\"), "My\\nExec=evil\\\\");
25+
});
26+
27+
it("quotes Exec arguments", () => {
28+
assert.equal(desktopExecArg("/home/a b/app"), '"/home/a b/app"');
29+
assert.equal(
30+
desktopExecArg('/x/100%/$HOME/"q"/b\\s'),
31+
'"/x/100%%/\\\\$HOME/\\\\"q\\\\"/b\\\\\\\\s"',
32+
);
33+
assert.throws(() => desktopExecArg("/a\nb"));
34+
});
35+
36+
it("escapes XML", () => {
37+
assert.equal(
38+
fillTemplate("<name>__APP_NAME__</name>", {
39+
APP_NAME: xmlEscape(`A & <b> "'`),
40+
}),
41+
"<name>A &amp; &lt;b&gt; &quot;&apos;</name>",
42+
);
43+
});
44+
45+
it("installs with a quoted Exec and no shell injection", () => {
46+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "ns-linux-install-"));
47+
try {
48+
const src = path.join(root, "pkg");
49+
const data = path.join(root, "data 100%");
50+
const name = `My $(touch pwned) 'App'`;
51+
fs.mkdirSync(src);
52+
fs.writeFileSync(
53+
path.join(src, "install.sh"),
54+
installScript("org.x.app", name),
55+
);
56+
fs.writeFileSync(
57+
path.join(src, "org.x.app.desktop"),
58+
"[Desktop Entry]\nExec=__EXEC__ %U\n",
59+
);
60+
const out = execFileSync("sh", [path.join(src, "install.sh")], {
61+
cwd: root,
62+
env: { ...process.env, XDG_DATA_HOME: data },
63+
}).toString();
64+
assert.include(out, `Installed ${name}`);
65+
assert.isFalse(fs.existsSync(path.join(root, "pwned")));
66+
const exe = path.join(data, "org.x.app", name);
67+
assert.equal(
68+
fs.readFileSync(
69+
path.join(data, "applications", "org.x.app.desktop"),
70+
"utf8",
71+
),
72+
`[Desktop Entry]\nExec=${desktopExecArg(exe)} %U\n`,
73+
);
74+
} finally {
75+
fs.rmSync(root, { recursive: true, force: true });
76+
}
77+
});
78+
});

0 commit comments

Comments
 (0)