Files
wekan/sandstorm-src/start.js
T
Lauri Ojansivu e9751b65d4 Caddy and FerretDB run with no MPTCP listener (CVE-2026-98432).
CVE-2026-98432 is a Linux kernel use-after-free in IPv4 TCP connection
handling, shown to give remote code execution through an MPTCP listener
(golang-announce, 2026-10). Since Go 1.24 every Linux listen socket of a
Go program is MPTCP by default, and WeKan ships two Go servers: Caddy, the
snap's web server on ports 80 and 443, and FerretDB, the default database.

Every place WeKan starts one sets GODEBUG=multipathtcp=0: the snap's
environment (every app, Caddy and FerretDB among them), the Docker
entrypoint and the bundle launcher - which keep an operator's own
multipathtcp setting - every docker-compose FerretDB service (the commented
FerretDB 2 example too), and the FerretDB the Sandstorm grain starts. Caddy
is an upstream binary, so no rebuild is needed: Go reads GODEBUG at start.
wekan/FerretDB builds with `godebug multipathtcp=0` as well. The real fix
is a patched host kernel.

Checked on Linux: a Go server's default listener reports MPTCP true;
GODEBUG=multipathtcp=0, or the go.mod setting, makes it false.
tests/goMptcpOff.test.cjs pins every launcher, runs the launcher line, and
fails when something turns MPTCP back on.

Thanks to xet7 !
2026-10-30 04:30:39 +02:00

