Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Sandbox LibreOffice (#8150)

Anthony Stirlingb7cce8da650e
diff --git a/.github/config/.files.yaml b/.github/config/.files.yaml
index c2c6ff81d8..5a277000c8 100644
--- a/.github/config/.files.yaml
+++ b/.github/config/.files.yaml
@@ -40,7 +40,7 @@ openapi: &openapi
- .github/workflows/check-openapi.yml
docker-base: &docker-base
- - docker/base/Dockerfile
+ - docker/base/**
# Dockerfiles only (base, embedded, and unoserver). The slow multi-architecture
# (arm64) leg of the PR Docker test build runs only when a Dockerfile changes,
diff --git a/.github/workflows/push-docker.yml b/.github/workflows/push-docker.yml
index ef4c966597..95cb240bcc 100644
--- a/.github/workflows/push-docker.yml
+++ b/.github/workflows/push-docker.yml
@@ -289,7 +289,11 @@ jobs:
docker/unoserver/Dockerfile \
docker/unoserver/entrypoint.sh \
docker/unoserver/healthcheck.sh \
+ docker/unoserver/fonts.conf \
docker/unoserver/VERSION \
+ docker/base/lo-sandbox.c \
+ docker/base/stirling-hardening.xcd \
+ docker/base/unoserver-pipe-transport.py \
| sha256sum | cut -d' ' -f1)
echo "hash=${hash}" >> "$GITHUB_OUTPUT"
echo "Unoserver source hash: ${hash}"
diff --git a/.github/workflows/test-build-docker.yml b/.github/workflows/test-build-docker.yml
index eae6d0025c..4d7be9b468 100644
--- a/.github/workflows/test-build-docker.yml
+++ b/.github/workflows/test-build-docker.yml
@@ -124,22 +124,6 @@ jobs:
id: buildx
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0
- - name: Set base image for this build
- id: build-params
- # Pass workflow inputs through env vars rather than expanding `${{ }}`
- # directly into the shell — defense-in-depth against template injection
- # if any upstream provider of these values ever becomes less trusted.
- # GITHUB_EVENT_NAME is already provided by the runner.
- env:
- DOCKER_BASE_CHANGED: ${{ inputs.docker-base-changed }}
- run: |
- if [ "$GITHUB_EVENT_NAME" = "pull_request" ] && [ "$DOCKER_BASE_CHANGED" = "true" ]; then
- # Base Dockerfile changed: build against the locally-built base.
- echo "base_image=stirling-pdf-base:pr-test" >> "$GITHUB_OUTPUT"
- else
- echo "base_image=stirlingtools/stirling-pdf-base:latest" >> "$GITHUB_OUTPUT"
- fi
-
# Base-changed PRs build the embedded image with the local docker driver
# so the locally-built stirling-pdf-base:pr-test (in the daemon image
# store) resolves. A buildx container builder cannot see it and would try
@@ -148,13 +132,13 @@ jobs:
if: github.event_name == 'pull_request' && inputs.docker-base-changed == 'true'
run: |
DOCKER_BUILDKIT=1 docker build \
- --build-arg BASE_IMAGE=${{ steps.build-params.outputs.base_image }} \
+ --build-arg BASE_IMAGE=stirling-pdf-base:pr-test \
--file ./${{ matrix.docker-rev }} \
--tag stirling-pdf-embedded:pr-test \
.
# PRs that did NOT change the base use the buildx container builder
- # against the published base image.
+ # against the base image the Dockerfile pins.
- name: Build ${{ matrix.docker-rev }} (${{ matrix.platform }})
if: inputs.docker-base-changed != 'true'
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
@@ -168,8 +152,6 @@ jobs:
# image and PR entries were evicted before the next PR read them.
cache-from: type=gha,scope=${{ matrix.cache-scope }}
platforms: ${{ matrix.platform }}
- build-args: |
- BASE_IMAGE=${{ steps.build-params.outputs.base_image }}
provenance: true
sbom: true
diff --git a/app/common/src/main/java/stirling/software/common/configuration/RuntimePathConfig.java b/app/common/src/main/java/stirling/software/common/configuration/RuntimePathConfig.java
index 7cabc88ca7..d4f822185b 100644
--- a/app/common/src/main/java/stirling/software/common/configuration/RuntimePathConfig.java
+++ b/app/common/src/main/java/stirling/software/common/configuration/RuntimePathConfig.java
@@ -4,6 +4,7 @@ import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
@@ -156,6 +157,12 @@ public class RuntimePathConfig {
}
this.unoServerEndpoints = buildUnoServerEndpoints(processExecutor, libreOfficeLimit);
ProcessExecutor.setUnoServerPool(new UnoServerPool(this.unoServerEndpoints));
+
+ ApplicationProperties.TempFileManagement tempFiles = system.getTempFileManagement();
+ if (tempFiles != null) {
+ ProcessExecutor.setLibreOfficeWorkRoots(
+ Arrays.asList(tempFiles.getBaseTmpDir(), tempFiles.getLibreofficeDir()));
+ }
}
private String resolvePath(String defaultPath, String customPath) {
diff --git a/app/common/src/main/java/stirling/software/common/util/LibreOfficeSandboxPolicy.java b/app/common/src/main/java/stirling/software/common/util/LibreOfficeSandboxPolicy.java
new file mode 100644
index 0000000000..a98ca65f1d
--- /dev/null
+++ b/app/common/src/main/java/stirling/software/common/util/LibreOfficeSandboxPolicy.java
@@ -0,0 +1,260 @@
+package stirling.software.common.util;
+
+import java.io.IOException;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import lombok.extern.slf4j.Slf4j;
+
+/**
+ * Per-job confinement for the soffice conversions Java launches itself (office fallback, PDF/A,
+ * PDF-to-office). The shared policy exported by the init script lets LibreOffice write anywhere the
+ * Java user can, including other jobs' files under the shared temp dir; this narrows it to the
+ * job's own profile and output directory, read access to its input files, and a socket-only grant
+ * on /tmp. The variables are read by {@code docker/base/lo-sandbox.c}; outside the Docker image
+ * soffice is the real binary and ignores them.
+ */
+@Slf4j
+final class LibreOfficeSandboxPolicy {
+
+ static final String IPC_PIPE_DIR = "/tmp";
+ private static final String IPC_PIPE_PREFIX = "OSL_PIPE_";
+ private static final String USER_INSTALLATION_PREFIX = "-env:UserInstallation=";
+
+ /** soffice options whose value is the next argument rather than an input document. */
+ private static final Set<String> OPTIONS_WITH_VALUE =
+ Set.of("--convert-to", "--outdir", "--print-to-file", "--printer-name");
+
+ private static final String PROFILE_TMP_DIR = "tmp";
+
+ /** Environment for one soffice run and the profile it will use. */
+ record JobPolicy(Map<String, String> env, Path profile) {}
+
+ private LibreOfficeSandboxPolicy() {}
+
+ /**
+ * Environment overrides confining {@code command} to its own files, or empty when the command
+ * is not a direct soffice conversion, its paths cannot be expressed in the colon-separated
+ * lists lo-sandbox reads, or any of them lies outside {@code workRoots} (absolute, normalised
+ * dirs), in which case the inherited shared policy still applies.
+ */
+ static Optional<JobPolicy> forCommand(List<String> command, List<Path> workRoots) {
+ Path rawProfile = null;
+ Path rawOutDir = null;
+ List<Path> rawInputs = new ArrayList<>();
+ for (int i = 1; i < command.size(); i++) {
+ String arg = command.get(i);
+ if (arg.startsWith(USER_INSTALLATION_PREFIX)) {
+ rawProfile = toPath(arg.substring(USER_INSTALLATION_PREFIX.length()));
+ } else if ("--outdir".equals(arg) && i + 1 < command.size()) {
+ rawOutDir = toPath(command.get(++i));
+ } else if (OPTIONS_WITH_VALUE.contains(arg)) {
+ i++;
+ } else if (!arg.startsWith("-")) {
+ Path input = toPath(arg);
+ if (input != null) {
+ rawInputs.add(input);
+ }
+ }
+ }
+ if (rawProfile == null || rawOutDir == null) {
+ return Optional.empty();
+ }
+ Path profile = confined(rawProfile, workRoots);
+ Path outDir = confined(rawOutDir, workRoots);
+ List<Path> inputs = new ArrayList<>();
+ for (Path rawInput : rawInputs) {
+ Path input = confined(rawInput, workRoots);
+ if (input == null) {
+ return outsideWorkRoots(rawInput);
+ }
+ if (Files.isRegularFile(input)) {
+ inputs.add(input);
+ }
+ }
+ if (profile == null || outDir == null) {
+ return outsideWorkRoots(profile == null ? rawProfile : rawOutDir);
+ }
+ if (!listable(profile, outDir, inputs)) {
+ return Optional.empty();
+ }
+ Path tmp = profile.resolve(PROFILE_TMP_DIR);
+ try {
+ Files.createDirectories(tmp);
+ Files.createDirectories(outDir);
+ } catch (IOException e) {
+ log.warn("Cannot prepare LibreOffice job dirs under {}: {}", profile, e.getMessage());
+ return Optional.empty();
+ }
+
+ Map<String, String> env = new LinkedHashMap<>();
+ env.put("STIRLING_LO_ALLOW_RW", profile + ":" + outDir + ":/dev");
+ env.put("STIRLING_LO_ALLOW_SOCK", IPC_PIPE_DIR);
+ env.put("STIRLING_LO_ALLOW_RO_EXTRA", join(inputs));
+ env.put("HOME", profile.toString());
+ for (String name : List.of("TMPDIR", "TMP", "TEMP", "SAL_TMP", "XDG_RUNTIME_DIR")) {
+ env.put(name, tmp.toString());
+ }
+ return Optional.of(new JobPolicy(env, profile));
+ }
+
+ /**
+ * {@code path} made absolute and normalised when it lies within one of {@code roots}, null
+ * otherwise. Normalising first means {@code ..} cannot climb out of a root.
+ */
+ private static Path confined(Path path, List<Path> roots) {
+ Path normalized = path.toAbsolutePath().normalize();
+ for (Path root : roots) {
+ if (normalized.startsWith(root)) {
+ return normalized;
+ }
+ }
+ return null;
+ }
+
+ private static Optional<JobPolicy> outsideWorkRoots(Path path) {
+ log.warn("LibreOffice job path {} is outside the temp dirs; not granting it", path);
+ return Optional.empty();
+ }
+
+ /**
+ * Copies the extension registry of {@code template}, a profile the init script makes with an
+ * init-only soffice run before any document is opened, into {@code profile} when it has no user
+ * layer yet. Without it a fresh profile makes soffice exit with its restart code and relaunch
+ * under the same IPC pipe name; the relaunch cannot unlink the first pipe on the socket-only
+ * /tmp and exits 1. Only the registry is copied: it is all that stops the relaunch, and nothing
+ * a conversion writes to its own profile reaches the next job.
+ */
+ static void seedProfile(Path profile, Path template) {
+ if (template == null || Files.exists(profile.resolve("user"))) {
+ return;
+ }
+ Path extensions = template.resolve("user").resolve("extensions");
+ if (!Files.isDirectory(extensions, LinkOption.NOFOLLOW_LINKS)) {
+ return;
+ }
+ try {
+ copyTree(extensions, profile.resolve("user").resolve("extensions"));
+ } catch (IOException e) {
+ log.debug("Cannot seed LibreOffice profile {}: {}", profile, e.getMessage());
+ }
+ }
+
+ private static void copyTree(Path from, Path to) throws IOException {
+ try (var paths = Files.walk(from)) {
+ for (Path source : (Iterable<Path>) paths::iterator) {
+ Path target = to.resolve(from.relativize(source).toString());
+ if (Files.isDirectory(source, LinkOption.NOFOLLOW_LINKS)) {
+ Files.createDirectories(target);
+ } else if (Files.isRegularFile(source, LinkOption.NOFOLLOW_LINKS)) {
+ Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
+ }
+ }
+ }
+ }
+
+ /**
+ * True when {@code profile} has no initialised user layer, so soffice will initialise it and
+ * relaunch on this run. Only such a run leaves the unbindable IPC pipe the retry handles, so
+ * the caller gates its retry on this rather than on the shared /tmp sweep, which under parallel
+ * load reports pipes other jobs left behind.
+ */
+ static boolean isProfileUninitialised(Path profile) {
+ return !Files.exists(profile.resolve("user"));
+ }
+
+ /** IPC pipe files present before a run, so only the run's own leftovers are removed. */
+ static Set<Path> snapshotIpcPipes(Path dir) {
+ Set<Path> pipes = new HashSet<>();
+ try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, IPC_PIPE_PREFIX + "*")) {
+ stream.forEach(pipes::add);
+ } catch (IOException e) {
+ log.debug("Cannot list {}: {}", dir, e.getMessage());
+ }
+ return pipes;
+ }
+
+ /**
+ * Removes IPC pipes a sandboxed soffice created but could not unlink, which it is denied on the
+ * socket-only /tmp, and reports whether any were found. Pipes still bound in {@code
+ * /proc/net/unix} belong to a live instance and are kept.
+ */
+ static boolean removeLeftoverIpcPipes(Path dir, Set<Path> before) {
+ Set<Path> created = snapshotIpcPipes(dir);
+ created.removeAll(before);
+ if (created.isEmpty()) {
+ return false;
+ }
+ boolean removed = false;
+ Set<String> bound = readBoundUnixSocketPaths();
+ for (Path pipe : created) {
+ if (bound.contains(pipe.toString()) || !isSocket(pipe)) {
+ continue;
+ }
+ try {
+ removed |= Files.deleteIfExists(pipe);
+ } catch (IOException e) {
+ log.debug("Cannot remove LibreOffice IPC pipe {}: {}", pipe, e.getMessage());
+ }
+ }
+ return removed;
+ }
+
+ /** Paths of bound UNIX sockets: the last column of each {@code /proc/net/unix} row. */
+ private static Set<String> readBoundUnixSocketPaths() {
+ Set<String> paths = new HashSet<>();
+ try {
+ for (String line :
+ Files.readAllLines(Path.of("/proc/net/unix"), StandardCharsets.UTF_8)) {
+ String[] columns = line.trim().split("\\s+");
+ if (columns.length >= 8 && columns[columns.length - 1].startsWith("/")) {
+ paths.add(columns[columns.length - 1]);
+ }
+ }
+ } catch (IOException e) {
+ log.debug("Cannot read /proc/net/unix: {}", e.getMessage());
+ }
+ return paths;
+ }
+
+ private static boolean isSocket(Path path) {
+ try {
+ return Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS)
+ .isOther();
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ private static Path toPath(String value) {
+ try {
+ return value.startsWith("file:") ? Path.of(URI.create(value)) : Path.of(value);
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ private static boolean listable(Path profile, Path outDir, List<Path> inputs) {
+ if (profile.toString().contains(":") || outDir.toString().contains(":")) {
+ return false;
+ }
+ return inputs.stream().noneMatch(p -> p.toString().contains(":"));
+ }
+
+ private static String join(List<Path> paths) {
+ return String.join(":", paths.stream().map(Path::toString).toList());
+ }
+}
diff --git a/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java b/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java
index 24f9bee709..0e278b780e 100644
--- a/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java
+++ b/app/common/src/main/java/stirling/software/common/util/ProcessExecutor.java
@@ -7,8 +7,10 @@ import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
+import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -31,6 +33,15 @@ public class ProcessExecutor {
private static final Map<Processes, ProcessExecutor> instances = new ConcurrentHashMap<>();
private static ApplicationProperties applicationProperties = new ApplicationProperties();
private static volatile UnoServerPool unoServerPool;
+ private static volatile List<Path> libreOfficeWorkRoots = workRoots(List.of());
+
+ // Installed only in the Docker image (docker/base/lo-sandbox.c), where LibreOffice runs as its
+ // own user under a policy read from the environment; bare installs launch it unchanged.
+ private static volatile boolean libreOfficeSandboxed =
+ Files.isExecutable(Path.of("/usr/local/lib/stirling/lo-sandbox"));
+
+ // Made by the init script (create_office_profile_template in init-without-ocr.sh).
+ private static final Path libreOfficeProfileTemplate = profileTemplateFromEnvironment();
private final Semaphore semaphore;
private final boolean liveUpdates;
private long timeoutDuration;
@@ -190,6 +201,47 @@ public class ProcessExecutor {
unoServerPool = pool;
}
+ static void setLibreOfficeSandboxed(boolean sandboxed) {
+ libreOfficeSandboxed = sandboxed;
+ }
+
+ private static Path profileTemplateFromEnvironment() {
+ String template = System.getenv("STIRLING_LO_PROFILE_TEMPLATE");
+ if (template == null || template.isBlank()) {
+ return null;
+ }
+ try {
+ return Path.of(template);
+ } catch (InvalidPathException e) {
+ return null;
+ }
+ }
+
+ /**
+ * Dirs a direct soffice job's profile, output dir and inputs must lie within for it to get a
+ * per-job sandbox policy. java.io.tmpdir is always included; blank or invalid entries are
+ * ignored.
+ */
+ public static void setLibreOfficeWorkRoots(Collection<String> dirs) {
+ libreOfficeWorkRoots = workRoots(dirs);
+ }
+
+ private static List<Path> workRoots(Collection<String> dirs) {
+ List<Path> roots = new ArrayList<>();
+ roots.add(Path.of(System.getProperty("java.io.tmpdir")).toAbsolutePath().normalize());
+ for (String dir : dirs) {
+ if (dir == null || dir.isBlank()) {
+ continue;
+ }
+ try {
+ roots.add(Path.of(dir).toAbsolutePath().normalize());
+ } catch (InvalidPathException e) {
+ log.warn("Ignoring invalid LibreOffice work dir {}: {}", dir, e.getMessage());
+ }
+ }
+ return List.copyOf(roots);
+ }
+
public ProcessExecutorResult runCommandWithOutputHandling(List<String> command)
throws IOException, InterruptedException {
return runCommandWithOutputHandling(command, null);
@@ -197,11 +249,41 @@ public class ProcessExecutor {
public ProcessExecutorResult runCommandWithOutputHandling(
List<String> command, File workingDirectory) throws IOException, InterruptedException {
+ RunOutcome outcome = new RunOutcome();
+ try {
+ return runOnce(command, workingDirectory, outcome);
+ } catch (IOException e) {
+ // A fresh profile makes soffice initialise it, relaunch under the IPC pipe the sandbox
+ // would not let it unlink, and exit 1; with the profile now initialised, one more run
+ // does not relaunch. Gated on this job's own profile, not on its pipe sweep finding the
+ // dead pipe: another job's sweep, or the init script's, may have removed it first.
+ if (outcome.freshProfile == null
+ || outcome.timedOut
+ || LibreOfficeSandboxPolicy.isProfileUninitialised(outcome.freshProfile)) {
+ throw e;
+ }
+ log.info("Retrying LibreOffice now its fresh profile is initialised");
+ return runOnce(command, workingDirectory, new RunOutcome());
+ }
+ }
+
+ private static final class RunOutcome {
+ /** The job's profile when it had no user layer before this run, else null. */
+ Path freshProfile;
+
+ boolean timedOut;
+ }
+
+ private ProcessExecutorResult runOnce(
+ List<String> command, File workingDirectory, RunOutcome outcome)
+ throws IOException, InterruptedException {
String messages = "";
int exitCode = 1;
UnoServerPool.UnoServerLease unoLease = null;
boolean useSemaphore = true;
List<String> commandToRun = command;
+ Set<Path> ipcPipesBefore = null;
+ LibreOfficeSandboxPolicy.JobPolicy jobPolicy = null;
boolean useUnoServerPool = shouldUseUnoServerPool(command);
@@ -238,6 +320,23 @@ public class ProcessExecutor {
validateCommand(commandToRun);
log.info("Running command: {}", String.join(" ", commandToRun));
ProcessBuilder processBuilder = new ProcessBuilder(commandToRun);
+ scrubEnvironment(processBuilder);
+ if (processType == Processes.LIBRE_OFFICE && libreOfficeSandboxed) {
+ jobPolicy =
+ LibreOfficeSandboxPolicy.forCommand(commandToRun, libreOfficeWorkRoots)
+ .orElse(null);
+ if (jobPolicy != null) {
+ processBuilder.environment().putAll(jobPolicy.env());
+ LibreOfficeSandboxPolicy.seedProfile(
+ jobPolicy.profile(), libreOfficeProfileTemplate);
+ if (LibreOfficeSandboxPolicy.isProfileUninitialised(jobPolicy.profile())) {
+ outcome.freshProfile = jobPolicy.profile();
+ }
+ ipcPipesBefore =
+ LibreOfficeSandboxPolicy.snapshotIpcPipes(
+ Path.of(LibreOfficeSandboxPolicy.IPC_PIPE_DIR));
+ }
+ }
// Use the working directory if it's set
if (workingDirectory != null) {
@@ -348,6 +447,7 @@ public class ProcessExecutor {
// Interrupt the reader threads
errorReaderThread.interrupt();
outputReaderThread.interrupt();
+ outcome.timedOut = true;
throw new IOException("Process timeout exceeded.");
}
exitCode = process.exitValue();
@@ -399,6 +499,10 @@ public class ProcessExecutor {
}
}
} finally {
+ if (ipcPipesBefore != null) {
+ LibreOfficeSandboxPolicy.removeLeftoverIpcPipes(
+ Path.of(LibreOfficeSandboxPolicy.IPC_PIPE_DIR), ipcPipesBefore);
+ }
if (useSemaphore) {
semaphore.release();
}
@@ -409,6 +513,71 @@ public class ProcessExecutor {
return new ProcessExecutorResult(exitCode, messages);
}
+ private static final Set<String> LIBRE_OFFICE_ENV_ALLOWLIST =
+ Set.of(
+ "HOME",
+ "USER",
+ "LOGNAME",
+ "PATH",
+ "SHELL",
+ "PWD",
+ "TMPDIR",
+ "TMP",
+ "LANG",
+ "LANGUAGE",
+ "TZ",
+ "TERM",
+ "HOSTNAME",
+ "DISPLAY",
+ "XDG_RUNTIME_DIR",
+ "XDG_CACHE_HOME",
+ "XDG_CONFIG_HOME",
+ "XDG_DATA_HOME",
+ "LD_LIBRARY_PATH",
+ "JAVA_HOME",
+ "FONTCONFIG_PATH",
+ "FONTCONFIG_FILE",
+ "DBUS_SESSION_BUS_ADDRESS",
+ "MALLOC_ARENA_MAX",
+ "PYTHONIOENCODING",
+ "PYTHONUNBUFFERED");
+
+ private static final List<String> LIBRE_OFFICE_ENV_ALLOWED_PREFIXES =
+ List.of("LC_", "SAL_", "OOO_", "UNO_", "URE_", "OFFICE_", "STIRLING_LO_");
+
+ private static boolean isLoopbackHost(String host) {
+ if (host == null) {
+ return false;
+ }
+ String normalized = host.trim().toLowerCase(java.util.Locale.ROOT);
+ return "127.0.0.1".equals(normalized)
+ || "localhost".equals(normalized)
+ || "::1".equals(normalized)
+ || "[::1]".equals(normalized);
+ }
+
+ private void scrubEnvironment(ProcessBuilder processBuilder) {
+ if (processType != Processes.LIBRE_OFFICE || !libreOfficeSandboxed) {
+ return;
+ }
+ processBuilder.environment().keySet().removeIf(name -> !isLibreOfficeEnvAllowed(name));
+ }
+
+ private static boolean isLibreOfficeEnvAllowed(String name) {
+ if (name == null) {
+ return false;
+ }
+ if (LIBRE_OFFICE_ENV_ALLOWLIST.contains(name)) {
+ return true;
+ }
+ for (String prefix : LIBRE_OFFICE_ENV_ALLOWED_PREFIXES) {
+ if (name.startsWith(prefix)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
private boolean shouldUseUnoServerPool(List<String> command) {
if (processType != Processes.LIBRE_OFFICE || unoServerPool == null) {
return false;
@@ -466,8 +635,10 @@ public class ProcessExecutor {
}
// Normalize and validate hostLocation (only auto|local|remote allowed)
- if (hostLocation == null) {
- hostLocation = "auto";
+ if (hostLocation == null
+ || hostLocation.isBlank()
+ || "auto".equalsIgnoreCase(hostLocation)) {
+ hostLocation = libreOfficeSandboxed && isLoopbackHost(host) ? "remote" : "auto";
} else {
hostLocation = hostLocation.trim().toLowerCase(java.util.Locale.ROOT);
if (!Set.of("auto", "local", "remote").contains(hostLocation)) {
diff --git a/app/common/src/test/java/stirling/software/common/configuration/RuntimePathConfigTest.java b/app/common/src/test/java/stirling/software/common/configuration/RuntimePathConfigTest.java
index f3e0490b14..5bec207b61 100644
--- a/app/common/src/test/java/stirling/software/common/configuration/RuntimePathConfigTest.java
+++ b/app/common/src/test/java/stirling/software/common/configuration/RuntimePathConfigTest.java
@@ -19,6 +19,7 @@ import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.ApplicationProperties.CustomPaths.Operations;
import stirling.software.common.model.ApplicationProperties.CustomPaths.Pipeline;
import stirling.software.common.model.ApplicationProperties.ProcessExecutor.UnoServerEndpoint;
+import stirling.software.common.util.UnoServerPool;
/**
* Unit tests for {@link RuntimePathConfig}. All of the resolution logic lives in the constructor,
@@ -394,6 +395,16 @@ class RuntimePathConfigTest {
}
}
+ @Test
+ @DisplayName("Auto endpoints count as local, so conversions wake the on-demand pool")
+ void autoEndpointsAreLocalForTheDemandManager() {
+ RuntimePathConfig config = build(newProperties());
+
+ UnoServerPool pool = new UnoServerPool(config.getUnoServerEndpoints());
+
+ assertTrue(pool.hasLocalEndpoints());
+ }
+
@Test
@DisplayName("Manual mode returns the configured (valid) endpoints")
void manualEndpointsAreUsed() {
diff --git a/app/common/src/test/java/stirling/software/common/util/LibreOfficeSandboxPolicyTest.java b/app/common/src/test/java/stirling/software/common/util/LibreOfficeSandboxPolicyTest.java
new file mode 100644
index 0000000000..41114c1271
--- /dev/null
+++ b/app/common/src/test/java/stirling/software/common/util/LibreOfficeSandboxPolicyTest.java
@@ -0,0 +1,224 @@
+package stirling.software.common.util;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import java.io.IOException;
+import java.net.StandardProtocolFamily;
+import java.net.UnixDomainSocketAddress;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledOnOs;
+import org.junit.jupiter.api.condition.OS;
+import org.junit.jupiter.api.io.TempDir;
+
+class LibreOfficeSandboxPolicyTest {
+
+ @TempDir Path tmp;
+
+ private List<Path> roots() {
+ return List.of(tmp);
+ }
+
+ private List<String> sofficeCommand(Path profile, Path outDir, Path input) {
+ return List.of(
+ "/usr/bin/soffice",
+ "-env:UserInstallation=" + profile.toUri(),
+ "--headless",
+ "--nologo",
+ "--convert-to",
+ "pdf:writer_pdf_Export:{\"SelectPdfVersion\":{\"type\":\"long\",\"value\":\"2\"}}",
+ "--outdir",
+ outDir.toString(),
+ input.toString());
+ }
+
+ @Test
+ void confinesDirectConversionToItsOwnFiles() throws IOException {
+ Path profile = tmp.resolve("libreoffice_profile_1");
+ Path outDir = tmp.resolve("output_1");
+ Path input = Files.writeString(tmp.resolve("in.docx"), "x");
+
+ LibreOfficeSandboxPolicy.JobPolicy policy =
+ LibreOfficeSandboxPolicy.forCommand(sofficeCommand(profile, outDir, input), roots())
+ .orElseThrow();
+ Map<String, String> env = policy.env();
+
+ assertEquals(profile, policy.profile());
+
+ assertEquals(profile + ":" + outDir + ":/dev", env.get("STIRLING_LO_ALLOW_RW"));
+ assertEquals(input.toString(), env.get("STIRLING_LO_ALLOW_RO_EXTRA"));
+ assertEquals("/tmp", env.get("STIRLING_LO_ALLOW_SOCK"));
+ assertEquals(profile.toString(), env.get("HOME"));
+ for (String name : List.of("TMPDIR", "TMP", "TEMP", "SAL_TMP", "XDG_RUNTIME_DIR")) {
+ assertEquals(profile.resolve("tmp").toString(), env.get(name), name);
+ }
+ assertTrue(Files.isDirectory(profile.resolve("tmp")));
+ assertTrue(Files.isDirectory(outDir));
+ }
+
+ @Test
+ void convertToFilterValueIsNotTreatedAsInput() throws IOException {
+ Path input = Files.writeString(tmp.resolve("in.pdf"), "x");
+ Files.writeString(tmp.resolve("pdf"), "decoy");
+
+ Map<String, String> env =
+ LibreOfficeSandboxPolicy.forCommand(
+ List.of(
+ "soffice",
+ "-env:UserInstallation=" + tmp.resolve("p").toUri(),
+ "--convert-to",
+ tmp.resolve("pdf").toString(),
+ "--outdir",
+ tmp.resolve("o").toString(),
+ input.toString()),
+ roots())
+ .orElseThrow()
+ .env();
+
+ assertEquals(input.toString(), env.get("STIRLING_LO_ALLOW_RO_EXTRA"));
+ }
+
+ @Test
+ void unoconvertCommandIsLeftToSharedPolicy() {
+ assertEquals(
+ Optional.empty(),
+ LibreOfficeSandboxPolicy.forCommand(
+ List.of(
+ "unoconvert",
+ "--host-location",
+ "remote",
+ "--convert-to",
+ "pdf",
+ "/tmp/a.docx",
+ "/tmp/a.pdf"),
+ roots()));
+ }
+
+ @Test
+ void commandWithoutOutdirIsLeftToSharedPolicy() {
+ assertEquals(
+ Optional.empty(),
+ LibreOfficeSandboxPolicy.forCommand(
+ List.of(
+ "soffice",
+ "-env:UserInstallation=" + tmp.resolve("p").toUri(),
+ "--convert-to",
+ "pdf",
+ "in.docx"),
+ roots()));
+ }
+
+ @Test
+ void pathWithListSeparatorIsLeftToSharedPolicy() throws IOException {
+ Path odd = Files.createDirectories(tmp.resolve("a:b"));
+ Path input = Files.writeString(tmp.resolve("in.docx"), "x");
+
+ assertEquals(
+ Optional.empty(),
+ LibreOfficeSandboxPolicy.forCommand(
+ sofficeCommand(odd.resolve("profile"), tmp.resolve("out"), input),
+ roots()));
+ }
+
+ @Test
+ void pathsOutsideTheWorkRootsAreNotGranted() throws IOException {
+ Path root = Files.createDirectories(tmp.resolve("work"));
+ Path outside = Files.createDirectories(tmp.resolve("elsewhere"));
+ Path input = Files.writeString(root.resolve("in.docx"), "x");
+ Path outsideInput = Files.writeString(outside.resolve("secret.docx"), "x");
+ List<Path> roots = List.of(root);
+
+ assertTrue(
+ LibreOfficeSandboxPolicy.forCommand(
+ sofficeCommand(root.resolve("p"), root.resolve("o"), input), roots)
+ .isPresent());
+ assertEquals(
+ Optional.empty(),
+ LibreOfficeSandboxPolicy.forCommand(
+ sofficeCommand(outside.resolve("p"), root.resolve("o"), input), roots));
+ assertEquals(
+ Optional.empty(),
+ LibreOfficeSandboxPolicy.forCommand(
+ sofficeCommand(root.resolve("p"), root.resolve("../elsewhere/o"), input),
+ roots));
+ assertEquals(
+ Optional.empty(),
+ LibreOfficeSandboxPolicy.forCommand(
+ sofficeCommand(root.resolve("p"), root.resolve("o"), outsideInput), roots));
+ }
+
+ @Test
+ void seedsOnlyTheExtensionRegistryIntoFreshProfiles() throws IOException {
+ Path template = tmp.resolve("template");
+ Files.createDirectories(template.resolve("user/extensions/bundled"));
+ Files.writeString(template.resolve("user/extensions/buildid"), "build-1");
+ Files.createDirectories(template.resolve("user/basic/Standard"));
+ Files.writeString(template.resolve("user/basic/Standard/Module1.xba"), "macro");
+ Files.writeString(template.resolve("user/registrymodifications.xcu"), "<items/>");
+
+ Path fresh = tmp.resolve("profile_b");
+ LibreOfficeSandboxPolicy.seedProfile(fresh, template);
+
+ assertEquals("build-1", Files.readString(fresh.resolve("user/extensions/buildid")));
+ assertTrue(Files.isDirectory(fresh.resolve("user/extensions/bundled")));
+ assertFalse(Files.exists(fresh.resolve("user/basic")), "macros are not templated");
+ assertFalse(Files.exists(fresh.resolve("user/registrymodifications.xcu")));
+
+ Path existing = tmp.resolve("profile_c");
+ Files.createDirectories(existing.resolve("user"));
+ LibreOfficeSandboxPolicy.seedProfile(existing, template);
+ assertFalse(Files.exists(existing.resolve("user/extensions")));
+
+ Path unseeded = tmp.resolve("profile_d");
+ LibreOfficeSandboxPolicy.seedProfile(unseeded, tmp.resolve("missing-template"));
+ LibreOfficeSandboxPolicy.seedProfile(unseeded, null);
+ assertFalse(Files.exists(unseeded));
+ }
+
+ @Test
+ void reportsWhetherProfileIsUninitialised() throws IOException {
+ Path fresh = tmp.resolve("fresh");
+ Files.createDirectories(fresh);
+ assertTrue(LibreOfficeSandboxPolicy.isProfileUninitialised(fresh));
+
+ Files.createDirectories(fresh.resolve("user"));
+ assertFalse(LibreOfficeSandboxPolicy.isProfileUninitialised(fresh));
+ }
+
+ @Test
+ @EnabledOnOs(OS.LINUX)
+ void removesOnlyUnboundPipesCreatedDuringTheRun() throws IOException {
+ Path preexisting = Files.writeString(tmp.resolve("OSL_PIPE_1000_old"), "");
+ Set<Path> before = LibreOfficeSandboxPolicy.snapshotIpcPipes(tmp);
+
+ Path stale = tmp.resolve("OSL_PIPE_1000_SingleOfficeIPC_stale");
+ Path live = tmp.resolve("OSL_PIPE_1000_SingleOfficeIPC_live");
+ Path regular = Files.writeString(tmp.resolve("OSL_PIPE_1000_notasocket"), "");
+ try (ServerSocketChannel staleChannel =
+ ServerSocketChannel.open(StandardProtocolFamily.UNIX);
+ ServerSocketChannel liveChannel =
+ ServerSocketChannel.open(StandardProtocolFamily.UNIX)) {
+ staleChannel.bind(UnixDomainSocketAddress.of(stale));
+ liveChannel.bind(UnixDomainSocketAddress.of(live));
+ staleChannel.close();
+ assertTrue(Files.exists(stale), "closing a bound channel leaves its file behind");
+
+ assertTrue(LibreOfficeSandboxPolicy.removeLeftoverIpcPipes(tmp, before));
+
+ assertFalse(Files.exists(stale));
+ assertTrue(Files.exists(live), "a pipe still bound belongs to a running instance");
+ }
+ assertTrue(Files.exists(preexisting));
+ assertTrue(Files.exists(regular));
+ assertFalse(
+ LibreOfficeSandboxPolicy.removeLeftoverIpcPipes(
+ tmp, LibreOfficeSandboxPolicy.snapshotIpcPipes(tmp)));
+ }
+}
diff --git a/app/common/src/test/java/stirling/software/common/util/ProcessExecutorGapTest.java b/app/common/src/test/java/stirling/software/common/util/ProcessExecutorGapTest.java
index 961ae0b6cb..e7a374128f 100644
--- a/app/common/src/test/java/stirling/software/common/util/ProcessExecutorGapTest.java
+++ b/app/common/src/test/java/stirling/software/common/util/ProcessExecutorGapTest.java
@@ -83,6 +83,7 @@ class ProcessExecutorGapTest {
@AfterEach
void resetUnoServerPool() {
ProcessExecutor.setUnoServerPool(null);
+ ProcessExecutor.setLibreOfficeSandboxed(false);
}
// ----- validateCommand deeper branches -----------------------------------
@@ -290,17 +291,51 @@ class ProcessExecutorGapTest {
}
@Test
- @DisplayName("blank host falls back to 127.0.0.1 and non-positive port falls back to 2003")
+ @DisplayName(
+ "blank host falls back to loopback, which forces byte transport when sandboxed")
void appliesHostAndPortFallbacks() throws Exception {
+ ProcessExecutor.setLibreOfficeSandboxed(true);
List<String> command = List.of("unoconvert", "in.docx");
ApplicationProperties.ProcessExecutor.UnoServerEndpoint ep =
endpoint(" ", 0, "auto", "http");
List<String> result = invokeApplyUnoServerEndpoint(qpdfExecutor(), command, ep);
+ assertEquals(
+ List.of(
+ "unoconvert",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ "2003",
+ "--host-location",
+ "remote",
+ "in.docx"),
+ result);
+ }
+
+ @Test
+ @DisplayName("without the sandbox a loopback endpoint keeps unoconvert's own transport")
+ void loopbackStaysAutoWithoutSandbox() throws Exception {
+ List<String> command = List.of("unoconvert", "in.docx");
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint ep =
+ endpoint("127.0.0.1", 2003, "auto", "http");
+ List<String> result = invokeApplyUnoServerEndpoint(qpdfExecutor(), command, ep);
assertEquals(
List.of("unoconvert", "--host", "127.0.0.1", "--port", "2003", "in.docx"),
result);
}
+ @Test
+ @DisplayName("auto host-location on a non-loopback host stays auto")
+ void autoHostLocationRemainsForRemoteHost() throws Exception {
+ List<String> command = List.of("unoconvert", "in.docx");
+ ApplicationProperties.ProcessExecutor.UnoServerEndpoint ep =
+ endpoint("uno.internal", 2003, "auto", "http");
+ List<String> result = invokeApplyUnoServerEndpoint(qpdfExecutor(), command, ep);
+ assertEquals(
+ List.of("unoconvert", "--host", "uno.internal", "--port", "2003", "in.docx"),
+ result);
+ }
+
@Test
@DisplayName("invalid host-location and protocol values are normalised to defaults")
void invalidHostLocationAndProtocolNormalised() throws Exception {
diff --git a/app/common/src/test/java/stirling/software/common/util/ProcessExecutorLibreOfficeRetryTest.java b/app/common/src/test/java/stirling/software/common/util/ProcessExecutorLibreOfficeRetryTest.java
new file mode 100644
index 0000000000..4e0df21116
--- /dev/null
+++ b/app/common/src/test/java/stirling/software/common/util/ProcessExecutorLibreOfficeRetryTest.java
@@ -0,0 +1,138 @@
+package stirling.software.common.util;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Stream;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.mockito.MockedConstruction;
+import org.mockito.Mockito;
+
+import stirling.software.common.util.ProcessExecutor.ProcessExecutorResult;
+
+class ProcessExecutorLibreOfficeRetryTest {
+
+ @TempDir Path tmp;
+
+ private Path profile;
+ private List<String> command;
+
+ @BeforeEach
+ void runAsInTheDockerImage() {
+ ProcessExecutor.setLibreOfficeSandboxed(true);
+ }
+
+ @AfterEach
+ void restoreBareInstall() {
+ ProcessExecutor.setLibreOfficeSandboxed(false);
+ }
+
+ private void prepareCommand() throws IOException {
+ profile = tmp.resolve("libreoffice_profile_job");
+ Path outDir = tmp.resolve("out");
+ Path input = Files.writeString(tmp.resolve("in.docx"), "x");
+ command =
+ List.of(
+ "soffice",
+ "-env:UserInstallation=" + profile.toUri(),
+ "--headless",
+ "--convert-to",
+ "pdf",
+ "--outdir",
+ outDir.toString(),
+ input.toString());
+ }
+
+ private static Process process(boolean finished, int exitCode) throws InterruptedException {
+ Process process = mock(Process.class);
+ when(process.getInputStream()).thenReturn(new ByteArrayInputStream(new byte[0]));
+ when(process.getErrorStream()).thenReturn(new ByteArrayInputStream(new byte[0]));
+ when(process.waitFor(anyLong(), any(TimeUnit.class))).thenReturn(finished);
+ when(process.exitValue()).thenReturn(exitCode);
+ when(process.descendants()).thenReturn(Stream.empty());
+ return process;
+ }
+
+ /**
+ * Stands in for soffice: the first launch initialises the profile the way a real first start
+ * does and then fails with the relaunch's exit code; later launches exit with {@code
+ * laterExitCode}.
+ */
+ private MockedConstruction<ProcessBuilder> soffice(
+ AtomicInteger launches, boolean firstFinishes, int laterExitCode) {
+ return Mockito.mockConstruction(
+ ProcessBuilder.class,
+ (builder, context) -> {
+ when(builder.environment()).thenReturn(new HashMap<>());
+ when(builder.directory(any())).thenReturn(builder);
+ when(builder.start())
+ .thenAnswer(
+ invocation -> {
+ if (launches.getAndIncrement() == 0) {
+ Files.createDirectories(profile.resolve("user"));
+ return process(firstFinishes, 1);
+ }
+ return process(true, laterExitCode);
+ });
+ });
+ }
+
+ private ProcessExecutor libreOffice() {
+ return ProcessExecutor.getInstance(ProcessExecutor.Processes.LIBRE_OFFICE);
+ }
+
+ @Test
+ void freshProfileIsRetriedOnceItHasBeenInitialised() throws Exception {
+ prepareCommand();
+ AtomicInteger launches = new AtomicInteger();
+
+ try (MockedConstruction<ProcessBuilder> ignored = soffice(launches, true, 0)) {
+ ProcessExecutorResult result = libreOffice().runCommandWithOutputHandling(command);
+
+ assertThat(result.getRc()).isZero();
+ }
+ assertThat(launches).hasValue(2);
+ }
+
+ @Test
+ void failureOnAnAlreadyInitialisedProfileIsNotRetried() throws Exception {
+ prepareCommand();
+ Files.createDirectories(profile.resolve("user"));
+ AtomicInteger launches = new AtomicInteger();
+
+ try (MockedConstruction<ProcessBuilder> ignored = soffice(launches, true, 0)) {
+ assertThatThrownBy(() -> libreOffice().runCommandWithOutputHandling(command))
+ .isInstanceOf(IOException.class);
+ }
+ assertThat(launches).hasValue(1);
+ }
+
+ @Test
+ void timedOutRunIsNotRetried() throws Exception {
+ prepareCommand();
+ AtomicInteger launches = new AtomicInteger();
+
+ try (MockedConstruction<ProcessBuilder> ignored = soffice(launches, false, 0)) {
+ assertThatThrownBy(() -> libreOffice().runCommandWithOutputHandling(command))
+ .isInstanceOf(IOException.class)
+ .hasMessageContaining("timeout");
+ }
+ assertThat(launches).hasValue(1);
+ }
+}
diff --git a/app/core/src/main/java/stirling/software/SPDF/LibreOfficeListener.java b/app/core/src/main/java/stirling/software/SPDF/LibreOfficeListener.java
deleted file mode 100644
index 78abea7ffd..0000000000
--- a/app/core/src/main/java/stirling/software/SPDF/LibreOfficeListener.java
+++ /dev/null
@@ -1,99 +0,0 @@
-package stirling.software.SPDF;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-import io.github.pixee.security.SystemCommand;
-
-import lombok.extern.slf4j.Slf4j;
-
-@Slf4j
-public class LibreOfficeListener {
-
- private static final long ACTIVITY_TIMEOUT = 20L * 60 * 1000; // 20 minutes
-
- private static final LibreOfficeListener INSTANCE = new LibreOfficeListener();
- private static final int LISTENER_PORT = 2002;
- private ExecutorService executorService;
- private long lastActivityTime;
- private Process process;
-
- private LibreOfficeListener() {}
-
- public static LibreOfficeListener getInstance() {
- return INSTANCE;
- }
-
- private boolean isListenerRunning() {
- log.info("waiting for listener to start");
- try (Socket socket = new Socket()) {
- socket.connect(
- new InetSocketAddress("localhost", LISTENER_PORT),
- 1000); // Timeout after 1 second
- return true;
- } catch (Exception e) {
- return false;
- }
- }
-
- public void start() throws IOException {
- // Check if the listener is already running
- if (process != null && process.isAlive()) {
- return;
- }
-
- // Start the listener process
- process = SystemCommand.runCommand(Runtime.getRuntime(), "unoconv --listener");
- lastActivityTime = System.currentTimeMillis();
-
- // Start a virtual thread to monitor the activity timeout
- executorService = Executors.newVirtualThreadPerTaskExecutor();
- executorService.submit(
- () -> {
- while (true) {
- long idleTime = System.currentTimeMillis() - lastActivityTime;
- if (idleTime >= ACTIVITY_TIMEOUT) {
- // If there has been no activity for too long, tear down the listener
- process.destroy();
- break;
- }
- try {
- Thread.sleep(5000); // Check for inactivity every 5 seconds
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- break;
- }
- }
- });
-
- // Wait for the listener to start up
- long startTime = System.currentTimeMillis();
- long timeout = 30000; // Timeout after 30 seconds
- while (System.currentTimeMillis() - startTime < timeout) {
- if (isListenerRunning()) {
-
- lastActivityTime = System.currentTimeMillis();
- return;
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- log.error("exception", e);
- } // Check every 1 second
- }
- }
-
- public synchronized void stop() {
- // Stop the activity timeout monitor thread
- executorService.shutdownNow();
-
- // Stop the listener process
- if (process != null && process.isAlive()) {
- process.destroy();
- }
- }
-}
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java
index 97552000f2..7482791b42 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/converters/ConvertOfficeController.java
@@ -218,8 +218,6 @@ public class ConvertOfficeController {
public ResponseEntity<Resource> processFileToPDF(@ModelAttribute GeneralFile generalFile)
throws Exception {
MultipartFile inputFile = generalFile.getFileInput();
- // unused but can start server instance if startup time is to long
- // LibreOfficeListener.getInstance().start();
File file = null;
TempFile tempOut = null;
try {
diff --git a/app/core/src/test/java/stirling/software/SPDF/LibreOfficeListenerTest.java b/app/core/src/test/java/stirling/software/SPDF/LibreOfficeListenerTest.java
deleted file mode 100644
index 670ecc6748..0000000000
--- a/app/core/src/test/java/stirling/software/SPDF/LibreOfficeListenerTest.java
+++ /dev/null
@@ -1,186 +0,0 @@
-package stirling.software.SPDF;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-
-import java.lang.reflect.Field;
-import java.net.Socket;
-import java.util.concurrent.ExecutorService;
-
-import org.junit.jupiter.api.AfterEach;
-import org.junit.jupiter.api.BeforeEach;
-import org.junit.jupiter.api.DisplayName;
-import org.junit.jupiter.api.Nested;
-import org.junit.jupiter.api.Test;
-import org.mockito.MockedConstruction;
-import org.mockito.MockedStatic;
-import org.mockito.Mockito;
-
-import io.github.pixee.security.SystemCommand;
-
-/**
- * Unit tests for {@link LibreOfficeListener}. The process, socket and SystemCommand boundaries are
- * mocked so no real soffice/unoconv process or network connection is ever created.
- */
-@DisplayName("LibreOfficeListener")
-class LibreOfficeListenerTest {
-
- private LibreOfficeListener listener;
-
- @BeforeEach
- void setUp() {
- listener = LibreOfficeListener.getInstance();
- }
-
- @AfterEach
- void tearDown() throws Exception {
- // Reset the singleton's mutable state so tests stay independent.
- ExecutorService es = readExecutor();
- if (es != null) {
- es.shutdownNow();
- }
- setField("process", null);
- setField("executorService", null);
- }
-
- private void setField(String name, Object value) throws Exception {
- Field f = LibreOfficeListener.class.getDeclaredField(name);
- f.setAccessible(true);
- f.set(listener, value);
- }
-
- private Object readField(String name) throws Exception {
- Field f = LibreOfficeListener.class.getDeclaredField(name);
- f.setAccessible(true);
- return f.get(listener);
- }
-
- private ExecutorService readExecutor() throws Exception {
- return (ExecutorService) readField("executorService");
- }
-
- @Nested
- @DisplayName("getInstance")
- class GetInstance {
-
- @Test
- @DisplayName("always returns the same singleton instance")
- void singletonIsStable() {
- assertThat(LibreOfficeListener.getInstance())
- .isSameAs(LibreOfficeListener.getInstance());
- }
- }
-
- @Nested
- @DisplayName("start")
- class Start {
-
- @Test
- @DisplayName("returns immediately when a live process already exists")
- void alreadyRunningShortCircuits() throws Exception {
- Process alive = Mockito.mock(Process.class);
- Mockito.when(alive.isAlive()).thenReturn(true);
- setField("process", alive);
-
- try (MockedStatic<SystemCommand> sys = Mockito.mockStatic(SystemCommand.class)) {
- listener.start();
-
- // No new process is spawned when one is already alive.
- sys.verifyNoInteractions();
- assertThat(readField("process")).isSameAs(alive);
- assertThat(readExecutor()).isNull();
- }
- }
-
- @Test
- @DisplayName("spawns the listener and returns once the socket connects")
- void spawnsAndDetectsRunningListener() throws Exception {
- Process spawned = Mockito.mock(Process.class);
-
- try (MockedStatic<SystemCommand> sys = Mockito.mockStatic(SystemCommand.class);
- MockedConstruction<Socket> socket = Mockito.mockConstruction(Socket.class)) {
-
- sys.when(() -> SystemCommand.runCommand(any(Runtime.class), anyString()))
- .thenReturn(spawned);
-
- listener.start();
-
- // The spawned process is retained and the monitor executor is created.
- assertThat(readField("process")).isSameAs(spawned);
- assertThat(readExecutor()).isNotNull();
- // A socket was constructed and connected exactly once on the first poll.
- assertThat(socket.constructed()).hasSize(1);
- Mockito.verify(socket.constructed().get(0)).connect(any(), eq(1000));
- sys.verify(
- () ->
- SystemCommand.runCommand(
- any(Runtime.class), eq("unoconv --listener")));
- }
- }
-
- @Test
- @DisplayName("retries until the listener socket becomes reachable")
- void retriesUntilSocketReachable() throws Exception {
- Process spawned = Mockito.mock(Process.class);
-
- // First socket fails to connect, second succeeds; start() should poll twice.
- try (MockedStatic<SystemCommand> sys = Mockito.mockStatic(SystemCommand.class);
- MockedConstruction<Socket> socket =
- Mockito.mockConstruction(
- Socket.class,
- (mock, ctx) -> {
- if (ctx.getCount() == 1) {
- Mockito.doThrow(new java.io.IOException("refused"))
- .when(mock)
- .connect(any(), eq(1000));
- }
- })) {
-
- sys.when(() -> SystemCommand.runCommand(any(Runtime.class), anyString()))
- .thenReturn(spawned);
-
- listener.start();
-
- // At least two sockets were attempted before one connected.
- assertThat(socket.constructed().size()).isGreaterThanOrEqualTo(2);
- }
- }
- }
-
- @Nested
- @DisplayName("stop")
- class Stop {
-
- @Test
- @DisplayName("shuts down the monitor and destroys a live process")
- void destroysLiveProcess() throws Exception {
- Process alive = Mockito.mock(Process.class);
- Mockito.when(alive.isAlive()).thenReturn(true);
- ExecutorService es = Mockito.mock(ExecutorService.class);
- setField("process", alive);
- setField("executorService", es);
-
- listener.stop();
-
- Mockito.verify(es).shutdownNow();
- Mockito.verify(alive).destroy();
- }
-
- @Test
- @DisplayName("does not destroy a process that is already dead")
- void skipsDestroyWhenProcessDead() throws Exception {
- Process dead = Mockito.mock(Process.class);
- Mockito.when(dead.isAlive()).thenReturn(false);
- ExecutorService es = Mockito.mock(ExecutorService.class);
- setField("process", dead);
- setField("executorService", es);
-
- listener.stop();
-
- Mockito.verify(es).shutdownNow();
- Mockito.verify(dead, Mockito.never()).destroy();
- }
- }
-}
diff --git a/docker/backend/Dockerfile b/docker/backend/Dockerfile
index cbacadfb89..c875c4a832 100644
--- a/docker/backend/Dockerfile
+++ b/docker/backend/Dockerfile
@@ -1,6 +1,6 @@
# Stirling-PDF backend-only image — JAR built with -PbuildWithFrontend=false, UI ships separately.
-ARG BASE_VERSION=1.0.2@sha256:c7698687f486707ddef9e0298587ca8b44c4e96185e1bdb0c3d119eb2bf9a82e
+ARG BASE_VERSION=1.0.6@sha256:003c1056474d4f9b8c38d3c8b72c78a7ac51b45e12500f831739a4cbf8803987
ARG BASE_IMAGE=stirlingtools/stirling-pdf-base:${BASE_VERSION}
# Stage 1: Build the Java application (backend only, no frontend)
diff --git a/docker/base/Dockerfile b/docker/base/Dockerfile
index 0c73738214..027fa5bad0 100644
--- a/docker/base/Dockerfile
+++ b/docker/base/Dockerfile
@@ -367,6 +367,17 @@ RUN --mount=type=cache,target=/root/.cache/pip,sharing=locked \
find /opt/venv -name '*.so' -exec strip --strip-unneeded {} + 2>/dev/null || true
+FROM ubuntu:noble@sha256:33ceb71981b602c1a7443a53469e4dba065f7503eab3078a2d7a57a2ab987517 AS lo-sandbox-build
+
+RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
+ apt-get update && apt-get install -y --no-install-recommends gcc libc6-dev && \
+ rm -rf /var/lib/apt/lists/*
+
+COPY lo-sandbox.c /src/lo-sandbox.c
+RUN gcc -O2 -Wall -Wextra -Werror -o /usr/local/bin/lo-sandbox /src/lo-sandbox.c && \
+ strip --strip-unneeded /usr/local/bin/lo-sandbox
+
+
# Final runtime image - the actual base image
FROM eclipse-temurin:25-jre-noble@sha256:b4c93a50fc67612798db73d68ca3b0ee4ebdd51736e59cca370e689b9797037e AS runtime
@@ -630,6 +641,22 @@ RUN set -eux; \
-d /home/stirlingpdfuser -s /bin/bash stirlingpdfuser; \
fi
+RUN set -eux; \
+ if ! getent group stirlingofficegroup >/dev/null 2>&1; then \
+ groupadd -g 1100 stirlingofficegroup 2>/dev/null \
+ || groupadd stirlingofficegroup; \
+ fi; \
+ if ! id -u stirlingofficeuser >/dev/null 2>&1; then \
+ useradd -m -u 1100 -g stirlingofficegroup \
+ -d /home/stirlingofficeuser -s /usr/sbin/nologin stirlingofficeuser 2>/dev/null \
+ || useradd -m -g stirlingofficegroup \
+ -d /home/stirlingofficeuser -s /usr/sbin/nologin stirlingofficeuser; \
+ fi; \
+ mkdir -p /var/lib/libreoffice-sandbox; \
+ chown stirlingofficeuser:stirlingofficegroup \
+ /home/stirlingofficeuser /var/lib/libreoffice-sandbox; \
+ chmod 700 /var/lib/libreoffice-sandbox
+
# Application directories
RUN set -eux; \
mkdir -p /configs /configs/cache /configs/heap_dumps /logs /customFiles \
@@ -652,6 +679,25 @@ RUN set -eux; \
ln -sf /opt/venv/bin/unoping /usr/local/bin/unoping; \
fc-cache -f
+COPY --from=lo-sandbox-build /usr/local/bin/lo-sandbox /usr/local/lib/stirling/lo-sandbox
+COPY stirling-hardening.xcd /usr/lib/libreoffice/share/registry/stirling-hardening.xcd
+COPY unoserver-pipe-transport.py /usr/local/lib/stirling/unoserver-pipe-transport.py
+
+RUN set -eux; \
+ chown root:root /usr/local/lib/stirling/lo-sandbox \
+ /usr/lib/libreoffice/share/registry/stirling-hardening.xcd; \
+ chmod 0755 /usr/local/lib/stirling/lo-sandbox; \
+ chmod 0644 /usr/lib/libreoffice/share/registry/stirling-hardening.xcd; \
+ for name in /usr/bin/soffice /usr/bin/libreoffice /usr/bin/ooffice; do \
+ if [ -e "$name" ] || [ -L "$name" ]; then rm -f "$name"; fi; \
+ cp /usr/local/lib/stirling/lo-sandbox "$name"; \
+ chown root:root "$name"; \
+ chmod 0755 "$name"; \
+ done; \
+ /opt/venv/bin/python /usr/local/lib/stirling/unoserver-pipe-transport.py \
+ "$(/opt/venv/bin/python -c 'import unoserver, os; print(os.path.dirname(unoserver.__file__))')"; \
+ STIRLING_LO_SANDBOX=off /usr/bin/soffice --version
+
# Metadata labels - base image
LABEL org.opencontainers.image.title="Stirling-PDF Base" \
org.opencontainers.image.description="Pre-built base image with Calibre, Ghostscript, QPDF, ImageMagick, LibreOffice, OCRmyPDF and dependencies" \
diff --git a/docker/base/lo-sandbox.c b/docker/base/lo-sandbox.c
new file mode 100644
index 0000000000..613cef9108
--- /dev/null
+++ b/docker/base/lo-sandbox.c
@@ -0,0 +1,506 @@
+#define _GNU_SOURCE
+
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/audit.h>
+#include <linux/filter.h>
+#include <linux/seccomp.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/prctl.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+#if defined(__x86_64__)
+#define LO_AUDIT_ARCH AUDIT_ARCH_X86_64
+#elif defined(__aarch64__)
+#define LO_AUDIT_ARCH AUDIT_ARCH_AARCH64
+#else
+#error "unsupported architecture"
+#endif
+
+#ifndef SECCOMP_SET_MODE_FILTER
+#define SECCOMP_SET_MODE_FILTER 1
+#endif
+#ifndef SECCOMP_RET_KILL_PROCESS
+#define SECCOMP_RET_KILL_PROCESS 0x80000000U
+#endif
+
+#ifndef __NR_io_uring_setup
+#define __NR_io_uring_setup 425
+#endif
+#ifndef __NR_io_uring_enter
+#define __NR_io_uring_enter 426
+#endif
+#ifndef __NR_io_uring_register
+#define __NR_io_uring_register 427
+#endif
+#ifndef __NR_landlock_create_ruleset
+#define __NR_landlock_create_ruleset 444
+#endif
+#ifndef __NR_landlock_add_rule
+#define __NR_landlock_add_rule 445
+#endif
+#ifndef __NR_landlock_restrict_self
+#define __NR_landlock_restrict_self 446
+#endif
+
+#ifndef LANDLOCK_CREATE_RULESET_VERSION
+#define LANDLOCK_CREATE_RULESET_VERSION (1U << 0)
+
+struct landlock_ruleset_attr {
+ uint64_t handled_access_fs;
+};
+
+struct landlock_path_beneath_attr {
+ uint64_t allowed_access;
+ int32_t parent_fd;
+} __attribute__((packed));
+
+#define LANDLOCK_RULE_PATH_BENEATH 1
+#endif
+
+#ifndef LANDLOCK_ACCESS_FS_EXECUTE
+#define LANDLOCK_ACCESS_FS_EXECUTE (1ULL << 0)
+#define LANDLOCK_ACCESS_FS_WRITE_FILE (1ULL << 1)
+#define LANDLOCK_ACCESS_FS_READ_FILE (1ULL << 2)
+#define LANDLOCK_ACCESS_FS_READ_DIR (1ULL << 3)
+#define LANDLOCK_ACCESS_FS_REMOVE_DIR (1ULL << 4)
+#define LANDLOCK_ACCESS_FS_REMOVE_FILE (1ULL << 5)
+#define LANDLOCK_ACCESS_FS_MAKE_CHAR (1ULL << 6)
+#define LANDLOCK_ACCESS_FS_MAKE_DIR (1ULL << 7)
+#define LANDLOCK_ACCESS_FS_MAKE_REG (1ULL << 8)
+#define LANDLOCK_ACCESS_FS_MAKE_SOCK (1ULL << 9)
+#define LANDLOCK_ACCESS_FS_MAKE_FIFO (1ULL << 10)
+#define LANDLOCK_ACCESS_FS_MAKE_BLOCK (1ULL << 11)
+#define LANDLOCK_ACCESS_FS_MAKE_SYM (1ULL << 12)
+#endif
+#ifndef LANDLOCK_ACCESS_FS_REFER
+#define LANDLOCK_ACCESS_FS_REFER (1ULL << 13)
+#endif
+#ifndef LANDLOCK_ACCESS_FS_TRUNCATE
+#define LANDLOCK_ACCESS_FS_TRUNCATE (1ULL << 14)
+#endif
+#ifndef LANDLOCK_ACCESS_FS_IOCTL_DEV
+#define LANDLOCK_ACCESS_FS_IOCTL_DEV (1ULL << 15)
+#endif
+
+#define LO_ACCESS_RO \
+ (LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_READ_FILE | \
+ LANDLOCK_ACCESS_FS_READ_DIR)
+
+/* Rights the kernel accepts on a rule whose target is a file rather than a directory. */
+#define LO_ACCESS_FILE \
+ (LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_WRITE_FILE | \
+ LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_TRUNCATE | \
+ LANDLOCK_ACCESS_FS_IOCTL_DEV)
+
+#define LO_ACCESS_NET_BIND_TCP (1ULL << 0)
+#define LO_ACCESS_NET_CONNECT_TCP (1ULL << 1)
+#define LO_SCOPE_ABSTRACT_UNIX_SOCKET (1ULL << 0)
+#define LO_SCOPE_SIGNAL (1ULL << 1)
+
+/* Kernel ABI 4 adds handled_access_net and ABI 6 adds scoped; the size passed to
+ * landlock_create_ruleset tells an older kernel which fields to read. */
+struct lo_ruleset_attr {
+ uint64_t handled_access_fs;
+ uint64_t handled_access_net;
+ uint64_t scoped;
+};
+
+/* Used when STIRLING_LO_ALLOW_RO/RW are unset, so soffice started outside the init
+ * scripts is still confined instead of being denied every path. The read-only list is
+ * what LibreOffice opens across Writer, Calc, Impress, PDF import and PDF/A conversions:
+ * its own install and Ubuntu's /etc and /var links for it, shared libraries, locale,
+ * fonts and fontconfig, poppler's cmaps, time zones, and the few /etc files libc reads.
+ * The launcher script needs /bin/sh, dirname, grep and uname. Entries missing on a given
+ * architecture or image are skipped. */
+#define DEFAULT_RO \
+ "/usr/lib/libreoffice:/etc/libreoffice:/var/lib/libreoffice:" \
+ "/var/spool/libreoffice:/usr/lib/x86_64-linux-gnu:/usr/lib/aarch64-linux-gnu:" \
+ "/usr/lib/locale:/usr/share/fonts:/usr/local/share/fonts:" \
+ "/usr/share/fontconfig:/etc/fonts:/var/cache/fontconfig:/usr/share/poppler:" \
+ "/usr/share/zoneinfo:/usr/share/liblangtag:/usr/share/hyphen:" \
+ "/usr/share/myspell:/etc/ld.so.cache:/etc/passwd:/etc/nsswitch.conf:" \
+ "/etc/locale.alias:/etc/localtime:/bin/sh:/usr/bin/dirname:/usr/bin/grep:" \
+ "/usr/bin/uname:/proc/cpuinfo:/proc/meminfo:/proc/filesystems:" \
+ "/sys/devices/system/cpu"
+#define DEFAULT_RW "/tmp:/dev"
+
+/* Fixed at build time: an exec target read from the environment would let whoever sets it
+ * run any binary through the launcher. */
+#define REAL_SOFFICE "/usr/lib/libreoffice/program/soffice"
+
+/* Applies the sandbox exactly as a launch would, reports what is active and exits instead of
+ * starting LibreOffice, so the init script can check the running kernel. */
+#define SELF_CHECK_FLAG "--stirling-sandbox-check"
+
+/* First Landlock ABI that scopes abstract UNIX sockets and signals to the sandbox. */
+#define LANDLOCK_ABI_SCOPED 6
+
+static const char *const ENV_ALLOW[] = {"HOME",
+ "USER",
+ "LOGNAME",
+ "PATH",
+ "SHELL",
+ "PWD",
+ "TMPDIR",
+ "TMP",
+ "LANG",
+ "LANGUAGE",
+ "TZ",
+ "TERM",
+ "HOSTNAME",
+ "DISPLAY",
+ "XDG_RUNTIME_DIR",
+ "XDG_CACHE_HOME",
+ "XDG_CONFIG_HOME",
+ "XDG_DATA_HOME",
+ "LD_LIBRARY_PATH",
+ "JAVA_HOME",
+ "FONTCONFIG_PATH",
+ "FONTCONFIG_FILE",
+ "DBUS_SESSION_BUS_ADDRESS",
+ "MALLOC_ARENA_MAX",
+ NULL};
+
+static const char *const ENV_ALLOW_PREFIX[] = {"LC_", "SAL_", "OOO_",
+ "UNO_", "URE_", "OFFICE_",
+ "STIRLING_LO_", NULL};
+
+static int env_allowed(const char *entry) {
+ const char *eq = strchr(entry, '=');
+ size_t name_len = eq != NULL ? (size_t)(eq - entry) : strlen(entry);
+
+ for (size_t i = 0; ENV_ALLOW[i] != NULL; i++) {
+ if (strlen(ENV_ALLOW[i]) == name_len &&
+ strncmp(entry, ENV_ALLOW[i], name_len) == 0) {
+ return 1;
+ }
+ }
+ for (size_t i = 0; ENV_ALLOW_PREFIX[i] != NULL; i++) {
+ size_t plen = strlen(ENV_ALLOW_PREFIX[i]);
+ if (name_len > plen && strncmp(entry, ENV_ALLOW_PREFIX[i], plen) == 0) {
+ return 1;
+ }
+ }
+ return 0;
+}
+
+static char **scrub_environment(char **envp) {
+ size_t count = 0;
+ size_t kept = 0;
+ char **out;
+
+ while (envp != NULL && envp[count] != NULL) {
+ count++;
+ }
+ out = calloc(count + 1, sizeof(char *));
+ if (out == NULL) {
+ return envp;
+ }
+ for (size_t i = 0; i < count; i++) {
+ if (env_allowed(envp[i])) {
+ out[kept++] = envp[i];
+ }
+ }
+ out[kept] = NULL;
+ return out;
+}
+
+static int install_seccomp(void) {
+ struct sock_filter filter[] = {
+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, arch)),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, LO_AUDIT_ARCH, 1, 0),
+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
+
+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS, offsetof(struct seccomp_data, nr)),
+#if defined(__x86_64__)
+ /* x32 syscalls report AUDIT_ARCH_X86_64 but carry this bit in nr, so none of the
+ * comparisons below would match them. */
+ BPF_JUMP(BPF_JMP | BPF_JGE | BPF_K, 0x40000000U, 0, 1),
+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_KILL_PROCESS),
+#endif
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_socket, 9, 0),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_socketpair, 8, 0),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_io_uring_setup, 6, 0),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_io_uring_enter, 5, 0),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_io_uring_register, 4, 0),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_ptrace, 3, 0),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_process_vm_readv, 2, 0),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, __NR_process_vm_writev, 1, 0),
+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ERRNO | (EPERM & SECCOMP_RET_DATA)),
+
+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS,
+ offsetof(struct seccomp_data, args[0]) + 4),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, 1, 0),
+ BPF_STMT(BPF_RET | BPF_K,
+ SECCOMP_RET_ERRNO | (EAFNOSUPPORT & SECCOMP_RET_DATA)),
+ BPF_STMT(BPF_LD | BPF_W | BPF_ABS,
+ offsetof(struct seccomp_data, args[0])),
+ BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, AF_UNIX, 1, 0),
+ BPF_STMT(BPF_RET | BPF_K,
+ SECCOMP_RET_ERRNO | (EAFNOSUPPORT & SECCOMP_RET_DATA)),
+ BPF_STMT(BPF_RET | BPF_K, SECCOMP_RET_ALLOW),
+ };
+ struct sock_fprog prog = {
+ .len = (unsigned short)(sizeof(filter) / sizeof(filter[0])),
+ .filter = filter,
+ };
+
+ if (syscall(__NR_seccomp, SECCOMP_SET_MODE_FILTER, 0, &prog) == 0) {
+ return 0;
+ }
+ /* QEMU user-mode emulation answers EINVAL rather than ENOSYS. */
+ if (errno != ENOSYS && errno != EINVAL) {
+ return -1;
+ }
+ if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) == 0) {
+ return 0;
+ }
+ if (errno == ENOSYS || errno == EINVAL) {
+ return 1;
+ }
+ return -1;
+}
+
+static int landlock_add_path(int fd, const char *path, uint64_t access,
+ int warn_missing) {
+ struct landlock_path_beneath_attr attr;
+ int parent;
+ int rc;
+
+ struct stat st;
+
+ parent = open(path, O_PATH | O_CLOEXEC);
+ if (parent < 0) {
+ /* Skipped so optional RO paths (e.g. /lib64, absent on arm64) can be listed, and
+ * so another user's private dirs (EACCES) are simply left out. A missing RW or
+ * per-job path means LibreOffice will fail on it, so say so. */
+ if (warn_missing && errno == ENOENT) {
+ fprintf(stderr, "lo-sandbox: allowed path %s skipped: %s\n", path,
+ strerror(errno));
+ }
+ return 0;
+ }
+ if (fstat(parent, &st) == 0 && !S_ISDIR(st.st_mode)) {
+ access &= LO_ACCESS_FILE;
+ }
+ attr.allowed_access = access;
+ attr.parent_fd = parent;
+ rc = (int)syscall(__NR_landlock_add_rule, fd, LANDLOCK_RULE_PATH_BENEATH,
+ &attr, 0);
+ close(parent);
+ return rc;
+}
+
+static int landlock_add_list(int fd, const char *list, uint64_t access,
+ int warn_missing) {
+ char *copy;
+ char *saved = NULL;
+
+ if (list == NULL || *list == '\0') {
+ return 0;
+ }
+ copy = strdup(list);
+ if (copy == NULL) {
+ return -1;
+ }
+ for (char *item = strtok_r(copy, ":", &saved); item != NULL;
+ item = strtok_r(NULL, ":", &saved)) {
+ if (*item == '\0') {
+ continue;
+ }
+ if (landlock_add_path(fd, item, access, warn_missing) != 0) {
+ free(copy);
+ return -1;
+ }
+ }
+ free(copy);
+ return 0;
+}
+
+/* Returns the Landlock ABI the ruleset was enforced with, 0 when the kernel has no Landlock,
+ * or -1 when it has Landlock but the ruleset could not be applied. */
+static int install_landlock(const char *ro, const char *ro_extra, const char *rw,
+ const char *sock) {
+ struct lo_ruleset_attr attr;
+ size_t attr_size;
+ uint64_t access;
+ int abi;
+ int fd;
+
+ abi = (int)syscall(__NR_landlock_create_ruleset, NULL, 0,
+ LANDLOCK_CREATE_RULESET_VERSION);
+ if (abi < 1) {
+ return 0;
+ }
+
+ access = LANDLOCK_ACCESS_FS_EXECUTE | LANDLOCK_ACCESS_FS_WRITE_FILE |
+ LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR |
+ LANDLOCK_ACCESS_FS_REMOVE_DIR | LANDLOCK_ACCESS_FS_REMOVE_FILE |
+ LANDLOCK_ACCESS_FS_MAKE_CHAR | LANDLOCK_ACCESS_FS_MAKE_DIR |
+ LANDLOCK_ACCESS_FS_MAKE_REG | LANDLOCK_ACCESS_FS_MAKE_SOCK |
+ LANDLOCK_ACCESS_FS_MAKE_FIFO | LANDLOCK_ACCESS_FS_MAKE_BLOCK |
+ LANDLOCK_ACCESS_FS_MAKE_SYM;
+ if (abi >= 2) {
+ access |= LANDLOCK_ACCESS_FS_REFER;
+ }
+ if (abi >= 3) {
+ access |= LANDLOCK_ACCESS_FS_TRUNCATE;
+ }
+ if (abi >= 5) {
+ access |= LANDLOCK_ACCESS_FS_IOCTL_DEV;
+ }
+
+ memset(&attr, 0, sizeof(attr));
+ attr.handled_access_fs = access;
+ attr_size = sizeof(attr.handled_access_fs);
+ if (abi >= 4) {
+ /* No net rules are added, so TCP bind/connect is denied even if seccomp is not. */
+ attr.handled_access_net = LO_ACCESS_NET_BIND_TCP | LO_ACCESS_NET_CONNECT_TCP;
+ attr_size = offsetof(struct lo_ruleset_attr, scoped);
+ }
+ if (abi >= LANDLOCK_ABI_SCOPED) {
+ /* Pathname sockets (the unoserver pipe) are unaffected; abstract sockets and
+ * signals to processes outside the sandbox are refused. */
+ attr.scoped = LO_SCOPE_ABSTRACT_UNIX_SOCKET | LO_SCOPE_SIGNAL;
+ attr_size = sizeof(attr);
+ }
+ fd = (int)syscall(__NR_landlock_create_ruleset, &attr, attr_size, 0);
+ if (fd < 0) {
+ return -1;
+ }
+
+ if (landlock_add_list(fd, ro, LO_ACCESS_RO & access, 0) != 0 ||
+ landlock_add_list(fd, ro_extra, LO_ACCESS_RO & access, 1) != 0 ||
+ landlock_add_list(fd, rw, access, 1) != 0 ||
+ landlock_add_list(fd, sock, LANDLOCK_ACCESS_FS_MAKE_SOCK, 0) != 0) {
+ close(fd);
+ return -1;
+ }
+ if (syscall(__NR_landlock_restrict_self, fd, 0) != 0) {
+ close(fd);
+ return -1;
+ }
+ close(fd);
+ return abi;
+}
+
+/* Only a bare probe skips the sandbox; a flag appended to a real invocation must not. */
+static int is_probe(int argc, char **argv) {
+ if (argc != 2) {
+ return 0;
+ }
+ return strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-version") == 0 ||
+ strcmp(argv[1], "--help") == 0;
+}
+
+int main(int argc, char **argv, char **envp) {
+ const char *mode = getenv("STIRLING_LO_SANDBOX");
+ const char *ro = getenv("STIRLING_LO_ALLOW_RO");
+ const char *rw = getenv("STIRLING_LO_ALLOW_RW");
+ const char *ro_extra = getenv("STIRLING_LO_ALLOW_RO_EXTRA");
+ /* Socket-only dirs: LibreOffice hardcodes its single-instance IPC pipe to /tmp, so it
+ * must bind there, but gets no read, write, list or delete right on /tmp itself. */
+ const char *sock = getenv("STIRLING_LO_ALLOW_SOCK");
+ int required;
+ int check;
+ int landlock_abi;
+ int seccomp_rc;
+ char **clean;
+
+ if (mode == NULL || *mode == '\0') {
+ mode = "enforce";
+ }
+ if (ro == NULL || *ro == '\0') {
+ ro = DEFAULT_RO;
+ }
+ if (rw == NULL || *rw == '\0') {
+ rw = DEFAULT_RW;
+ }
+ required = strcmp(mode, "required") == 0;
+ check = argc == 2 && strcmp(argv[1], SELF_CHECK_FLAG) == 0;
+
+ if (strcmp(mode, "off") == 0) {
+ if (check) {
+ fprintf(stderr, "lo-sandbox: disabled (mode=off)\n");
+ return 0;
+ }
+ execv(REAL_SOFFICE, argv);
+ fprintf(stderr, "lo-sandbox: exec %s failed: %s\n", REAL_SOFFICE, strerror(errno));
+ return 127;
+ }
+ if (is_probe(argc, argv)) {
+ execv(REAL_SOFFICE, argv);
+ fprintf(stderr, "lo-sandbox: exec %s failed: %s\n", REAL_SOFFICE, strerror(errno));
+ return 127;
+ }
+
+ clean = scrub_environment(envp);
+
+ if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0) {
+ fprintf(stderr, "lo-sandbox: no_new_privs failed: %s\n",
+ strerror(errno));
+ return 125;
+ }
+
+ landlock_abi = install_landlock(ro, ro_extra, rw, sock);
+ if (landlock_abi < 0) {
+ fprintf(stderr, "lo-sandbox: landlock ruleset failed: %s\n",
+ strerror(errno));
+ return 125;
+ }
+ if (landlock_abi == 0) {
+ if (required) {
+ fprintf(stderr,
+ "lo-sandbox: landlock unavailable and mode=required\n");
+ return 125;
+ }
+ fprintf(stderr,
+ "lo-sandbox: landlock unavailable, filesystem unconfined\n");
+ } else if (landlock_abi < LANDLOCK_ABI_SCOPED) {
+ if (required) {
+ fprintf(stderr,
+ "lo-sandbox: landlock ABI %d cannot scope signals and abstract "
+ "sockets (needs %d) and mode=required\n",
+ landlock_abi, LANDLOCK_ABI_SCOPED);
+ return 125;
+ }
+ if (check) {
+ fprintf(stderr,
+ "lo-sandbox: landlock scoping unavailable (ABI %d), signals and "
+ "abstract sockets unconfined\n",
+ landlock_abi);
+ }
+ }
+
+ seccomp_rc = install_seccomp();
+ if (seccomp_rc < 0) {
+ fprintf(stderr, "lo-sandbox: seccomp filter rejected: %s\n",
+ strerror(errno));
+ return 125;
+ }
+ if (seccomp_rc > 0) {
+ if (required) {
+ fprintf(stderr, "lo-sandbox: seccomp unavailable and mode=required\n");
+ return 125;
+ }
+ fprintf(stderr, "lo-sandbox: seccomp unavailable, network unconfined\n");
+ }
+
+ if (check) {
+ fprintf(stderr, "lo-sandbox: landlock ABI %d, seccomp %s\n", landlock_abi,
+ seccomp_rc == 0 ? "active" : "unavailable");
+ return 0;
+ }
+ execve(REAL_SOFFICE, argv, clean);
+ fprintf(stderr, "lo-sandbox: exec %s failed: %s\n", REAL_SOFFICE, strerror(errno));
+ return 127;
+}
diff --git a/docker/base/stirling-hardening.xcd b/docker/base/stirling-hardening.xcd
new file mode 100644
index 0000000000..024a495c69
--- /dev/null
+++ b/docker/base/stirling-hardening.xcd
@@ -0,0 +1,83 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<oor:data xmlns:oor="http://openoffice.org/2001/registry"
+ xmlns:xs="http://www.w3.org/2001/XMLSchema"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <dependency file="main"/>
+ <oor:component-data oor:name="Common" oor:package="org.openoffice.Office">
+ <node oor:name="Security">
+ <node oor:name="Scripting">
+ <prop oor:name="DisableMacrosExecution" oor:finalized="true">
+ <value>true</value>
+ </prop>
+ <prop oor:name="MacroSecurityLevel" oor:finalized="true">
+ <value>3</value>
+ </prop>
+ <prop oor:name="DisableActiveContent" oor:finalized="true">
+ <value>true</value>
+ </prop>
+ <prop oor:name="DisableOLEAutomation" oor:finalized="true">
+ <value>true</value>
+ </prop>
+ <prop oor:name="BlockUntrustedRefererLinks" oor:finalized="true">
+ <value>true</value>
+ </prop>
+ <prop oor:name="SecureURL" oor:finalized="true">
+ <value/>
+ </prop>
+ <node oor:name="TrustedAuthors" oor:finalized="true"/>
+ </node>
+ </node>
+ </oor:component-data>
+ <oor:component-data oor:name="Writer" oor:package="org.openoffice.Office">
+ <node oor:name="Content">
+ <node oor:name="Update">
+ <prop oor:name="Link" oor:finalized="true">
+ <value>2</value>
+ </prop>
+ <prop oor:name="Field" oor:finalized="true">
+ <value>false</value>
+ </prop>
+ <prop oor:name="Chart" oor:finalized="true">
+ <value>false</value>
+ </prop>
+ </node>
+ </node>
+ </oor:component-data>
+ <oor:component-data oor:name="Calc" oor:package="org.openoffice.Office">
+ <node oor:name="Content">
+ <node oor:name="Update">
+ <prop oor:name="Link" oor:finalized="true">
+ <value>1</value>
+ </prop>
+ </node>
+ </node>
+ </oor:component-data>
+ <oor:component-data oor:name="Inet" oor:package="org.openoffice">
+ <node oor:name="Settings">
+ <prop oor:name="ooInetProxyType" oor:finalized="true">
+ <value>2</value>
+ </prop>
+ <prop oor:name="ooInetHTTPProxyName" oor:finalized="true">
+ <value>127.0.0.1</value>
+ </prop>
+ <prop oor:name="ooInetHTTPProxyPort" oor:finalized="true">
+ <value>1</value>
+ </prop>
+ <prop oor:name="ooInetHTTPSProxyName" oor:finalized="true">
+ <value>127.0.0.1</value>
+ </prop>
+ <prop oor:name="ooInetHTTPSProxyPort" oor:finalized="true">
+ <value>1</value>
+ </prop>
+ <prop oor:name="ooInetFTPProxyName" oor:finalized="true">
+ <value>127.0.0.1</value>
+ </prop>
+ <prop oor:name="ooInetFTPProxyPort" oor:finalized="true">
+ <value>1</value>
+ </prop>
+ <prop oor:name="ooInetNoProxy" oor:finalized="true">
+ <value/>
+ </prop>
+ </node>
+ </oor:component-data>
+</oor:data>
diff --git a/docker/base/unoserver-pipe-transport.py b/docker/base/unoserver-pipe-transport.py
new file mode 100644
index 0000000000..a35119f383
--- /dev/null
+++ b/docker/base/unoserver-pipe-transport.py
@@ -0,0 +1,45 @@
+import pathlib
+import sys
+
+SERVER_OLD = (
+ ' connection = (\n'
+ ' "socket,host=%s,port=%s,tcpNoDelay=1;urp;StarOffice.ComponentContext"\n'
+ ' % (self.uno_interface, self.uno_port)\n'
+ ' )\n'
+)
+SERVER_NEW = (
+ ' connection = (\n'
+ ' "pipe,name=unoserver_%s;urp;StarOffice.ComponentContext"\n'
+ ' % (self.uno_port,)\n'
+ ' )\n'
+)
+
+CLIENT_OLD = (
+ ' f"uno:socket,host={interface},port={port};urp;StarOffice.ComponentContext"\n'
+)
+CLIENT_NEW = (
+ ' f"uno:pipe,name=unoserver_{port};urp;StarOffice.ComponentContext"\n'
+)
+
+
+def patch(path, old, new):
+ target = pathlib.Path(path)
+ text = target.read_text(encoding="utf-8")
+ if new in text:
+ return
+ if old not in text:
+ sys.exit("unoserver pipe transport patch does not apply to %s" % path)
+ target.write_text(text.replace(old, new, 1), encoding="utf-8")
+
+
+def main():
+ if len(sys.argv) != 2:
+ sys.exit("usage: unoserver-pipe-transport.py <site-packages/unoserver>")
+ base = pathlib.Path(sys.argv[1])
+ patch(base / "server.py", SERVER_OLD, SERVER_NEW)
+ patch(base / "converter.py", CLIENT_OLD, CLIENT_NEW)
+ patch(base / "comparer.py", CLIENT_OLD, CLIENT_NEW)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/docker/embedded/Dockerfile b/docker/embedded/Dockerfile
index 3bc127b29b..c18aad9633 100644
--- a/docker/embedded/Dockerfile
+++ b/docker/embedded/Dockerfile
@@ -1,7 +1,7 @@
# Stirling-PDF - Full version (embedded frontend)
# Uses pre-built base image for fast builds
-ARG BASE_VERSION=1.0.2@sha256:c7698687f486707ddef9e0298587ca8b44c4e96185e1bdb0c3d119eb2bf9a82e
+ARG BASE_VERSION=1.0.6@sha256:003c1056474d4f9b8c38d3c8b72c78a7ac51b45e12500f831739a4cbf8803987
ARG BASE_IMAGE=stirlingtools/stirling-pdf-base:${BASE_VERSION}
# Stage 1: Build the Java application and frontend
diff --git a/docker/embedded/Dockerfile.fat b/docker/embedded/Dockerfile.fat
index de98ea1c95..f3af0a0f7f 100644
--- a/docker/embedded/Dockerfile.fat
+++ b/docker/embedded/Dockerfile.fat
@@ -4,7 +4,7 @@
# Extra fonts for air-gapped environments
# Uses pre-built base image for fast builds
-ARG BASE_VERSION=1.0.2@sha256:c7698687f486707ddef9e0298587ca8b44c4e96185e1bdb0c3d119eb2bf9a82e
+ARG BASE_VERSION=1.0.6@sha256:003c1056474d4f9b8c38d3c8b72c78a7ac51b45e12500f831739a4cbf8803987
ARG BASE_IMAGE=stirlingtools/stirling-pdf-base:${BASE_VERSION}
# Stage 1: Build the Java application and frontend
diff --git a/docker/unoserver/Dockerfile b/docker/unoserver/Dockerfile
index 11dff0f129..6615f23fe4 100644
--- a/docker/unoserver/Dockerfile
+++ b/docker/unoserver/Dockerfile
@@ -1,6 +1,14 @@
# Standalone unoserver image for Stirling-PDF remote UNO mode.
# Pinned to unoserver 3.7 to match Stirling-PDF's client (avoids wire mismatch).
+FROM ubuntu:noble@sha256:33ceb71981b602c1a7443a53469e4dba065f7503eab3078a2d7a57a2ab987517 AS lo-sandbox-build
+RUN apt-get update && apt-get install -y --no-install-recommends gcc libc6-dev && \
+ rm -rf /var/lib/apt/lists/*
+COPY docker/base/lo-sandbox.c /src/lo-sandbox.c
+RUN gcc -O2 -Wall -Wextra -Werror -o /usr/local/bin/lo-sandbox /src/lo-sandbox.c && \
+ strip --strip-unneeded /usr/local/bin/lo-sandbox
+
+
FROM ubuntu:noble@sha256:33ceb71981b602c1a7443a53469e4dba065f7503eab3078a2d7a57a2ab987517
ARG UNOSERVER_VERSION=3.7
@@ -90,6 +98,23 @@ RUN rm -rf /usr/lib/libreoffice/share/gallery \
/usr/lib/libreoffice/share/extensions/nlpsolver \
/usr/share/doc/* /usr/share/man/* /usr/share/info/*
+COPY --from=lo-sandbox-build /usr/local/bin/lo-sandbox /usr/local/lib/stirling/lo-sandbox
+COPY --chmod=0644 docker/base/stirling-hardening.xcd /usr/lib/libreoffice/share/registry/stirling-hardening.xcd
+COPY docker/base/unoserver-pipe-transport.py /usr/local/lib/stirling/unoserver-pipe-transport.py
+
+RUN set -eux; \
+ chown root:root /usr/local/lib/stirling/lo-sandbox; \
+ chmod 0755 /usr/local/lib/stirling/lo-sandbox; \
+ for name in /usr/bin/soffice /usr/bin/libreoffice /usr/bin/ooffice; do \
+ if [ -e "$name" ] || [ -L "$name" ]; then rm -f "$name"; fi; \
+ cp /usr/local/lib/stirling/lo-sandbox "$name"; \
+ chown root:root "$name"; \
+ chmod 0755 "$name"; \
+ done; \
+ /opt/unoserver-venv/bin/python /usr/local/lib/stirling/unoserver-pipe-transport.py \
+ "$(/opt/unoserver-venv/bin/python -c 'import unoserver, os; print(os.path.dirname(unoserver.__file__))')"; \
+ STIRLING_LO_SANDBOX=off /usr/bin/soffice --version
+
ARG PUID=1001
ARG PGID=1001
RUN groupadd -g "${PGID}" unoserver && \
diff --git a/docker/unoserver/VERSION b/docker/unoserver/VERSION
index 3eefcb9dd5..7dea76edb3 100644
--- a/docker/unoserver/VERSION
+++ b/docker/unoserver/VERSION
@@ -1 +1 @@
-1.0.0
+1.0.1
diff --git a/docker/unoserver/entrypoint.sh b/docker/unoserver/entrypoint.sh
index 6fea01a6bc..7344060126 100644
--- a/docker/unoserver/entrypoint.sh
+++ b/docker/unoserver/entrypoint.sh
@@ -28,6 +28,11 @@ case "$IDLE_TIMEOUT" in ''|*[!0-9]*) log "Invalid UNOSERVER_IDLE_TIMEOUT_SECONDS
mkdir -p "$PROFILE_DIR"
+export STIRLING_LO_SANDBOX="${STIRLING_LO_SANDBOX:-enforce}"
+# Read-only paths come from lo-sandbox's built-in default unless STIRLING_LO_ALLOW_RO is set.
+export STIRLING_LO_ALLOW_RW="${STIRLING_LO_ALLOW_RW:-/tmp:/dev:${PROFILE_DIR}:${HOME:-/home/unoserver}}"
+log "LibreOffice sandbox mode=${STIRLING_LO_SANDBOX}"
+
start_xvfb() {
if command -v Xvfb >/dev/null 2>&1 && [ -z "${DISPLAY:-}" ]; then
Xvfb :99 -screen 0 1024x768x24 -ac +extension GLX +render -noreset >/dev/null 2>&1 &
diff --git a/scripts/init-without-ocr.sh b/scripts/init-without-ocr.sh
index f855590c29..ff6f01952c 100755
--- a/scripts/init-without-ocr.sh
+++ b/scripts/init-without-ocr.sh
@@ -131,11 +131,6 @@ cleanup() {
[ -n "$pid" ] && kill -TERM "$pid" 2>/dev/null || true
done
- # Stop Xvfb if running (on-demand mode)
- if [ -n "${XVFB_PID:-}" ] && kill -0 "$XVFB_PID" 2>/dev/null; then
- kill -TERM "$XVFB_PID" 2>/dev/null || true
- fi
-
# Signal Java to shut down gracefully, Spring Boot handles SIGTERM cleanly
if [ -n "${JAVA_PID:-}" ] && kill -0 "$JAVA_PID" 2>/dev/null; then
kill -TERM "$JAVA_PID" 2>/dev/null || true
@@ -151,7 +146,7 @@ cleanup() {
fi
fi
- # Kill any remaining children (watchdog, Xvfb, etc.)
+ # Kill any remaining children (watchdog, etc.)
pkill -P $$ 2>/dev/null || true
log "Cleanup complete."
@@ -271,6 +266,134 @@ run_as_runtime_user() {
fi
}
+OFFICE_USER="${STIRLING_OFFICE_USER:-stirlingofficeuser}"
+OFFICE_SANDBOX_HOME="/var/lib/libreoffice-sandbox"
+OFFICE_USER_AVAILABLE=false
+# LibreOffice's own temp and XDG dirs. The inherited TMPDIR/SAL_TMP/XDG_RUNTIME_DIR point into
+# the runtime user's shared dirs, which the office user cannot write (every store then fails
+# with Io Write 16) and which the sandbox no longer grants. Set by prepare_office_dirs.
+OFFICE_TMP=""
+OFFICE_XDG=""
+
+resolve_office_user() {
+ if ! id -u "$OFFICE_USER" >/dev/null 2>&1; then
+ log "Office sandbox user ${OFFICE_USER} not present; LibreOffice will share the runtime user"
+ return
+ fi
+ if [ "$(id -u "$OFFICE_USER")" = "$(id -u "$RUNTIME_USER" 2>/dev/null || echo -1)" ]; then
+ log "WARNING: ${OFFICE_USER} and ${RUNTIME_USER} resolve to the same uid; LibreOffice privilege separation is disabled. Choose a PUID other than $(id -u "$OFFICE_USER")."
+ return
+ fi
+ if [ "$CURRENT_UID" -ne 0 ] || ! command_exists setpriv; then
+ log "Cannot switch to ${OFFICE_USER} (not root or setpriv missing); LibreOffice will share the runtime user"
+ return
+ fi
+ OFFICE_USER_AVAILABLE=true
+}
+
+run_as_office_user() {
+ if [ "$OFFICE_USER_AVAILABLE" != true ]; then
+ run_as_runtime_user env \
+ TMPDIR="$OFFICE_TMP" TMP="$OFFICE_TMP" TEMP="$OFFICE_TMP" SAL_TMP="$OFFICE_TMP" \
+ XDG_RUNTIME_DIR="$OFFICE_XDG" \
+ "$@"
+ return
+ fi
+ env HOME="$OFFICE_SANDBOX_HOME" \
+ USER="$OFFICE_USER" \
+ LOGNAME="$OFFICE_USER" \
+ TMPDIR="$OFFICE_TMP" \
+ TMP="$OFFICE_TMP" \
+ TEMP="$OFFICE_TMP" \
+ SAL_TMP="$OFFICE_TMP" \
+ XDG_RUNTIME_DIR="$OFFICE_XDG" \
+ setpriv --reuid="$OFFICE_USER" --regid="$(id -gn "$OFFICE_USER")" --init-groups -- "$@"
+}
+
+# The sandbox grants /tmp as socket-only, so LibreOffice can bind its IPC pipes there but
+# cannot unlink them. A pipe left by a killed instance would make the restart's bind fail;
+# a pipe file with no bound socket in /proc/net/unix is stale and safe to remove.
+clear_stale_office_pipes() {
+ local pipe
+ for pipe in /tmp/OSL_PIPE_*; do
+ [ -S "$pipe" ] || continue
+ if ! grep -qF " $pipe" /proc/net/unix 2>/dev/null; then
+ rm -f "$pipe" 2>/dev/null || true
+ fi
+ done
+}
+
+# Read-only paths come from lo-sandbox's built-in default unless STIRLING_LO_ALLOW_RO is set.
+# Java narrows RW/SOCK further per job for the soffice commands it runs itself.
+export_office_sandbox_policy() {
+ local profile_root=$1
+ local rw="/dev:${profile_root}:${OFFICE_TMP}:${OFFICE_XDG}"
+ [ "$OFFICE_USER_AVAILABLE" = true ] && rw="${rw}:${OFFICE_SANDBOX_HOME}"
+ export STIRLING_LO_SANDBOX="${STIRLING_LO_SANDBOX:-enforce}"
+ export STIRLING_LO_ALLOW_RW="${STIRLING_LO_ALLOW_RW:-${rw}}"
+ export STIRLING_LO_ALLOW_SOCK="${STIRLING_LO_ALLOW_SOCK:-/tmp}"
+ log "LibreOffice sandbox mode=${STIRLING_LO_SANDBOX} user=$([ "$OFFICE_USER_AVAILABLE" = true ] && echo "$OFFICE_USER" || echo "$RUNTIME_USER")"
+ check_office_sandbox
+}
+
+# enforce mode degrades silently to a stderr line per launch when the kernel lacks Landlock
+# or seccomp (old kernels, gVisor, QEMU user emulation); report it once, loudly, at startup.
+check_office_sandbox() {
+ local soffice out rc
+ soffice="$(command -v soffice || true)"
+ [ -n "$soffice" ] || return 0
+ if [ ! -x /usr/local/lib/stirling/lo-sandbox ]; then
+ log "WARNING: LibreOffice sandbox launcher is not in this image; LibreOffice runs unconfined"
+ return 0
+ fi
+ [ "$STIRLING_LO_SANDBOX" = off ] && { log "WARNING: LibreOffice sandbox disabled (STIRLING_LO_SANDBOX=off)"; return 0; }
+ rc=0
+ out="$("$soffice" --stirling-sandbox-check 2>&1)" || rc=$?
+ out="$(printf '%s' "$out" | tr '\n' ' ')"
+ if [ "$rc" -eq 125 ]; then
+ log "ERROR: LibreOffice sandbox required but unavailable; office conversions will fail: ${out}"
+ elif [ "$rc" -ne 0 ] || ! printf '%s' "$out" | grep -q 'lo-sandbox: landlock ABI'; then
+ log "ERROR: LibreOffice sandbox self-check failed (exit ${rc}): ${out}"
+ elif printf '%s' "$out" | grep -qE 'landlock unavailable|seccomp unavailable'; then
+ log "WARNING: LibreOffice sandbox is only partially active on this kernel: ${out}. Set STIRLING_LO_SANDBOX=required to refuse to run LibreOffice unconfined."
+ elif printf '%s' "$out" | grep -q 'scoping unavailable'; then
+ log "WARNING: LibreOffice sandbox active without signal and abstract-socket scoping on this kernel: ${out}. STIRLING_LO_SANDBOX=required needs Landlock ABI 6 (Linux 6.12+) and would refuse every conversion here."
+ else
+ log "LibreOffice sandbox active (${out})"
+ fi
+}
+
+# A profile from an init-only soffice run, made before any document is opened. Java copies its
+# extension registry into fresh per-job profiles so LibreOffice does not relaunch on first start,
+# which fails under the sandbox; it is root-owned so no LibreOffice process can change it later.
+OFFICE_PROFILE_TEMPLATE=/var/lib/libreoffice-template
+
+create_office_profile_template() {
+ local build="${OFFICE_PROFILE_TEMPLATE}.new"
+ [ "$CURRENT_UID" -eq 0 ] || return 0
+ rm -rf "$build" "$OFFICE_PROFILE_TEMPLATE"
+ mkdir -p "$build/tmp"
+ if [ "$OFFICE_USER_AVAILABLE" = true ]; then
+ chown -R "$OFFICE_USER" "$build"
+ else
+ chown -R "$RUNTIME_USER" "$build"
+ fi
+ run_as_office_user env HOME="$build" TMPDIR="$build/tmp" TMP="$build/tmp" TEMP="$build/tmp" \
+ SAL_TMP="$build/tmp" XDG_RUNTIME_DIR="$build/tmp" STIRLING_LO_ALLOW_RW="/dev:${build}" \
+ timeout 120 soffice --headless --norestore --terminate_after_init \
+ "-env:UserInstallation=file://${build}" >/dev/null 2>&1 || true
+ clear_stale_office_pipes
+ if [ -d "$build/user/extensions" ]; then
+ rm -rf "$build/tmp"
+ chown -R root:root "$build"
+ chmod -R a+rX,go-w "$build"
+ mv "$build" "$OFFICE_PROFILE_TEMPLATE"
+ else
+ log "WARNING: could not create the LibreOffice profile template; direct soffice jobs will retry their first run"
+ rm -rf "$build"
+ fi
+}
+
run_as_runtime_user_with_timeout() {
local secs=$1; shift
if command_exists timeout; then
@@ -349,9 +472,23 @@ start_unoserver_instance() {
conversion_timeout="$(get_unoserver_conversion_timeout_seconds)"
# Per-instance profile dir avoids LibreOffice lock-file contention.
local profile_dir="${LIBREOFFICE_PROFILE}/instance_${port}"
- run_as_runtime_user mkdir -p "$profile_dir"
+ run_as_office_user mkdir -p "$profile_dir"
+ # The watchdog only signals unoserver's direct children, so a soffice.bin reparented to init
+ # can outlive a restart and keep the instance's pipe bound; the new instance then cannot start.
+ local leftover="-env:UserInstallation=file://${profile_dir}"
+ if pkill -KILL -f -- "$leftover" 2>/dev/null; then
+ for _ in 1 2 3 4 5; do pgrep -f -- "$leftover" >/dev/null 2>&1 || break; sleep 1; done
+ fi
+ clear_stale_office_pipes
+ # A fresh profile makes soffice initialise it and relaunch under an IPC pipe the sandbox will not
+ # let it unlink, so unoserver's own first soffice would die; initialise the profile up front.
+ if [ ! -d "${profile_dir}/user" ]; then
+ run_as_office_user timeout 120 soffice --headless --norestore --terminate_after_init \
+ "$leftover" >/dev/null 2>&1 || true
+ clear_stale_office_pipes
+ fi
# --user-installation is a plain path; unoserver 3.6 crashes if pre-wrapped as file://.
- run_as_runtime_user "$UNOSERVER_BIN" \
+ run_as_office_user "$UNOSERVER_BIN" \
--interface 127.0.0.1 \
--port "$port" \
--uno-port "$uno_port" \
@@ -360,6 +497,17 @@ start_unoserver_instance() {
2> >(grep --line-buffered -v "POST /RPC2" >&2) \
&
LAST_UNOSERVER_PID=$!
+ UNOSERVER_STARTED_AT[$port]=$(date +%s)
+}
+
+# unoserver waits a few seconds before binding its port, so a health check right after a
+# (re)start sees a starting instance as dead and kills it again.
+UNOSERVER_START_GRACE_SECONDS=30
+declare -A UNOSERVER_STARTED_AT=()
+
+unoserver_starting() {
+ local started=${UNOSERVER_STARTED_AT[$1]:-0}
+ [ $(( $(date +%s) - started )) -lt "$UNOSERVER_START_GRACE_SECONDS" ]
}
# Stop an unoserver instance and its soffice children. Child PIDs are captured
@@ -403,7 +551,7 @@ start_unoserver_watchdog() {
if [ -z "$pid" ] || ! kill -0 "$pid" 2>/dev/null; then
log "unoserver PID ${pid} not found for port ${port}"
needs_restart=true
- elif ! check_unoserver_port_ready "$port"; then
+ elif ! unoserver_starting "$port" && ! check_unoserver_port_ready "$port"; then
needs_restart=true
fi
@@ -459,34 +607,11 @@ start_unoserver_pool_eager() {
}
# ---------- On-demand unoserver management ----------
-# When UNO_DEMAND_ENABLED=true, unoserver + soffice + Xvfb are only started
+# When UNO_DEMAND_ENABLED=true, unoserver + soffice are only started
# when a conversion is needed and stopped after an idle timeout.
# This saves ~200-350 MB idle memory.
UNO_DEMAND_FILE="/tmp/uno-last-used"
UNO_POOL_RUNNING=false
-XVFB_PID=""
-
-start_xvfb_if_needed() {
- if [ -n "${XVFB_PID:-}" ] && kill -0 "$XVFB_PID" 2>/dev/null; then
- return 0
- fi
- if command_exists Xvfb; then
- Xvfb :99 -screen 0 1024x768x24 -ac +extension GLX +render -noreset > /dev/null 2>&1 &
- XVFB_PID=$!
- export DISPLAY=:99
- sleep 1
- log "Xvfb started on-demand (pid $XVFB_PID)"
- fi
-}
-
-stop_xvfb() {
- if [ -n "${XVFB_PID:-}" ] && kill -0 "$XVFB_PID" 2>/dev/null; then
- kill -TERM "$XVFB_PID" 2>/dev/null || true
- wait "$XVFB_PID" 2>/dev/null || true
- log "Xvfb stopped"
- fi
- XVFB_PID=""
-}
# Start the unoserver pool on-demand (called from the demand manager).
start_unoserver_pool_now() {
@@ -494,8 +619,6 @@ start_unoserver_pool_now() {
return 0
fi
- start_xvfb_if_needed
-
local count
count="$(get_unoserver_count)"
case "$count" in
@@ -539,15 +662,13 @@ start_unoserver_pool_now() {
UNO_POOL_RUNNING=true
}
-# Stop all unoserver instances and Xvfb to reclaim memory. Runs even when the
+# Stop all unoserver instances to reclaim memory. Runs even when the
# pool flag was never set, so a partially started pool still gets cleaned.
stop_unoserver_pool_now() {
for pid in "${UNOSERVER_PIDS[@]:-}"; do
stop_unoserver_instance "$pid"
done
- stop_xvfb
-
UNOSERVER_PIDS=()
UNOSERVER_PORTS=()
UNOSERVER_UNO_PORTS=()
@@ -566,7 +687,7 @@ start_unoserver_demand_manager() {
local check_interval=5
# This loop runs in a background subshell, so the parent's cleanup cannot see
- # its UNOSERVER_PIDS or XVFB_PID; clean the tree up from here.
+ # its UNOSERVER_PIDS; clean the tree up from here.
manager_cleanup() {
trap - TERM INT EXIT
stop_unoserver_pool_now
@@ -616,7 +737,7 @@ start_unoserver_demand_manager() {
log "unoserver PID ${pid} died for port ${port}, restarting"
start_unoserver_instance "$port" "$uno_port"
UNOSERVER_PIDS[i]=$LAST_UNOSERVER_PID
- elif ! check_unoserver_port_ready "$port" "silent"; then
+ elif ! unoserver_starting "$port" && ! check_unoserver_port_ready "$port" "silent"; then
log "unoserver port ${port} unhealthy, restarting"
stop_unoserver_instance "$pid"
start_unoserver_instance "$port" "$uno_port"
@@ -1171,7 +1292,7 @@ CHOWN_OK=true
for p in "${CHOWN_PATHS[@]}"; do
if [ -e "$p" ]; then
chown -R "stirlingpdfuser:stirlingpdfgroup" "$p" 2>/dev/null || CHOWN_OK=false
- chmod -R 755 "$p" 2>/dev/null || true
+ find "$p" -type d -exec chmod 755 {} + 2>/dev/null || true
fi
done
@@ -1190,7 +1311,27 @@ for dir in "${CRITICAL_DIRS[@]}"; do
fi
done
-# ---------- Xvfb + unoserver ----------
+# ---------- Private work areas ----------
+# STIRLING_TEMPDIR is user-set; a shared dir such as /tmp must keep its sticky bit and owner,
+# or the office user can no longer bind LibreOffice's IPC pipes there.
+STIRLING_FILE_STORE="${STIRLING_TEMPDIR:-/tmp/stirling-files}"
+for private_dir in /tmp/stirling-pdf "$STIRLING_FILE_STORE"; do
+ case "$(realpath -m "$private_dir" 2>/dev/null || printf '%s' "$private_dir")" in
+ /|/tmp|/var|/var/tmp|/dev/shm|/home|/run|/usr|/etc|/opt)
+ log "Not locking down shared dir ${private_dir}"
+ continue
+ ;;
+ esac
+ mkdir -p "$private_dir" 2>/dev/null || true
+ if [ -d "$private_dir" ]; then
+ chown "stirlingpdfuser:stirlingpdfgroup" "$private_dir" 2>/dev/null || true
+ chmod 700 "$private_dir" 2>/dev/null || true
+ fi
+done
+
+# ---------- unoserver ----------
+# LibreOffice renders headless (SAL_USE_VCLPLUGIN=svp), so no X server is started: one running
+# as root with access control off would be reachable from the sandbox through its socket.
# Detect whether on-demand mode is enabled.
UNO_DEMAND_ENABLED="${UNO_DEMAND_ENABLED:-true}"
UNO_DEMAND_ENABLED="${UNO_DEMAND_ENABLED,,}"
@@ -1200,12 +1341,28 @@ UNOCONVERT_BIN="$(command -v unoconvert || true)"
UNOPING_BIN="$(command -v unoping || true)"
if [ -n "$UNOSERVER_BIN" ] && [ -n "$UNOCONVERT_BIN" ]; then
- LIBREOFFICE_PROFILE="${HOME:-/home/${RUNTIME_USER}}/.libreoffice_uno_${RUID}"
- run_as_runtime_user mkdir -p "$LIBREOFFICE_PROFILE"
+ resolve_office_user
+ if [ "$OFFICE_USER_AVAILABLE" = true ]; then
+ LIBREOFFICE_PROFILE="${OFFICE_SANDBOX_HOME}/profiles"
+ OFFICE_TMP="${OFFICE_SANDBOX_HOME}/tmp"
+ OFFICE_XDG="${OFFICE_SANDBOX_HOME}/xdg"
+ mkdir -p "$LIBREOFFICE_PROFILE" "$OFFICE_TMP" "$OFFICE_XDG"
+ chown -R "$OFFICE_USER:$(id -gn "$OFFICE_USER")" "$OFFICE_SANDBOX_HOME" 2>/dev/null || true
+ chmod 700 "$OFFICE_SANDBOX_HOME" "$OFFICE_TMP" "$OFFICE_XDG" 2>/dev/null || true
+ else
+ LIBREOFFICE_PROFILE="${HOME:-/home/${RUNTIME_USER}}/.libreoffice_uno_${RUID}"
+ OFFICE_TMP="${LIBREOFFICE_PROFILE}/tmp"
+ OFFICE_XDG="${LIBREOFFICE_PROFILE}/xdg"
+ run_as_runtime_user mkdir -p "$LIBREOFFICE_PROFILE" "$OFFICE_TMP" "$OFFICE_XDG"
+ run_as_runtime_user chmod 700 "$OFFICE_TMP" "$OFFICE_XDG" 2>/dev/null || true
+ fi
+ export_office_sandbox_policy "$LIBREOFFICE_PROFILE"
+ export STIRLING_LO_PROFILE_TEMPLATE="$OFFICE_PROFILE_TEMPLATE"
+ create_office_profile_template &
if [ "$UNO_DEMAND_ENABLED" = "true" ]; then
# ---------- On-demand mode ----------
- # Do NOT start Xvfb, unoserver, or soffice yet.
+ # Do NOT start unoserver or soffice yet.
# The demand manager will start them lazily when a conversion request arrives
# and stop them after an idle timeout to reclaim ~200-350 MB RSS.
log "unoserver on-demand mode enabled (UNO_IDLE_TIMEOUT_SECONDS=${UNO_IDLE_TIMEOUT_SECONDS:-120}s)"
@@ -1214,16 +1371,6 @@ if [ -n "$UNOSERVER_BIN" ] && [ -n "$UNOCONVERT_BIN" ]; then
DEMAND_MANAGER_PID=$!
else
# ---------- Legacy always-on mode ----------
- if command_exists Xvfb; then
- log "Starting Xvfb on :99"
- Xvfb :99 -screen 0 1024x768x24 -ac +extension GLX +render -noreset > /dev/null 2>&1 &
- XVFB_PID=$!
- export DISPLAY=:99
- sleep 1
- else
- log "Xvfb not installed; skipping virtual display setup"
- fi
-
start_unoserver_pool_eager
log "unoserver pool started (Profile: $LIBREOFFICE_PROFILE), Java starting in parallel"
fi
diff --git a/testing/test.sh b/testing/test.sh
index d14caf3a95..9eafea6f26 100644
--- a/testing/test.sh
+++ b/testing/test.sh
@@ -345,6 +345,7 @@ capture_file_list() {
-not -path '*/tmp/stirling-pdf/lu*' \
-not -path '*/tmp/stirling-pdf/tmp*' \
-not -path '/tmp/lu*' \
+ -not -path '/var/lib/libreoffice-sandbox/tmp/lu*' \
-not -path '*/tmp/*/user/registrymodifications.xcu' \
-not -path '/app/stirling.aot' \
-not -path '*/tmp/stirling.aotconf' \
@@ -377,7 +378,7 @@ capture_file_list() {
-not -path '*/tmp/stirling-pdf/tmp*' \
-not -path '*/tmp/lu*' \
-not -path '*/tmp/tmp*' \
- -not -path '/app/stirling.aot' \
+ -not -path '/app/stirling.aot' \
-not -path '*/tmp/stirling.aotconf' \
-not -path '*/tmp/aot-*.log' \
2>/dev/null | sort" > "$output_file"
@@ -429,6 +430,8 @@ compare_file_lists() {
grep -i "tmp\|temp" "$after_file" \
| grep -v '/jpdfium-' \
| grep -v '\.libreoffice_uno_' \
+ | grep -v '/var/lib/libreoffice-sandbox/profiles/' \
+ | grep -v '/var/lib/libreoffice-template/' \
| grep -v '\.X99-lock' \
| grep -v 'uno-last-used' \
| grep -v 'xdg-' \
@@ -469,6 +472,7 @@ compare_file_lists() {
grep -i "tmp\|temp" "${diff_file}.added" \
| grep -v '/jpdfium-' \
| grep -v '\.libreoffice_uno_' \
+ | grep -v '/var/lib/libreoffice-sandbox/profiles/' \
| grep -v '\.X99-lock' \
| grep -v 'uno-last-used' \
| grep -v 'xdg-' \