A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
feat(docker): drop Linux capabilities and set no_new_privs for the app processes (#3276)
Mohamed Bassem1c6aa6c4fcaa
diff --git a/docker/root/etc/s6-overlay/s6-rc.d/init-db-migration/run b/docker/root/etc/s6-overlay/s6-rc.d/init-db-migration/runindex f8cfe71b..c4c2a553 100644--- a/docker/root/etc/s6-overlay/s6-rc.d/init-db-migration/run+++ b/docker/root/etc/s6-overlay/s6-rc.d/init-db-migration/run@@ -3,4 +3,4 @@echo "Running db migration script";cd /db_migrations;-exec node index.js;+exec /etc/s6-overlay/scripts/drop-privileges node index.js;diff --git a/docker/root/etc/s6-overlay/s6-rc.d/svc-web/run b/docker/root/etc/s6-overlay/s6-rc.d/svc-web/runindex 83e9b9f1..cae73da4 100644--- a/docker/root/etc/s6-overlay/s6-rc.d/svc-web/run+++ b/docker/root/etc/s6-overlay/s6-rc.d/svc-web/run@@ -2,4 +2,4 @@# shellcheck shell=bashcd /app/apps/web;-exec node server.js;+exec /etc/s6-overlay/scripts/drop-privileges node server.js;diff --git a/docker/root/etc/s6-overlay/s6-rc.d/svc-workers/run b/docker/root/etc/s6-overlay/s6-rc.d/svc-workers/runindex 220f2e9b..550f77b0 100644--- a/docker/root/etc/s6-overlay/s6-rc.d/svc-workers/run+++ b/docker/root/etc/s6-overlay/s6-rc.d/svc-workers/run@@ -2,4 +2,4 @@# shellcheck shell=bashcd /app/apps/workers;-exec node dist/index.js+exec /etc/s6-overlay/scripts/drop-privileges node dist/index.jsdiff --git a/docker/root/etc/s6-overlay/scripts/drop-privileges b/docker/root/etc/s6-overlay/scripts/drop-privilegesnew file mode 100755index 00000000..e550ad6e--- /dev/null+++ b/docker/root/etc/s6-overlay/scripts/drop-privileges@@ -0,0 +1,73 @@+#!/bin/sh+# Runs the given command with the fewest privileges this container allows.+#+# - no_new_privs is set, so setuid binaries and file capabilities can't grant+# the process (or anything it spawns, e.g. yt-dlp, ghostscript or ffmpeg)+# more privileges.+# - When running as root, every Linux capability is dropped except:+# * DAC_OVERRIDE and FOWNER, so root can keep using a data directory owned+# by another user (e.g. a bind-mounted host directory), and CHOWN, which+# SQLite uses to keep its -wal/-shm files owned by the database file's+# owner. Everything else in the image is owned by root anyway, so these+# grant little beyond that.+# * NET_BIND_SERVICE, unless PORT and WORKERS_PORT are known to be at+# least 1024 (or unset).+#+# File ownership is never changed. If the runtime doesn't allow dropping+# capabilities (e.g. the container already runs without CAP_SETPCAP), it falls+# back to only setting no_new_privs, and then to running the command as is.+#+# Set KARAKEEP_DISABLE_PRIVILEGE_DROP=true to skip all of this.++if [ "${KARAKEEP_DISABLE_PRIVILEGE_DROP:-false}" = "true" ]; then+ exec "$@"+fi++# Whether a port setting might end up below 1024. The app is lenient when+# parsing ports (" 80 ", "+80" and "8e1" all mean 80), so only an unset or+# zero (random) port, or a plain number of at least 1024, is known not to need+# NET_BIND_SERVICE. Anything else keeps it.+may_be_privileged_port() {+ case "$1" in+ "" | 0) return 1 ;;+ *[!0-9]*) return 0 ;;+ esac+ [ "$1" -lt 1024 ]+}++if [ "$(id -u)" = "0" ]; then+ # Capability numbers: CHOWN=0, DAC_OVERRIDE=1, FOWNER=3, NET_BIND_SERVICE=10.+ KEEP_CAPS="+chown,+dac_override,+fowner"+ KEEP_MASK=$(((1 << 0) | (1 << 1) | (1 << 3)))+ if may_be_privileged_port "${PORT:-}" || may_be_privileged_port "${WORKERS_PORT:-}"; then+ KEEP_CAPS="${KEEP_CAPS},+net_bind_service"+ KEEP_MASK=$((KEEP_MASK | (1 << 10)))+ fi+ SETPRIV_DROP_CAPS="setpriv --no-new-privs --inh-caps=-all --ambient-caps=-all --bounding-set=-all,${KEEP_CAPS}"++ # Dry run that checks the capabilities the process actually ends up with:+ # some setpriv versions skip the bounding set without failing when+ # CAP_SETPCAP is missing. If the drop didn't take, fall through instead of+ # failing the service.+ DROPPED=false+ CAPS=$(${SETPRIV_DROP_CAPS} awk '/^Cap(Bnd|Eff):/ { print $2 }' /proc/self/status 2>/dev/null)+ if [ -n "${CAPS}" ]; then+ DROPPED=true+ for CAP in ${CAPS}; do+ if [ $((0x${CAP} & ~KEEP_MASK)) -ne 0 ]; then+ DROPPED=false+ fi+ done+ fi+ if [ "${DROPPED}" = "true" ]; then+ exec ${SETPRIV_DROP_CAPS} "$@"+ fi+ echo "WARNING: couldn't drop Linux capabilities, $1 keeps the container's full set." >&2+fi++if setpriv --no-new-privs true 2>/dev/null; then+ exec setpriv --no-new-privs "$@"+fi++echo "WARNING: couldn't set no_new_privs for $1." >&2+exec "$@"diff --git a/docs/docs/03-configuration/01-environment-variables.md b/docs/docs/03-configuration/01-environment-variables.mdindex 9dd06516..294910e0 100644--- a/docs/docs/03-configuration/01-environment-variables.md+++ b/docs/docs/03-configuration/01-environment-variables.md@@ -31,6 +31,7 @@ The app is mainly configured by environment variables. All the used environment| RULE_ENGINE_NUM_WORKERS | No | 1 | Number of concurrent workers for rule engine processing. Increase this if you have complex automation rules that need to be processed quickly. || MAX_RSS_FEEDS_PER_USER | No | 1000 | The maximum number of RSS feeds a user can create. || MAX_WEBHOOKS_PER_USER | No | 100 | The maximum number of webhooks a user can create. |+| KARAKEEP_DISABLE_PRIVILEGE_DROP | No | false | Docker image only. By default, the server and workers processes in the image start with all Linux capabilities dropped (except the ones needed to use a data directory owned by another user, or to listen on a port below 1024) and with `no_new_privs` set. This is best-effort: if the container runtime doesn't allow it, they start with fewer restrictions and a `WARNING: couldn't ...` line is logged. File ownership is never changed. Set this to `true` to run them with the container's full privileges, as older versions did. |## Asset Storagediff --git a/packages/e2e_tests/tests/docker/privileges.test.ts b/packages/e2e_tests/tests/docker/privileges.test.tsnew file mode 100644index 00000000..ee81eb7c--- /dev/null+++ b/packages/e2e_tests/tests/docker/privileges.test.ts@@ -0,0 +1,69 @@+import { execFileSync } from "child_process";+import * as path from "path";+import { fileURLToPath } from "url";+import { describe, expect, it } from "vitest";++// The directory holding the e2e docker-compose.yml.+const composeDir = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "../..",+);++// Prints "<name> <uid> <CapEff> <CapBnd> <NoNewPrivs>" for the web server and+// the workers. Matching on the start of the command line keeps this script+// (whose own command line mentions both names) out of the results.+const inspectScript = `+for d in /proc/[0-9]*; do+ c=$(tr "\\0" " " < "$d/cmdline" 2>/dev/null)+ case "$c" in+ "node dist/index.js"*) name=workers ;;+ next-server*) name=web ;;+ *) continue ;;+ esac+ echo "$name $(awk '/^Uid:/ { u = $2 } /^CapEff:/ { e = $2 } /^CapBnd:/ { b = $2 } /^NoNewPrivs:/ { n = $2 } END { print u, e, b, n }' "$d/status")"+done+`;++interface ProcessPrivileges {+ name: string;+ uid: string;+ capEff: string;+ capBnd: string;+ noNewPrivs: string;+}++function inspectAppProcesses(): ProcessPrivileges[] {+ const output = execFileSync(+ "docker",+ ["compose", "exec", "-T", "web", "sh", "-c", inspectScript],+ { cwd: composeDir, encoding: "utf8" },+ );+ return output+ .trim()+ .split("\n")+ .filter((line) => line.length > 0)+ .map((line) => {+ const [name, uid, capEff, capBnd, noNewPrivs] = line.split(" ");+ return { name, uid, capEff, capBnd, noNewPrivs };+ });+}++describe("Docker image privileges", () => {+ it("runs the web server and workers with only the capabilities they need", () => {+ const processes = inspectAppProcesses();++ expect(processes.map((p) => p.name).sort()).toEqual(["web", "workers"]);+ // CHOWN (bit 0), DAC_OVERRIDE (bit 1) and FOWNER (bit 3), see+ // docker/root/etc/s6-overlay/scripts/drop-privileges.+ const expectedCaps = "000000000000000b";+ for (const p of processes) {+ expect(p, p.name).toEqual({+ name: p.name,+ uid: "0",+ capEff: expectedCaps,+ capBnd: expectedCaps,+ noNewPrivs: "1",+ });+ }+ });+});