431 lines
22 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// WeKan on Sandstorm — grain launcher (meteor-spk.deps/start.js).
//
// Runs WeKan (Node 26) on FerretDB v1 (embedded SQLite), migrating an existing
// grain's data to FerretDB on first launch. See
// docs/Platforms/FOSS/Container/Sandstorm/Meteor3/Migration.md.
//
// Data an existing grain may hold, and how this handles it:
// * none → fresh: run WeKan on an empty FerretDB.
// * niscu (MongoDB 2.x) → migrate niscu → MongoDB 3.0 (the legacy meteor-spk
// data under /var path, preserved), which produces /var/wiredTigerDb,
// then migrate MongoDB 3.0 → FerretDB.
// * MongoDB 3.0 (WiredTiger) → migrate MongoDB 3.0 → FerretDB.
// under /var/wiredTigerDb
// * already FerretDB → marker present: skip, run WeKan on FerretDB.
//
// The MongoDB 3 → FerretDB step reads with the legacy Mongo CLI (mongoexport —
// the modern driver can't talk to 3.x) and inserts into FerretDB with the Node
// driver; CollectionFS/Meteor-Files GridFS attachments+avatars are extracted to
// the filesystem. Migration is idempotent (marker); the old data is never
// auto-deleted (the admin frees it from Admin Panel / Attachments / Sandstorm).
const markStartup = require('./startup-timing')('launcher');
markStartup('entry');
const { spawn, spawnSync } = require('child_process');
const fs = require('fs');
const net = require('net');
const path = require('path');
// ── layout ───────────────────────────────────────────────────────────────────
// Read-only app payload (resolve from __dirname; do not hardcode the mount point).
const APPROOT = __dirname;
const NODE = path.join(APPROOT, 'bin/node'); // Node 26
const MONGOD3 = path.join(APPROOT, 'bin/mongod'); // MongoDB 3.0.7
const NISCUD = path.join(APPROOT, 'bin/niscud'); // MongoDB 2.x (Niscu)
const MM_BIN = path.join(APPROOT, 'migratemongo/bin'); // mongo + mongoexport (3.x CLIs)
const MM_LIB = path.join(APPROOT, 'migratemongo/lib'); // old glibc for those CLIs
const MONGO_CLI = path.join(MM_BIN, 'mongo');
const FERRETDB = path.join(APPROOT, 'ferretdb'); // FerretDB v1 (Go, SQLite)
const IMPORTER = path.join(APPROOT, 'migrate-mongo3-to-ferretdb.mjs');
const BRIDGE = path.join(APPROOT, 'migration-bridge.js'); // "please wait" page on APP_PORT
const NODE_MODULES = path.join(APPROOT, 'programs/server/node_modules');
// #6458: run every bundled binary through cpu-exec when it is available, so a
// grain landing on a host whose CPU lacks a feature a binary needs — AVX masked
// by a hypervisor (QEMU/KVM/Proxmox) is the reported case — transparently falls
// back to bundled qemu-user instead of dying instantly with SIGILL (exit 132).
// Sandstorm has the least control over its hardware of any WeKan platform, and
// was the only launcher still spawning binaries directly: Docker
// (releases/ferretdb/wekan-entrypoint.sh), the bundle
// (releases/ferretdb/start-wekan.sh) and the snap (snap-src/bin/mongodb-control)
// already route through it.
//
// None of these binaries DECLARES a required feature, so cpu-exec exec's them
// directly with zero overhead today; the point is that the launch path is
// feature-safe if that ever stops being true (a newer FerretDB build, a Node
// built for a higher baseline, a future bundled mongod).
//
// cpu-exec is a bash script, so it needs both itself and bash to be executable;
// if either is missing the binary is run directly, exactly as before.
const CPU_EXEC = path.join(APPROOT, 'bin/cpu-exec');
const HAVE_CPU_EXEC = (() => {
try {
fs.accessSync(CPU_EXEC, fs.constants.X_OK);
fs.accessSync('/bin/bash', fs.constants.X_OK);
return true;
} catch (_) {
return false;
}
})();
// Spread into spawn/spawnSync: spawnSync(...cpuExec(BIN, [args]), opts).
function cpuExec(bin, args) {
return HAVE_CPU_EXEC ? [CPU_EXEC, [bin, ...args]] : [bin, args];
}
// Writable grain state (only /var is writable in a grain).
const NISCU_DBPATH = '/var'; // legacy niscu data dir
const NISCU_MARKER = '/var/journal'; // presence ⇒ niscu-era data
const OLD_MONGO = '/var/wiredTigerDb'; // MongoDB 3.0 data dir
const FILES_DIR = '/var/files'; // WRITABLE_PATH
const SQLITE_DIR = path.join(FILES_DIR, 'db'); // FerretDB SQLite dir
const STATE_DIR = '/var/ferretdb'; // FerretDB process state (state.json)
const MARKER = '/var/.migration-to-ferretdb-done'; // FerretDB migration done
const STATUS_FILE = path.join(SQLITE_DIR, 'migration-status.json');
const MIGRATE_LOG = '/var/migration-mongod.log';
// Ports (loopback inside the grain).
const APP_PORT = process.env.PORT || '4000'; // behind sandstorm-http-bridge
const DB_PORT = '4001'; // FerretDB steady-state
const SRC_PORT = '4003'; // mongod 3.0 (migration source)
const NISCU_PORT = '4004'; // niscud (niscu→3.0 source)
// #6503/#6480/#6481: FerretDB v1 CAN tail an OpLog (auto-created capped
// local.oplog.rs + replica-set hello handshake), but on the SQLite backend the
// tailable+awaitData tail keeps FerretDB CPU pinned (~190–390% even idle) and a
// struggling tail shows as "oplog catching up took too long" and stalls loading,
// so the DEFAULT is now POLLING ONLY. Opt into OpLog tailing with
// WEKAN_FERRETDB_OPLOG=true. The transient migration-target FerretDB above stays
// OpLog-free (no --repl-set-name) regardless.
const FERRET_OPLOG = process.env.WEKAN_FERRETDB_OPLOG === 'true';
const REPL_SET_NAME = process.env.WEKAN_FERRETDB_REPL_SET || 'rs0';
function ensureDirs() {
for (const d of [FILES_DIR, SQLITE_DIR, STATE_DIR,
path.join(FILES_DIR, 'attachments'),
path.join(FILES_DIR, 'avatars')]) {
fs.mkdirSync(d, { recursive: true });
}
}
function haveNiscuData() { return fs.existsSync(NISCU_MARKER); }
function haveMongo3Data() { return fs.existsSync(path.join(OLD_MONGO, 'WiredTiger')); }
// LD_LIBRARY_PATH with the old libs prepended (for the Mongo 3.x CLI tools).
function oldLibEnv() {
return {
...process.env,
LD_LIBRARY_PATH: MM_LIB + (process.env.LD_LIBRARY_PATH ? ':' + process.env.LD_LIBRARY_PATH : ''),
};
}
// Block without a child process: a grain has no /bin/sleep (no coreutils at all),
// so spawning it failed silently and every wait here returned at once.
const SLEEP_CELL = new Int32Array(new SharedArrayBuffer(4));
function sleep(sec) { Atomics.wait(SLEEP_CELL, 0, 0, sec * 1000); }
// ── "please wait" bridge on APP_PORT ─────────────────────────────────────────
// Sandstorm frames the grain, proxying to APP_PORT via /sandstorm-http-bridge. Any
// moment nothing is bound there — during first-launch migration and the handoff to
// WeKan — the browser shows "This page can not be displayed embedded in another page"
// (see docs/Platforms/FOSS/Container/Sandstorm). Keep a tiny child-process server
// answering on APP_PORT across those windows so the grain stays framed until WeKan is
// up. A CHILD process (not in-process) is required: start.js runs the migration with
// blocking spawnSync, so it could not service an in-process server nor release its
// listening socket before the importer / Meteor bind APP_PORT — killing a child is a
// definitive socket close. Best-effort: never blocks or crashes startup.
let bridge = null;
function startBridge(message) {
if (bridge || !fs.existsSync(BRIDGE)) return; // already up, or not bundled
try {
bridge = spawn(...cpuExec(NODE, [BRIDGE]), {
stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
env: { ...process.env, PORT: APP_PORT, BRIDGE_MESSAGE: message || '' },
});
bridge.on('error', () => {}); // a bridge failure must not break startup
const child = bridge;
bridge.on('exit', () => {
// Migration blocks the event loop. An old bridge's exit event can arrive
// after startBridge has installed its replacement; retain that new owner
// so yieldPortOnListen can stop it before Meteor binds APP_PORT.
if (bridge === child) bridge = null;
});
} catch (_) { bridge = null; }
}
function stopBridge() {
if (!bridge) return;
try { bridge.kill('SIGTERM'); } catch (_) {}
bridge = null;
sleep(1); // let the OS release APP_PORT before the next listener binds it
}
process.on('exit', () => { if (bridge) { try { bridge.kill('SIGKILL'); } catch (_) {} } });
// Hand APP_PORT from the bridge to WeKan at the moment WeKan BINDS it, not
// before main.js loads. Meteor 3 awaits every Meteor.startup hook before it
// calls httpServer.listen (boot.js callStartupHooks, then webapp's main), and
// on a grain those hooks take a while. Releasing the port before require()
// left nothing on APP_PORT for all of that time, so sandstorm-http-bridge got
// connection-refused, which Sandstorm passes on as a DISCONNECTED error and
// the browser shows as an empty response (NS_ERROR_NET_EMPTY_RESPONSE) - and
// a startup hook that never finished made it permanent. Now the please-wait
// page answers until the listen call itself. The bridge releases its listening
// socket over IPC but retains active readiness requests until Meteor listens.
function yieldPortOnListen() {
const listen = net.Server.prototype.listen;
net.Server.prototype.listen = function (...args) {
const opts = args[0];
const port = opts && typeof opts === 'object' ? opts.port : opts;
if (String(port) !== String(APP_PORT)) return listen.apply(this, args);
net.Server.prototype.listen = listen; // only the first bind of APP_PORT
markStartup('meteor-listen-requested');
this.once('listening', () => {
markStartup('meteor-listening');
if (child && child.connected) {
child.send('app-listening', () => {});
}
console.log(`** WeKan is listening on port ${APP_PORT}`);
});
const child = bridge;
bridge = null;
if (!child || child.exitCode !== null || child.signalCode !== null) {
return listen.apply(this, args);
}
let bound = false;
const bind = () => { if (!bound) { bound = true; listen.apply(this, args); } };
child.once('exit', bind);
// An unresponsive bridge must not keep WeKan off its port. Also reap it if
// an abandoned browser connection prevents graceful shutdown after handoff.
const killTimer = setTimeout(() => { try { child.kill('SIGKILL'); } catch (_) {} }, 3000);
killTimer.unref();
child.once('exit', () => clearTimeout(killTimer));
if (child.connected) {
child.on('message', message => { if (message === 'port-released') bind(); });
child.send('release-port', error => {
if (error) { try { child.kill('SIGTERM'); } catch (_) { bind(); } }
});
} else {
// Compatibility with bridge processes started without an IPC channel.
try { child.kill('SIGTERM'); } catch (_) { bind(); }
}
return this;
};
}
function startFerret(port, opts = {}) {
const args = ['--handler=sqlite', `--sqlite-url=file:${SQLITE_DIR}/`,
// FerretDB persists state.json via its state provider even with telemetry
// off; its --state-dir defaults to "." (= "/" in a grain, read-only), so
// point it at writable /var or it fails with "open /state.json: read-only
// file system" and the grain crash-loops.
`--state-dir=${STATE_DIR}`,
`--listen-addr=127.0.0.1:${port}`, '--telemetry=disable'];
// Only the steady-state instance enables the OpLog; the migration target does
// not, so bulk inserts are not slowed by oplog recording.
if (opts.oplog && FERRET_OPLOG) args.push(`--repl-set-name=${REPL_SET_NAME}`);
return spawn(...cpuExec(FERRETDB, args),
{ stdio: 'inherit',
// CVE-2026-98432: no MPTCP listener, Go's default since 1.24.
env: { ...process.env, DO_NOT_TRACK: '1', FERRETDB_TELEMETRY: 'disable',
FERRETDB_STATE_DIR: STATE_DIR, GODEBUG: 'multipathtcp=0' } });
}
// Wait until a mongod (3.x) answers a ping via the legacy mongo shell.
function waitMongoReady(port, tries = 30) {
for (let i = 0; i < tries; i++) {
const r = spawnSync(...cpuExec(MONGO_CLI,
['--port', String(port), '--quiet', '--eval', 'db.adminCommand({ping:1}).ok']),
{ env: oldLibEnv(), encoding: 'utf8' });
if (r.status === 0 && /1/.test(r.stdout || '')) return true;
sleep(1);
}
return false;
}
function stopMongo(port) {
spawnSync(...cpuExec(MONGO_CLI,
['--port', String(port), '--quiet', '--eval',
'db.getSiblingDB("admin").shutdownServer()']),
{ env: oldLibEnv(), encoding: 'utf8' });
sleep(2);
}
// ── Stage 1: niscu (MongoDB 2.x) → MongoDB 3.0 (WiredTiger) ───────────────────
// Faithful port of the legacy meteor-spk niscu→3.0 migration, using niscud and
// mongod 3.0 with the old bundled MongoDB driver (deps/node_modules/mongodb).
// Produces /var/wiredTigerDb, which Stage 2 then migrates to FerretDB.
async function migrateNiscuToMongo3() {
console.log('** WeKan: migrating niscu (MongoDB 2.x) -> MongoDB 3.0 ...');
const MongoClient = require('mongodb').MongoClient;
spawnSync(...cpuExec(NISCUD,
['--fork', '--port', NISCU_PORT, '--dbpath', NISCU_DBPATH, '--noauth',
'--bind_ip', '127.0.0.1', '--nohttpinterface', '--noprealloc',
'--logpath', '/var/niscu.log']),
{ stdio: 'inherit', env: process.env });
fs.mkdirSync(OLD_MONGO, { recursive: true });
spawnSync(...cpuExec(MONGOD3,
['--fork', '--port', SRC_PORT, '--dbpath', OLD_MONGO, '--noauth',
'--bind_ip', '127.0.0.1', '--storageEngine', 'wiredTiger',
// Pin the WiredTiger cache. mongod 3.0 sizes it from detected RAM
// (RAM/2 - 1GB), but inside a Sandstorm grain sandbox RAM detection returns
// 0, so it computes cache_size=0G and WiredTiger aborts (minimum is 1MB) with
// "Fatal Assertion 28561". mongod 3.0.7 parses this option as an integer
// number of GB (a decimal like 0.25 fails with 'Bad digit "."'), so pin it to
// 1 GB. It is a cache cap, not a preallocation, so a short migration of a
// normal-sized grain never actually uses that much; it just never depends on
// RAM detection.
'--wiredTigerCacheSizeGB', '1',
'--wiredTigerEngineConfigString', 'log=(prealloc=false,file_max=200KB)',
'--logpath', MIGRATE_LOG]),
{ stdio: 'inherit', env: process.env });
if (!waitMongoReady(SRC_PORT)) throw new Error('mongod 3.0 did not become ready for niscu import');
sleep(2); // give niscud a moment (old 2.x, not pingable with the 3.x shell)
const oldDb = await MongoClient.connect(`mongodb://127.0.0.1:${NISCU_PORT}/meteor`, {});
const newDb = await MongoClient.connect(`mongodb://127.0.0.1:${SRC_PORT}/meteor`, {});
const collections = await oldDb.collections();
for (const oldColl of collections) {
if (oldColl.collectionName.slice(0, 7) === 'system.') continue; // indexes regenerate
console.log(' niscu collection:', oldColl.collectionName);
const newColl = await newDb.createCollection(oldColl.collectionName);
const cursor = oldColl.find();
while (await cursor.hasNext()) {
await newColl.insertOne(await cursor.next());
}
}
try { await oldDb.admin().command({ shutdown: 1 }); } catch (_) {} // server kills itself
stopMongo(SRC_PORT);
console.log('** niscu -> MongoDB 3.0 done.');
}
// ── Stage 2: MongoDB 3.0 → FerretDB v1 (SQLite) ──────────────────────────────
function migrateMongo3ToFerret() {
console.log('** WeKan: migrating MongoDB 3 -> FerretDB (one-time) ...');
const started = spawnSync(...cpuExec(MONGOD3,
['--dbpath', OLD_MONGO, '--bind_ip', '127.0.0.1', '--port', SRC_PORT,
'--storageEngine', 'wiredTiger',
// Pin the WiredTiger cache to 1 GB: in a Sandstorm grain sandbox mongod 3.0's
// RAM detection returns 0, so its default cache sizing computes cache_size=0G
// and WiredTiger aborts with "Value too small for key 'cache_size'" /
// "Fatal Assertion 28561", which is exactly why this migration crash-looped on
// an existing grain's data. mongod 3.0.7 parses this option as an integer GB
// (0.25 fails to parse), and it is a cap not a preallocation. See the niscu
// stage above for the same fix.
'--wiredTigerCacheSizeGB', '1',
'--fork', '--logpath', MIGRATE_LOG]),
{ stdio: 'inherit', env: process.env });
if (started.status !== 0 || !waitMongoReady(SRC_PORT)) {
console.error(`** Migration: could not start/reach mongod 3.0 on the old data (see ${MIGRATE_LOG}). Old data kept; retry next start.`);
stopMongo(SRC_PORT);
process.exit(1);
}
const ferret = startFerret(DB_PORT); // the PERMANENT SQLite dir (no temp/switch)
// The importer binds APP_PORT itself for its own progress dashboard
// (MIGRATION_PORT below), so release our please-wait bridge first.
stopBridge();
const rc = spawnSync(...cpuExec(NODE, [IMPORTER]), {
stdio: 'inherit',
env: { ...process.env,
NODE_PATH: NODE_MODULES,
MONGO_BIN_DIR: MM_BIN,
MONGO_LIB: MM_LIB,
// Sandstorm WeKan grains store their data in the Meteor-default database
// "meteor" (the niscu -> 3.0 stage above also reads/writes "meteor", and an
// existing grain's WiredTiger catalog shows meteor.* collections). Only the
// FerretDB *target* is "wekan". Reading SRC_DB 'wekan' here migrated zero
// documents from a real grain.
SRC_PORT, SRC_DB: 'meteor',
TARGET_MONGO_URL: `mongodb://127.0.0.1:${DB_PORT}/wekan`,
FILES_DIR,
MIGRATION_PORT: APP_PORT, // progress dashboard shown at the grain URL
STATUS_FILE },
}).status;
try { ferret.kill(); } catch (_) {}
stopMongo(SRC_PORT);
// The importer's dashboard is gone; bridge the handoff until WeKan binds APP_PORT.
startBridge('Finishing up — starting WeKan…');
if (rc === 0) {
fs.writeFileSync(MARKER, new Date().toISOString()); // never re-migrate; old data KEPT
console.log('** Migration succeeded.');
} else {
console.error('** Migration failed; retry on next grain start. Old data kept.');
process.exit(1);
}
}
async function migrateIfNeeded() {
if (fs.existsSync(MARKER)) return; // already on FerretDB
if (haveNiscuData() && !haveMongo3Data()) {
markStartup('niscu-migration-start');
await migrateNiscuToMongo3(); // → produces /var/wiredTigerDb
markStartup('niscu-migration-end');
}
if (haveMongo3Data()) {
markStartup('mongo3-migration-start');
migrateMongo3ToFerret(); // → FerretDB
markStartup('mongo3-migration-end');
}
}
async function runApp() {
markStartup('migration-check-complete');
markStartup('ferretdb-spawn');
const ferret = startFerret(DB_PORT, { oplog: true }); // steady-state DB, OpLog on
ferret.on('exit', code => { // if the DB dies, restart the grain
console.error(`** FerretDB exited (code ${code}); stopping grain.`);
process.exit(code || 1);
});
process.on('exit', () => { try { ferret.kill(); } catch (_) {} });
process.env.MONGO_URL = `mongodb://127.0.0.1:${DB_PORT}/wekan`;
// Prefer OpLog tailing, fall back to polling if it does not come up (OpLog only
// when it works). Admin Panel → Version shows the live Reactivity mode.
if (FERRET_OPLOG) {
process.env.MONGO_OPLOG_URL = process.env.MONGO_OPLOG_URL ||
`mongodb://127.0.0.1:${DB_PORT}/local?replicaSet=${REPL_SET_NAME}`;
process.env.METEOR_REACTIVITY_ORDER = process.env.METEOR_REACTIVITY_ORDER || 'oplog,polling';
process.env.DEFAULT_METEOR_REACTIVITY_ORDER = process.env.DEFAULT_METEOR_REACTIVITY_ORDER || 'oplog,polling';
} else {
// #6498: also clear MONGO_OPLOG_URL — merely having it set makes Meteor start an
// OpLog tail at boot that polls FerretDB continuously (high CPU even with no
// clients), regardless of the reactivity order. Clearing it makes polling-only real.
delete process.env.MONGO_OPLOG_URL;
process.env.METEOR_REACTIVITY_ORDER = process.env.METEOR_REACTIVITY_ORDER || 'polling';
process.env.DEFAULT_METEOR_REACTIVITY_ORDER = process.env.DEFAULT_METEOR_REACTIVITY_ORDER || 'polling';
}
process.env.ROOT_URL = process.env.ROOT_URL || `http://127.0.0.1:${APP_PORT}`;
process.env.PORT = APP_PORT;
process.env.WRITABLE_PATH = FILES_DIR;
// Enable Sandstorm auth. The wekan-accounts-sandstorm package only sets
// __meteor_runtime_config__.SANDSTORM (which triggers the client's automatic
// header-based login) when process.env.SANDSTORM is set. Without it WeKan boots
// but every page shows "Must be logged in". Must be set BEFORE require('./main.js')
// so the package sees it at load. (Sandstorm context for app code is a separate
// flag, Meteor.settings.public.sandstorm, set via METEOR_SETTINGS in the pkgdef.)
process.env.SANDSTORM = '1';
console.log('** Starting WeKan on FerretDB ...');
await require('./wait-for-port')(DB_PORT);
markStartup('ferretdb-listening');
// The please-wait page keeps APP_PORT until Meteor binds it (above).
markStartup('meteor-load-start');
yieldPortOnListen();
require('./main.js');
// main.js starts asynchronous boot: returning is NOT HTTP readiness.
markStartup('meteor-require-returned');
}
ensureDirs();
markStartup('directories-ready');
// Show the please-wait page on APP_PORT from the very start so the grain is never an
// unframable connection-refused error, whether this launch migrates data or not.
const willMigrate = !fs.existsSync(MARKER) && (haveNiscuData() || haveMongo3Data());
startBridge(willMigrate ? 'WeKan is migrating your data…' : 'WeKan is starting…');
markStartup('migration-check-start');
migrateIfNeeded()
.then(runApp)
.catch(e => { console.error('** Fatal during migration:', e && e.stack || e); process.exit(1); });