From 301c3d4b154d66736e8b7b9690cb44a8c3072a60 Mon Sep 17 00:00:00 2001 From: Mitch Gaffigan Date: Wed, 26 Aug 2026 17:37:50 -0500 Subject: [PATCH 01/14] Secure keystores with filesystem acl, use pkcs12 Signed-off-by: Mitch Gaffigan --- server/basedir-includes/configure-from-env | 20 +++-- server/conf/mirth.properties | 11 ++- .../DefaultConfigurationController.java | 34 +------- .../server/util/FilePermissionUtil.java | 81 +++++++++++++++++++ .../server/util/FilePermissionUtilTest.java | 61 ++++++++++++++ server/src/test/resources/mirth.properties | 8 +- 6 files changed, 170 insertions(+), 45 deletions(-) create mode 100644 server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java create mode 100644 server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java diff --git a/server/basedir-includes/configure-from-env b/server/basedir-includes/configure-from-env index 3ab0ebbb7b..a5f6a00b5b 100755 --- a/server/basedir-includes/configure-from-env +++ b/server/basedir-includes/configure-from-env @@ -16,10 +16,18 @@ if [ $custom_extension_count != 0 ]; then done fi -# set storepass and keypass to 'changeme' so they aren't overwritten later -KEYSTORE_PASS=changeme -sed -i "s/^keystore\.storepass\s*=\s*.*\$/keystore.storepass = ${KEYSTORE_PASS//\//\\/}/" "$APP_DIR/conf/mirth.properties" -sed -i "s/^keystore\.keypass\s*=\s*.*\$/keystore.keypass = ${KEYSTORE_PASS//\//\\/}/" "$APP_DIR/conf/mirth.properties" +# The keystore is created with no passphrase and protected by file permissions instead, so there is +# no longer a password to pin here. Keystores created by earlier versions are JCEKS and were pinned +# to 'changeme', so keep those settings when one is already present in appdata. +KEYSTORE_FILE="$APP_DIR/appdata/keystore.pfx" +LEGACY_KEYSTORE_FILE="$APP_DIR/appdata/keystore.jks" +if [ -f "$LEGACY_KEYSTORE_FILE" ] || ! [ -z "${KEYSTORE_DOWNLOAD+x}" ]; then + echo "Found an existing keystore at ${LEGACY_KEYSTORE_FILE}, using jks keystore defaults." + sed -i 's|^keystore\.path\s*=\s*.*$|keystore.path = ${dir.appdata}/keystore.jks|' "$APP_DIR/conf/mirth.properties" + sed -i "s/^keystore\.storepass\s*=\s*.*\$/keystore.storepass = changeme/" "$APP_DIR/conf/mirth.properties" + sed -i "s/^keystore\.keypass\s*=\s*.*\$/keystore.keypass = changeme/" "$APP_DIR/conf/mirth.properties" + sed -i "s/^keystore\.type\s*=\s*.*\$/keystore.type = JCEKS/" "$APP_DIR/conf/mirth.properties" +fi # merge the environment variables into /opt/engine/conf/mirth.properties # db type @@ -230,9 +238,9 @@ fi if ! [ -z "${KEYSTORE_DOWNLOAD+x}" ]; then echo "Downloading keystore at ${KEYSTORE_DOWNLOAD}" if ! [ -z "${ALLOW_INSECURE}" ] && [ "${ALLOW_INSECURE}" == "true" ]; then - curl -ksSLf "${KEYSTORE_DOWNLOAD}" -o "$APP_DIR/appdata/keystore.jks" || echo "problem with keystore download" + curl -ksSLf "${KEYSTORE_DOWNLOAD}" -o "$LEGACY_KEYSTORE_FILE" || echo "problem with keystore download" else - curl -sSLf "${KEYSTORE_DOWNLOAD}" -o "$APP_DIR/appdata/keystore.jks" || echo "problem with keystore download" + curl -sSLf "${KEYSTORE_DOWNLOAD}" -o "$LEGACY_KEYSTORE_FILE" || echo "problem with keystore download" fi fi diff --git a/server/conf/mirth.properties b/server/conf/mirth.properties index 4c98942771..c095576e3d 100644 --- a/server/conf/mirth.properties +++ b/server/conf/mirth.properties @@ -25,10 +25,13 @@ password.reuselimit = 0 version = 4.7.0 # keystore -keystore.path = ${dir.appdata}/keystore.jks -keystore.storepass = 81uWxplDtB -keystore.keypass = 81uWxplDtB -keystore.type = JCEKS +# Created if missing with no passphrase and secured by chmod 600. +keystore.path = ${dir.appdata}/keystore.pfx +keystore.storepass = +keystore.keypass = +# Set to JCEKS for compatibility with older versions of the engine. +# a PKCS12 is a standard pfx file. JCEKS is a the older java-specific jks format. +keystore.type = PKCS12 # server http.contextpath = / diff --git a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java index d96c81e05f..8bdd9ee235 100644 --- a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java +++ b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java @@ -13,6 +13,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; @@ -121,6 +122,7 @@ import com.mirth.connect.server.mybatis.KeyValuePair; import com.mirth.connect.server.tools.ClassPathResource; import com.mirth.connect.server.util.DatabaseUtil; +import com.mirth.connect.server.util.FilePermissionUtil; import com.mirth.connect.server.util.PasswordRequirementsChecker; import com.mirth.connect.server.util.ResourceUtil; import com.mirth.connect.server.util.SqlConfig; @@ -195,8 +197,6 @@ public class DefaultConfigurationController extends ConfigurationController { private static final String XSTREAM_ALLOW_TYPES = "xstream.allowtypes"; private static final String XSTREAM_ALLOW_TYPE_HIERARCHIES = "xstream.allowtypehierarchies"; - private static final String DEFAULT_STOREPASS = "81uWxplDtB"; - // singleton pattern private static ConfigurationController instance = null; @@ -1272,22 +1272,6 @@ public void initializeSecuritySettings() { keyStore.load(keyStoreFileIs, keyStorePassword); logger.debug("found and loaded keystore: " + keyStoreFile.getAbsolutePath()); } else { - /* - * If a new keystore is being created, and the passwords are the defaults, then - * create new passwords. - */ - if (Arrays.equals(keyStorePassword, DEFAULT_STOREPASS.toCharArray()) && Arrays.equals(keyPassword, DEFAULT_STOREPASS.toCharArray())) { - String keyStorePasswordStr = generateNewPassword(); - mirthConfig.setProperty("keystore.storepass", keyStorePasswordStr); - keyStorePassword = keyStorePasswordStr.toCharArray(); - - String keyPasswordStr = generateNewPassword(); - mirthConfig.setProperty("keystore.keypass", keyPasswordStr); - keyPassword = keyPasswordStr.toCharArray(); - - saveMirthConfig(); - } - keyStore.load(null, keyStorePassword); logger.debug("keystore file not found, created new one"); } @@ -1296,6 +1280,7 @@ public void initializeSecuritySettings() { generateDefaultCertificate(provider, keyStore, keyPassword); // write the keystore back to the file + FilePermissionUtil.createOwnerOnlyFile(keyStoreFile); fos = new FileOutputStream(keyStoreFile); keyStore.store(fos, keyStorePassword); } catch (Exception e) { @@ -1306,19 +1291,6 @@ public void initializeSecuritySettings() { } } - /** - * Creates a random 12-character alphanumeric password. - */ - private String generateNewPassword() { - String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - SecureRandom random = new SecureRandom(); - StringBuilder builder = new StringBuilder(); - for (int i = 1; i <= 12; i++) { - builder.append(characters.charAt(random.nextInt(characters.length()))); - } - return builder.toString(); - } - @Override public void initializeDatabaseSettings() { try { diff --git a/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java b/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java new file mode 100644 index 0000000000..52a43303e1 --- /dev/null +++ b/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java @@ -0,0 +1,81 @@ +package com.mirth.connect.server.util; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.AclEntry; +import java.nio.file.attribute.AclEntryPermission; +import java.nio.file.attribute.AclEntryType; +import java.nio.file.attribute.AclFileAttributeView; +import java.nio.file.attribute.PosixFileAttributeView; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.nio.file.attribute.UserPrincipal; +import java.util.Collections; +import java.util.EnumSet; +import java.util.Set; + +public class FilePermissionUtil { + + private static final Set OWNER_ONLY = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE); + + private FilePermissionUtil() {} + + /* + * Creates the file if it does not already exist, and restricts it so that only the user the + * server runs as may read or write it. This is what protects files that hold key material in + * place of a passphrase, so the file must never be created readable and then locked down + * afterwards; on POSIX the permissions are applied as part of the create itself. + */ + public static void createOwnerOnlyFile(File file) throws IOException { + Path path = file.toPath(); + + if (!Files.exists(path)) { + File parent = file.getParentFile(); + + if (parent != null) { + Files.createDirectories(parent.toPath()); + } + + if (isPosix(path)) { + Files.createFile(path, PosixFilePermissions.asFileAttribute(OWNER_ONLY)); + return; + } + + Files.createFile(path); + } + + restrictToOwner(path); + } + + /* + * Replaces the permissions on an existing file with owner read/write only. On Windows the + * entire ACL is replaced with a single entry for the file's owner, which also detaches the file + * from any permissions inherited from its parent directory. + */ + private static void restrictToOwner(Path path) throws IOException { + if (isPosix(path)) { + Files.setPosixFilePermissions(path, OWNER_ONLY); + return; + } + + AclFileAttributeView aclView = Files.getFileAttributeView(path, AclFileAttributeView.class); + + if (aclView != null) { + UserPrincipal owner = aclView.getOwner(); + // @formatter:off + AclEntry entry = AclEntry.newBuilder() + .setType(AclEntryType.ALLOW) + .setPrincipal(owner) + .setPermissions(EnumSet.allOf(AclEntryPermission.class)) + .build(); + // @formatter:on + aclView.setAcl(Collections.singletonList(entry)); + } + } + + private static boolean isPosix(Path path) { + return Files.getFileAttributeView(path, PosixFileAttributeView.class) != null; + } +} diff --git a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java new file mode 100644 index 0000000000..3e7ba102f7 --- /dev/null +++ b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java @@ -0,0 +1,61 @@ +package com.mirth.connect.server.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeTrue; + +import java.io.File; +import java.io.FileOutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFileAttributeView; +import java.nio.file.attribute.PosixFilePermissions; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +public class FilePermissionUtilTest { + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void testCreatesMissingFileOwnerOnly() throws Exception { + File file = new File(temporaryFolder.getRoot(), "nested/keystore.p12"); + + FilePermissionUtil.createOwnerOnlyFile(file); + + assertTrue(file.exists()); + assertPermissions(file); + } + + @Test + public void testRestrictsExistingFile() throws Exception { + File file = temporaryFolder.newFile("keystore.p12"); + assumeTrue(file.setReadable(true, false)); + + FilePermissionUtil.createOwnerOnlyFile(file); + + assertPermissions(file); + } + + @Test + public void testPreservesExistingContent() throws Exception { + File file = temporaryFolder.newFile("keystore.p12"); + + try (FileOutputStream fos = new FileOutputStream(file)) { + fos.write(new byte[] { 1, 2, 3 }); + } + + FilePermissionUtil.createOwnerOnlyFile(file); + + assertEquals(3, file.length()); + } + + private void assertPermissions(File file) throws Exception { + Path path = file.toPath(); + assumeTrue(Files.getFileAttributeView(path, PosixFileAttributeView.class) != null); + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(path))); + } +} diff --git a/server/src/test/resources/mirth.properties b/server/src/test/resources/mirth.properties index 52d6d9d4d2..7a6d16cc7a 100644 --- a/server/src/test/resources/mirth.properties +++ b/server/src/test/resources/mirth.properties @@ -25,10 +25,10 @@ password.reuselimit = 0 version = 4.7.0 # keystore -keystore.path = ${dir.appdata}/keystore.jks -keystore.storepass = 81uWxplDtB -keystore.keypass = 81uWxplDtB -keystore.type = JCEKS +keystore.path = ${dir.appdata}/keystore.pfx +keystore.storepass = +keystore.keypass = +keystore.type = PKCS12 # server http.contextpath = / From 7f51d4daabb3ac3908bb7d2736782bd347e56585 Mon Sep 17 00:00:00 2001 From: Mitch Gaffigan Date: Thu, 27 Aug 2026 11:53:51 -0500 Subject: [PATCH 02/14] Use SDDL on windows to secure keystore to BA,SY,CO Signed-off-by: Mitch Gaffigan --- .../DefaultConfigurationController.java | 2 +- .../server/util/FilePermissionUtil.java | 65 +++---------- .../util/WindowsFilePermissionUtil.java | 94 +++++++++++++++++++ .../server/util/FilePermissionUtilTest.java | 65 ++++++++----- 4 files changed, 146 insertions(+), 80 deletions(-) create mode 100644 server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java diff --git a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java index 8bdd9ee235..150470a452 100644 --- a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java +++ b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java @@ -1274,13 +1274,13 @@ public void initializeSecuritySettings() { } else { keyStore.load(null, keyStorePassword); logger.debug("keystore file not found, created new one"); + FilePermissionUtil.createOwnerOnlyFile(keyStoreFile); } configureEncryption(provider, keyStore, keyPassword); generateDefaultCertificate(provider, keyStore, keyPassword); // write the keystore back to the file - FilePermissionUtil.createOwnerOnlyFile(keyStoreFile); fos = new FileOutputStream(keyStoreFile); keyStore.store(fos, keyStorePassword); } catch (Exception e) { diff --git a/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java b/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java index 52a43303e1..68f41e3f89 100644 --- a/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java +++ b/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java @@ -4,18 +4,13 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.attribute.AclEntry; -import java.nio.file.attribute.AclEntryPermission; -import java.nio.file.attribute.AclEntryType; -import java.nio.file.attribute.AclFileAttributeView; -import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; -import java.nio.file.attribute.UserPrincipal; -import java.util.Collections; import java.util.EnumSet; import java.util.Set; +import com.sun.jna.Platform; + public class FilePermissionUtil { private static final Set OWNER_ONLY = EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE); @@ -23,59 +18,21 @@ public class FilePermissionUtil { private FilePermissionUtil() {} /* - * Creates the file if it does not already exist, and restricts it so that only the user the - * server runs as may read or write it. This is what protects files that hold key material in - * place of a passphrase, so the file must never be created readable and then locked down - * afterwards; on POSIX the permissions are applied as part of the create itself. + * Creates a file that only the account the server runs as, and whoever administers the machine, + * may read or write. */ public static void createOwnerOnlyFile(File file) throws IOException { Path path = file.toPath(); + File parent = file.getParentFile(); - if (!Files.exists(path)) { - File parent = file.getParentFile(); - - if (parent != null) { - Files.createDirectories(parent.toPath()); - } - - if (isPosix(path)) { - Files.createFile(path, PosixFilePermissions.asFileAttribute(OWNER_ONLY)); - return; - } - - Files.createFile(path); + if (parent != null) { + Files.createDirectories(parent.toPath()); } - restrictToOwner(path); - } - - /* - * Replaces the permissions on an existing file with owner read/write only. On Windows the - * entire ACL is replaced with a single entry for the file's owner, which also detaches the file - * from any permissions inherited from its parent directory. - */ - private static void restrictToOwner(Path path) throws IOException { - if (isPosix(path)) { - Files.setPosixFilePermissions(path, OWNER_ONLY); - return; - } - - AclFileAttributeView aclView = Files.getFileAttributeView(path, AclFileAttributeView.class); - - if (aclView != null) { - UserPrincipal owner = aclView.getOwner(); - // @formatter:off - AclEntry entry = AclEntry.newBuilder() - .setType(AclEntryType.ALLOW) - .setPrincipal(owner) - .setPermissions(EnumSet.allOf(AclEntryPermission.class)) - .build(); - // @formatter:on - aclView.setAcl(Collections.singletonList(entry)); + if (Platform.isWindows()) { + WindowsFilePermissionUtil.createRestrictedFile(path); + } else { + Files.createFile(path, PosixFilePermissions.asFileAttribute(OWNER_ONLY)); } } - - private static boolean isPosix(Path path) { - return Files.getFileAttributeView(path, PosixFileAttributeView.class) != null; - } } diff --git a/server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java b/server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java new file mode 100644 index 0000000000..47d65b07d7 --- /dev/null +++ b/server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java @@ -0,0 +1,94 @@ +package com.mirth.connect.server.util; + +import java.io.IOException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Path; + +import com.sun.jna.Native; +import com.sun.jna.Pointer; +import com.sun.jna.platform.win32.Kernel32; +import com.sun.jna.platform.win32.Kernel32Util; +import com.sun.jna.platform.win32.WinBase; +import com.sun.jna.platform.win32.WinError; +import com.sun.jna.platform.win32.WinNT; +import com.sun.jna.platform.win32.WinNT.HANDLE; +import com.sun.jna.ptr.IntByReference; +import com.sun.jna.ptr.PointerByReference; +import com.sun.jna.win32.StdCallLibrary; +import com.sun.jna.win32.W32APIOptions; +import com.sun.security.auth.module.NTSystem; + +/* + * The Windows half of FilePermissionUtil, kept apart so that nothing here is loaded on a platform + * that has no Win32 API to call. + */ +class WindowsFilePermissionUtil { + + /* + * Full control to creator, LocalSystem and the local administrators. Matches + * user profile directories. + */ + private static final String SDDL = "D:P(A;;FA;;;{CURRENTUSERSID})(A;;FA;;;SY)(A;;FA;;;BA)"; + + private static final int SDDL_REVISION_1 = 1; + + /* + * The SDDL conversions are not part of JNA's Advapi32 mapping. + */ + private interface Advapi32Sddl extends StdCallLibrary { + Advapi32Sddl INSTANCE = Native.loadLibrary("Advapi32", Advapi32Sddl.class, W32APIOptions.DEFAULT_OPTIONS); + + boolean ConvertStringSecurityDescriptorToSecurityDescriptor(String sddl, int revision, PointerByReference securityDescriptor, IntByReference size); + } + + private WindowsFilePermissionUtil() {} + + /* + * Creates the file with a DACL that only lets the account the server runs as and the machine's + * administrators near it. The DACL is handed to CreateFile rather than applied afterwards, so + * the file is never briefly readable by anyone else. + */ + static void createRestrictedFile(Path path) throws IOException { + Pointer securityDescriptor = buildSecurityDescriptor(); + + try { + createFile(path, securityDescriptor); + } finally { + Kernel32.INSTANCE.LocalFree(securityDescriptor); + } + } + + private static Pointer buildSecurityDescriptor() throws IOException { + PointerByReference securityDescriptor = new PointerByReference(); + + String sddl = SDDL.replace("{CURRENTUSERSID}", new NTSystem().getUserSID()); + if (!Advapi32Sddl.INSTANCE.ConvertStringSecurityDescriptorToSecurityDescriptor(sddl, SDDL_REVISION_1, securityDescriptor, null)) { + throw lastError("Could not build a security descriptor from \"" + sddl + "\""); + } + + return securityDescriptor.getValue(); + } + + private static void createFile(Path path, Pointer securityDescriptor) throws IOException { + WinBase.SECURITY_ATTRIBUTES securityAttributes = new WinBase.SECURITY_ATTRIBUTES(); + securityAttributes.lpSecurityDescriptor = securityDescriptor; + securityAttributes.bInheritHandle = false; + + HANDLE handle = Kernel32.INSTANCE.CreateFile(path.toAbsolutePath().toString(), WinNT.GENERIC_WRITE, 0, securityAttributes, WinNT.CREATE_NEW, WinNT.FILE_ATTRIBUTE_NORMAL, null); + + if (WinBase.INVALID_HANDLE_VALUE.equals(handle)) { + // reported the same way as Files.createFile, so that callers need not care which is which + if (Kernel32.INSTANCE.GetLastError() == WinError.ERROR_FILE_EXISTS) { + throw new FileAlreadyExistsException(path.toString()); + } + + throw lastError("Could not create " + path); + } + + Kernel32.INSTANCE.CloseHandle(handle); + } + + private static IOException lastError(String message) { + return new IOException(message + ": " + Kernel32Util.formatMessage(Kernel32.INSTANCE.GetLastError())); + } +} diff --git a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java index 3e7ba102f7..fe21cde443 100644 --- a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java +++ b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java @@ -2,60 +2,75 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import java.io.File; -import java.io.FileOutputStream; +import java.nio.charset.Charset; import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.PosixFilePermissions; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.apache.commons.io.IOUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; +import com.sun.jna.Platform; + public class FilePermissionUtilTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @Test - public void testCreatesMissingFileOwnerOnly() throws Exception { - File file = new File(temporaryFolder.getRoot(), "nested/keystore.p12"); + public void testPosixPermissions() throws Exception { + assumeFalse("Test only applies on POSIX filesystems", Platform.isWindows()); + File file = new File(temporaryFolder.getRoot(), "keystore.p12"); FilePermissionUtil.createOwnerOnlyFile(file); - assertTrue(file.exists()); - assertPermissions(file); + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(file.toPath()))); } @Test - public void testRestrictsExistingFile() throws Exception { - File file = temporaryFolder.newFile("keystore.p12"); - assumeTrue(file.setReadable(true, false)); + public void testWindowsPermissions() throws Exception { + assumeTrue("Test only applies on windows", Platform.isWindows()); + assumeTrue("Test assumes english locale", System.getProperty("user.language").equals("en")); + File file = new File(temporaryFolder.getRoot(), "keystore.p12"); + String path = file.getAbsolutePath(); FilePermissionUtil.createOwnerOnlyFile(file); - - assertPermissions(file); + var icaclsOutput = system("icacls", path); + assertContains(icaclsOutput, System.getProperty("user.name") + ":(F)"); + assertContains(icaclsOutput, "BUILTIN\\Administrators:(F)"); + assertContains(icaclsOutput, "NT AUTHORITY\\SYSTEM:(F)"); + assertNotContains(icaclsOutput, "Everyone:"); + assertNotContains(icaclsOutput, "Users:"); + assertNotContains(icaclsOutput, "(I)" /* inherited permissions */); } - @Test - public void testPreservesExistingContent() throws Exception { - File file = temporaryFolder.newFile("keystore.p12"); + private void assertContains(String output, String expected) { + assertTrue("Expected output to contain '" + expected + "' but was '" + output + "'", output.contains(expected)); + } - try (FileOutputStream fos = new FileOutputStream(file)) { - fos.write(new byte[] { 1, 2, 3 }); - } + private void assertNotContains(String output, String expected) { + assertFalse("Expected output to not contain '" + expected + "' but was '" + output + "'", output.contains(expected)); + } - FilePermissionUtil.createOwnerOnlyFile(file); + private String system(String command, String... arguments) throws Exception { + List commandLine = new ArrayList(); + commandLine.add(command); + commandLine.addAll(Arrays.asList(arguments)); - assertEquals(3, file.length()); - } + Process process = new ProcessBuilder(commandLine).redirectErrorStream(true).start(); + String output = IOUtils.toString(process.getInputStream(), Charset.defaultCharset()); - private void assertPermissions(File file) throws Exception { - Path path = file.toPath(); - assumeTrue(Files.getFileAttributeView(path, PosixFileAttributeView.class) != null); - assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(path))); + assertEquals(output, 0, process.waitFor()); + return output; } } From 40b5d76e7016b5aa8c8baf1559f71e1a7709b901 Mon Sep 17 00:00:00 2001 From: Tony Germano Date: Tue, 13 Oct 2026 02:54:57 -0400 Subject: [PATCH 03/14] Add SPDX headers and fix keystore comments and imports Add SPDX headers to the new FilePermissionUtil, WindowsFilePermissionUtil and FilePermissionUtilTest files, and drop an unused import from DefaultConfigurationController. Reword the keystore comment in mirth.properties. It now says that the keystore is protected by file permissions on every platform, not just "chmod 600", and that keeping a JCEKS keystore means setting the path, both passwords and the type, not the type alone. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Tony Germano --- server/conf/mirth.properties | 8 +++++--- .../controllers/DefaultConfigurationController.java | 1 - .../com/mirth/connect/server/util/FilePermissionUtil.java | 3 +++ .../connect/server/util/WindowsFilePermissionUtil.java | 3 +++ .../mirth/connect/server/util/FilePermissionUtilTest.java | 3 +++ 5 files changed, 14 insertions(+), 4 deletions(-) diff --git a/server/conf/mirth.properties b/server/conf/mirth.properties index c095576e3d..5c48f52709 100644 --- a/server/conf/mirth.properties +++ b/server/conf/mirth.properties @@ -25,12 +25,14 @@ password.reuselimit = 0 version = 4.7.0 # keystore -# Created if missing with no passphrase and secured by chmod 600. +# Created if missing, with no passphrase. Instead, file permissions limit access to the account +# the server runs as (and administrators on Windows). +# PKCS12 is the standard pfx format. JCEKS is the older Java-specific format used by earlier +# versions of the engine; to keep using a JCEKS keystore, set keystore.path, keystore.storepass, +# keystore.keypass and keystore.type to match it. keystore.path = ${dir.appdata}/keystore.pfx keystore.storepass = keystore.keypass = -# Set to JCEKS for compatibility with older versions of the engine. -# a PKCS12 is a standard pfx file. JCEKS is a the older java-specific jks format. keystore.type = PKCS12 # server diff --git a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java index 150470a452..f9b4d363c7 100644 --- a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java +++ b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java @@ -13,7 +13,6 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; -import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; diff --git a/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java b/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java index 68f41e3f89..df8069db19 100644 --- a/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java +++ b/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java @@ -1,3 +1,6 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: Mitch Gaffigan + package com.mirth.connect.server.util; import java.io.File; diff --git a/server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java b/server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java index 47d65b07d7..e4661e6e98 100644 --- a/server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java +++ b/server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java @@ -1,3 +1,6 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: Mitch Gaffigan + package com.mirth.connect.server.util; import java.io.IOException; diff --git a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java index fe21cde443..a9b9ea589c 100644 --- a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java +++ b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java @@ -1,3 +1,6 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: Mitch Gaffigan + package com.mirth.connect.server.util; import static org.junit.Assert.assertEquals; From 552cc6f847eb9321cad5e1da847f550904780644 Mon Sep 17 00:00:00 2001 From: Tony Germano Date: Sun, 30 Aug 2026 23:58:54 -0400 Subject: [PATCH 04/14] refactor: modernize keystore file handling with NIO.2 and try-with-resources Updated `DefaultConfigurationController.initializeSecuritySettings` to use `java.nio.file.Path` and `Files` in place of legacy `java.io.File`, and changed `FilePermissionUtil.createOwnerOnlyFile` and its tests to take a `Path` to match. Key changes and benefits: - Replaced `FileInputStream` and `FileOutputStream` with `Files.newInputStream` and `Files.newOutputStream`. - Implemented try-with-resources, removing boilerplate `finally` blocks and `ResourceUtil.closeResourceQuietly` calls. - Fixed a silent failure risk: exceptions thrown during the output stream's `close()` operation (e.g., when flushing to a full disk) are now properly caught and logged instead of being swallowed. - Leveraged modern `Path.of()` for path instantiation. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Tony Germano --- .../DefaultConfigurationController.java | 24 +++++++++---------- .../server/util/FilePermissionUtil.java | 8 +++---- .../server/util/FilePermissionUtilTest.java | 15 ++++++------ 3 files changed, 21 insertions(+), 26 deletions(-) diff --git a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java index f9b4d363c7..a8260a067b 100644 --- a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java +++ b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java @@ -20,6 +20,8 @@ import java.math.BigInteger; import java.net.URI; import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; @@ -1243,16 +1245,13 @@ public void setChannelMetadata(Map channelMetadata) { @Override public void initializeSecuritySettings() { - InputStream keyStoreFileIs = null; - FileOutputStream fos = null; - try { /* * Load the encryption settings so that they can be referenced client side. */ encryptionConfig = new EncryptionSettings(ConfigurationConverter.getProperties(mirthConfig)); - File keyStoreFile = new File(mirthConfig.getString("keystore.path")); + Path keyStoreFile = Path.of(mirthConfig.getString("keystore.path")); char[] keyStorePassword = mirthConfig.getString("keystore.storepass").toCharArray(); char[] keyPassword = mirthConfig.getString("keystore.keypass").toCharArray(); Provider provider = (Provider) Class.forName(encryptionConfig.getSecurityProvider()).newInstance(); @@ -1266,10 +1265,11 @@ public void initializeSecuritySettings() { keyStore = KeyStore.getInstance(mirthConfig.getString("keystore.type", "JCEKS")); } - if (keyStoreFile.exists()) { - keyStoreFileIs = new FileInputStream(keyStoreFile); - keyStore.load(keyStoreFileIs, keyStorePassword); - logger.debug("found and loaded keystore: " + keyStoreFile.getAbsolutePath()); + if (Files.exists(keyStoreFile)) { + try (InputStream keyStoreFileIs = Files.newInputStream(keyStoreFile)) { + keyStore.load(keyStoreFileIs, keyStorePassword); + logger.debug("found and loaded keystore: " + keyStoreFile.toAbsolutePath().toString()); + } } else { keyStore.load(null, keyStorePassword); logger.debug("keystore file not found, created new one"); @@ -1280,13 +1280,11 @@ public void initializeSecuritySettings() { generateDefaultCertificate(provider, keyStore, keyPassword); // write the keystore back to the file - fos = new FileOutputStream(keyStoreFile); - keyStore.store(fos, keyStorePassword); + try (OutputStream fos = Files.newOutputStream(keyStoreFile)) { + keyStore.store(fos, keyStorePassword); + } } catch (Exception e) { logger.error("Could not initialize security settings.", e); - } finally { - ResourceUtil.closeResourceQuietly(keyStoreFileIs); - ResourceUtil.closeResourceQuietly(fos); } } diff --git a/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java b/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java index df8069db19..f41783f7b1 100644 --- a/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java +++ b/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java @@ -3,7 +3,6 @@ package com.mirth.connect.server.util; -import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -24,12 +23,11 @@ private FilePermissionUtil() {} * Creates a file that only the account the server runs as, and whoever administers the machine, * may read or write. */ - public static void createOwnerOnlyFile(File file) throws IOException { - Path path = file.toPath(); - File parent = file.getParentFile(); + public static void createOwnerOnlyFile(Path path) throws IOException { + Path parent = path.toAbsolutePath().getParent(); if (parent != null) { - Files.createDirectories(parent.toPath()); + Files.createDirectories(parent); } if (Platform.isWindows()) { diff --git a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java index a9b9ea589c..ce887771c3 100644 --- a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java +++ b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java @@ -9,9 +9,9 @@ import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; -import java.io.File; import java.nio.charset.Charset; import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermissions; import java.util.ArrayList; import java.util.Arrays; @@ -33,22 +33,21 @@ public class FilePermissionUtilTest { @Test public void testPosixPermissions() throws Exception { assumeFalse("Test only applies on POSIX filesystems", Platform.isWindows()); - File file = new File(temporaryFolder.getRoot(), "keystore.p12"); + Path path = temporaryFolder.getRoot().toPath().resolve("keystore.p12"); - FilePermissionUtil.createOwnerOnlyFile(file); + FilePermissionUtil.createOwnerOnlyFile(path); - assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(file.toPath()))); + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(path))); } @Test public void testWindowsPermissions() throws Exception { assumeTrue("Test only applies on windows", Platform.isWindows()); assumeTrue("Test assumes english locale", System.getProperty("user.language").equals("en")); - File file = new File(temporaryFolder.getRoot(), "keystore.p12"); - String path = file.getAbsolutePath(); + Path path = temporaryFolder.getRoot().toPath().resolve("keystore.p12"); - FilePermissionUtil.createOwnerOnlyFile(file); - var icaclsOutput = system("icacls", path); + FilePermissionUtil.createOwnerOnlyFile(path); + var icaclsOutput = system("icacls", path.toAbsolutePath().toString()); assertContains(icaclsOutput, System.getProperty("user.name") + ":(F)"); assertContains(icaclsOutput, "BUILTIN\\Administrators:(F)"); assertContains(icaclsOutput, "NT AUTHORITY\\SYSTEM:(F)"); From 8a548c401d1853d1fd324dfae24ccd83589dbb77 Mon Sep 17 00:00:00 2001 From: Tony Germano Date: Tue, 13 Oct 2026 02:54:57 -0400 Subject: [PATCH 05/14] Make FilePermissionUtilTest independent of the Windows display language The Windows test matched account names in icacls output, which Windows translates into the display language, so it was skipped on non-English systems. Its user.language check also did not reliably match the language icacls prints in. Read the file's ACL through JNA instead and compare SIDs, which are the same in every language. The test now requires exactly the expected entries (the current user, LocalSystem and Administrators, each with full control and none inherited) rather than ruling out a few names. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Tony Germano --- .../server/util/FilePermissionUtilTest.java | 58 ++++++++----------- 1 file changed, 23 insertions(+), 35 deletions(-) diff --git a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java index ce887771c3..07a79015a2 100644 --- a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java +++ b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java @@ -1,35 +1,37 @@ // SPDX-License-Identifier: MPL-2.0 // SPDX-FileCopyrightText: Mitch Gaffigan +// SPDX-FileCopyrightText: 2026 Tony Germano package com.mirth.connect.server.util; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; -import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermissions; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +import java.util.HashMap; +import java.util.Map; -import org.apache.commons.io.IOUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.sun.jna.Platform; +import com.sun.jna.platform.win32.Advapi32Util; +import com.sun.jna.platform.win32.WinNT; +import com.sun.security.auth.module.NTSystem; public class FilePermissionUtilTest { + // well-known SIDs, which unlike account names are the same in every Windows language + private static final String LOCAL_SYSTEM_SID = "S-1-5-18"; + private static final String ADMINISTRATORS_SID = "S-1-5-32-544"; + @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); - @Test public void testPosixPermissions() throws Exception { assumeFalse("Test only applies on POSIX filesystems", Platform.isWindows()); @@ -43,36 +45,22 @@ public void testPosixPermissions() throws Exception { @Test public void testWindowsPermissions() throws Exception { assumeTrue("Test only applies on windows", Platform.isWindows()); - assumeTrue("Test assumes english locale", System.getProperty("user.language").equals("en")); Path path = temporaryFolder.getRoot().toPath().resolve("keystore.p12"); FilePermissionUtil.createOwnerOnlyFile(path); - var icaclsOutput = system("icacls", path.toAbsolutePath().toString()); - assertContains(icaclsOutput, System.getProperty("user.name") + ":(F)"); - assertContains(icaclsOutput, "BUILTIN\\Administrators:(F)"); - assertContains(icaclsOutput, "NT AUTHORITY\\SYSTEM:(F)"); - assertNotContains(icaclsOutput, "Everyone:"); - assertNotContains(icaclsOutput, "Users:"); - assertNotContains(icaclsOutput, "(I)" /* inherited permissions */); - } - - private void assertContains(String output, String expected) { - assertTrue("Expected output to contain '" + expected + "' but was '" + output + "'", output.contains(expected)); - } - - private void assertNotContains(String output, String expected) { - assertFalse("Expected output to not contain '" + expected + "' but was '" + output + "'", output.contains(expected)); - } - - private String system(String command, String... arguments) throws Exception { - List commandLine = new ArrayList(); - commandLine.add(command); - commandLine.addAll(Arrays.asList(arguments)); - - Process process = new ProcessBuilder(commandLine).redirectErrorStream(true).start(); - String output = IOUtils.toString(process.getInputStream(), Charset.defaultCharset()); - assertEquals(output, 0, process.waitFor()); - return output; + Map grants = new HashMap(); + for (WinNT.ACCESS_ACEStructure ace : Advapi32Util.getFileSecurity(path.toAbsolutePath().toString(), false)) { + assertEquals("ACE type for " + ace.getSidString(), WinNT.ACCESS_ALLOWED_ACE_TYPE, ace.AceType); + assertEquals("ACE for " + ace.getSidString() + " is inherited", 0, ace.AceFlags & WinNT.INHERITED_ACE); + grants.put(ace.getSidString(), ace.Mask); + } + + // when running as LocalSystem, the current user and LocalSystem are the same entry + Map expected = new HashMap(); + expected.put(new NTSystem().getUserSID(), WinNT.FILE_ALL_ACCESS); + expected.put(LOCAL_SYSTEM_SID, WinNT.FILE_ALL_ACCESS); + expected.put(ADMINISTRATORS_SID, WinNT.FILE_ALL_ACCESS); + assertEquals(expected, grants); } } From 1b0b1db45c56e4c8524069e9e5bab9356dba2305 Mon Sep 17 00:00:00 2001 From: Tony Germano Date: Tue, 13 Oct 2026 02:54:57 -0400 Subject: [PATCH 06/14] Refuse to create a new keystore when a legacy keystore.jks exists The default keystore path changed from keystore.jks to keystore.pfx. If an existing appdata directory is used with a fresh mirth.properties, the server would not find keystore.pfx and would create a new keystore with a new encryption key, leaving anything already encrypted in the database unreadable. Before this change, the mismatched password made that case fail loudly instead. When the configured keystore is missing but appdata/keystore.jks exists, fail security initialization with a message that says which settings to fix, rather than creating a new keystore. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Tony Germano --- .../controllers/DefaultConfigurationController.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java index a8260a067b..605c24bbcd 100644 --- a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java +++ b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java @@ -1271,6 +1271,17 @@ public void initializeSecuritySettings() { logger.debug("found and loaded keystore: " + keyStoreFile.toAbsolutePath().toString()); } } else { + /* + * Earlier versions kept the keystore at ${dir.appdata}/keystore.jks. If that file is + * still here, mirth.properties no longer points at it, and creating a new keystore + * would generate a new encryption key, leaving anything already encrypted in the + * database unreadable. + */ + Path legacyKeyStoreFile = Path.of(getApplicationDataDir(), "keystore.jks"); + if (Files.exists(legacyKeyStoreFile)) { + throw new IllegalStateException("Keystore " + keyStoreFile.toAbsolutePath() + " not found, but an existing keystore was found at " + legacyKeyStoreFile.toAbsolutePath() + ". Not creating a new keystore, because it would replace the encryption key. Set keystore.path, keystore.storepass, keystore.keypass and keystore.type in mirth.properties to match the existing keystore."); + } + keyStore.load(null, keyStorePassword); logger.debug("keystore file not found, created new one"); FilePermissionUtil.createOwnerOnlyFile(keyStoreFile); From f0879ca8a6df32dc12b72c47e830a2767783f995 Mon Sep 17 00:00:00 2001 From: Tony Germano Date: Tue, 13 Oct 2026 02:54:57 -0400 Subject: [PATCH 07/14] Restrict permissions on a downloaded keystore and tidy configure-from-env The keystore is now protected by file permissions rather than a password, but a keystore fetched with KEYSTORE_DOWNLOAD was written using the default umask. Download it with umask 077, and chmod it afterwards in case an existing file was overwritten. A failed chmod only warns, so it cannot stop the container from starting. Also drop the unused KEYSTORE_FILE variable, and log whether an existing keystore or KEYSTORE_DOWNLOAD caused the switch to the JCEKS settings. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Tony Germano --- server/basedir-includes/configure-from-env | 23 ++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/server/basedir-includes/configure-from-env b/server/basedir-includes/configure-from-env index a5f6a00b5b..5833dd1a87 100755 --- a/server/basedir-includes/configure-from-env +++ b/server/basedir-includes/configure-from-env @@ -19,10 +19,13 @@ fi # The keystore is created with no passphrase and protected by file permissions instead, so there is # no longer a password to pin here. Keystores created by earlier versions are JCEKS and were pinned # to 'changeme', so keep those settings when one is already present in appdata. -KEYSTORE_FILE="$APP_DIR/appdata/keystore.pfx" LEGACY_KEYSTORE_FILE="$APP_DIR/appdata/keystore.jks" if [ -f "$LEGACY_KEYSTORE_FILE" ] || ! [ -z "${KEYSTORE_DOWNLOAD+x}" ]; then - echo "Found an existing keystore at ${LEGACY_KEYSTORE_FILE}, using jks keystore defaults." + if [ -f "$LEGACY_KEYSTORE_FILE" ]; then + echo "Found an existing keystore at ${LEGACY_KEYSTORE_FILE}, using jks keystore defaults." + else + echo "KEYSTORE_DOWNLOAD is set, using jks keystore defaults." + fi sed -i 's|^keystore\.path\s*=\s*.*$|keystore.path = ${dir.appdata}/keystore.jks|' "$APP_DIR/conf/mirth.properties" sed -i "s/^keystore\.storepass\s*=\s*.*\$/keystore.storepass = changeme/" "$APP_DIR/conf/mirth.properties" sed -i "s/^keystore\.keypass\s*=\s*.*\$/keystore.keypass = changeme/" "$APP_DIR/conf/mirth.properties" @@ -237,10 +240,18 @@ fi # download keystore if ! [ -z "${KEYSTORE_DOWNLOAD+x}" ]; then echo "Downloading keystore at ${KEYSTORE_DOWNLOAD}" - if ! [ -z "${ALLOW_INSECURE}" ] && [ "${ALLOW_INSECURE}" == "true" ]; then - curl -ksSLf "${KEYSTORE_DOWNLOAD}" -o "$LEGACY_KEYSTORE_FILE" || echo "problem with keystore download" - else - curl -sSLf "${KEYSTORE_DOWNLOAD}" -o "$LEGACY_KEYSTORE_FILE" || echo "problem with keystore download" + # the keystore is only as private as its file permissions, so never let it be readable by others + ( + umask 077 + if ! [ -z "${ALLOW_INSECURE}" ] && [ "${ALLOW_INSECURE}" == "true" ]; then + curl -ksSLf "${KEYSTORE_DOWNLOAD}" -o "$LEGACY_KEYSTORE_FILE" || echo "problem with keystore download" + else + curl -sSLf "${KEYSTORE_DOWNLOAD}" -o "$LEGACY_KEYSTORE_FILE" || echo "problem with keystore download" + fi + ) + # umask does not apply when curl overwrites an existing file + if [ -f "$LEGACY_KEYSTORE_FILE" ]; then + chmod 600 "$LEGACY_KEYSTORE_FILE" || echo "could not restrict permissions on ${LEGACY_KEYSTORE_FILE}" fi fi From 6c39ab7b7adf582dea2ab022348cc893c1ebd1b3 Mon Sep 17 00:00:00 2001 From: Tony Germano Date: Tue, 13 Oct 2026 03:54:49 -0400 Subject: [PATCH 08/14] Write keystore atomically and only when it changes * Write the keystore to an owner-only temp file in the same directory and atomically move it into place, so a failure part way through can no longer leave an empty or truncated keystore that prevents startup. Because the file is replaced, a rewritten keystore always ends up with owner-only permissions, even if they were changed by hand. * Only write the keystore when it is new or an entry was added, instead of rewriting an unchanged keystore on every startup. * Replace the target of a symlinked keystore rather than the link itself. * Document that FilePermissionUtil.createOwnerOnlyFile throws FileAlreadyExistsException if the file already exists. * Add tests for creating missing parent directories and for FileAlreadyExistsException. * Replace the license header of DefaultConfigurationController with SPDX identifiers. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Tony Germano --- .../DefaultConfigurationController.java | 53 ++++++++++++++----- .../server/util/FilePermissionUtil.java | 15 ++++-- .../server/util/FilePermissionUtilTest.java | 18 +++++++ 3 files changed, 70 insertions(+), 16 deletions(-) diff --git a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java index 605c24bbcd..fe58103a5a 100644 --- a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java +++ b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java @@ -1,11 +1,7 @@ -/* - * Copyright (c) Mirth Corporation. All rights reserved. - * - * http://www.mirthcorp.com - * - * The software in this package is published under the terms of the MPL license a copy of which has - * been included with this distribution in the LICENSE.txt file. - */ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: Mirth Corporation +// SPDX-FileCopyrightText: 2026 Mitch Gaffigan +// SPDX-FileCopyrightText: 2026 Tony Germano package com.mirth.connect.server.controllers; @@ -20,8 +16,10 @@ import java.math.BigInteger; import java.net.URI; import java.nio.charset.Charset; +import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardCopyOption; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; @@ -1284,21 +1282,52 @@ public void initializeSecuritySettings() { keyStore.load(null, keyStorePassword); logger.debug("keystore file not found, created new one"); - FilePermissionUtil.createOwnerOnlyFile(keyStoreFile); } + // Entries are only ever added below, never replaced, so a change in size means the keystore changed + int originalSize = keyStore.size(); + configureEncryption(provider, keyStore, keyPassword); generateDefaultCertificate(provider, keyStore, keyPassword); - // write the keystore back to the file - try (OutputStream fos = Files.newOutputStream(keyStoreFile)) { - keyStore.store(fos, keyStorePassword); + if (!Files.exists(keyStoreFile) || keyStore.size() != originalSize) { + storeKeyStore(keyStore, keyStoreFile, keyStorePassword); } } catch (Exception e) { logger.error("Could not initialize security settings.", e); } } + /* + * Writes the keystore to a new owner-only temp file in the same directory and then moves it + * into place, so that a failure part way through never leaves a truncated or empty keystore + * behind, and the keystore is never readable by other users, even briefly. + */ + private void storeKeyStore(KeyStore keyStore, Path keyStoreFile, char[] keyStorePassword) throws Exception { + // Replace the target of a symlink rather than the link itself + Path target = Files.isSymbolicLink(keyStoreFile) ? keyStoreFile.toRealPath() : keyStoreFile; + Path tempFile = target.resolveSibling(target.getFileName() + ".tmp"); + + // Remove a temp file left behind by a previous failed write + Files.deleteIfExists(tempFile); + + try { + FilePermissionUtil.createOwnerOnlyFile(tempFile); + + try (OutputStream os = Files.newOutputStream(tempFile)) { + keyStore.store(os, keyStorePassword); + } + + try { + Files.move(tempFile, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING); + } + } finally { + Files.deleteIfExists(tempFile); + } + } + @Override public void initializeDatabaseSettings() { try { diff --git a/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java b/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java index f41783f7b1..0ae3601e30 100644 --- a/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java +++ b/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java @@ -1,9 +1,11 @@ // SPDX-License-Identifier: MPL-2.0 // SPDX-FileCopyrightText: Mitch Gaffigan +// SPDX-FileCopyrightText: 2026 Tony Germano package com.mirth.connect.server.util; import java.io.IOException; +import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; @@ -19,11 +21,16 @@ public class FilePermissionUtil { private FilePermissionUtil() {} - /* - * Creates a file that only the account the server runs as, and whoever administers the machine, - * may read or write. + /** + * Creates a new file that only the account the server runs as, and whoever administers the + * machine, may read or write. The permissions are applied as part of the create itself, so the + * file is never briefly readable by anyone else. + * + * @param path The path of the file to create. + * @throws FileAlreadyExistsException If a file of that name already exists. + * @throws IOException If an I/O error occurs, or the permissions cannot be applied. */ - public static void createOwnerOnlyFile(Path path) throws IOException { + public static void createOwnerOnlyFile(Path path) throws FileAlreadyExistsException, IOException { Path parent = path.toAbsolutePath().getParent(); if (parent != null) { diff --git a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java index 07a79015a2..14d01a88a6 100644 --- a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java +++ b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java @@ -5,9 +5,11 @@ package com.mirth.connect.server.util; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; +import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermissions; @@ -32,6 +34,22 @@ public class FilePermissionUtilTest { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @Test + public void testCreatesMissingParentDirectories() throws Exception { + Path path = temporaryFolder.getRoot().toPath().resolve("nested/keystore.p12"); + + FilePermissionUtil.createOwnerOnlyFile(path); + + assertTrue(Files.exists(path)); + } + + @Test(expected = FileAlreadyExistsException.class) + public void testThrowsIfFileExists() throws Exception { + Path path = temporaryFolder.newFile("keystore.p12").toPath(); + + FilePermissionUtil.createOwnerOnlyFile(path); + } + @Test public void testPosixPermissions() throws Exception { assumeFalse("Test only applies on POSIX filesystems", Platform.isWindows()); From a972eaed4c333ef2b9cef0a0ed21cba955d32610 Mon Sep 17 00:00:00 2001 From: Tony Germano Date: Tue, 13 Oct 2026 03:49:55 -0400 Subject: [PATCH 09/14] Don't run with an encryption key that couldn't be saved initializeSecuritySettings sets up the encryptor, and puts the key in the encryption settings it sends to the Administrator, before the keystore is written. If a new encryption key is generated and writing the keystore then fails, the error was only logged and the server kept encrypting data with a key that would be gone after a restart, leaving that data unreadable. The Administrator would also encrypt exports with that key. When storing the keystore fails and the encryption key is new, clear the encryptor and the key in the encryption settings, so the failure leaves the server and its clients without encryption, the same as any other failure to initialize security settings. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Tony Germano --- .../DefaultConfigurationController.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java index fe58103a5a..498a2eb78c 100644 --- a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java +++ b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java @@ -1286,12 +1286,26 @@ public void initializeSecuritySettings() { // Entries are only ever added below, never replaced, so a change in size means the keystore changed int originalSize = keyStore.size(); + boolean newEncryptionKey = !keyStore.containsAlias(SECRET_KEY_ALIAS); configureEncryption(provider, keyStore, keyPassword); generateDefaultCertificate(provider, keyStore, keyPassword); if (!Files.exists(keyStoreFile) || keyStore.size() != originalSize) { - storeKeyStore(keyStore, keyStoreFile, keyStorePassword); + try { + storeKeyStore(keyStore, keyStoreFile, keyStorePassword); + } catch (Exception e) { + /* + * Anything encrypted with a key that was never saved could not be decrypted + * after a restart, so don't leave the server, or the clients it sends its + * encryption settings to, with one. + */ + if (newEncryptionKey) { + encryptor = null; + encryptionConfig.setSecretKey(null); + } + throw e; + } } } catch (Exception e) { logger.error("Could not initialize security settings.", e); From dd091d109eb7df34215c7df61938f853c5dc9535 Mon Sep 17 00:00:00 2001 From: Tony Germano Date: Sat, 7 Nov 2026 11:04:07 -0500 Subject: [PATCH 10/14] Test creating an owner-only file with a long path on Windows WindowsFilePermissionUtil passes the path to CreateFile as is. The Win32 file APIs reject paths longer than MAX_PATH (260 characters) unless they use the \\?\ extended-length form, which java.nio adds for its own calls but JNA does not, so creating a keystore under a deeply nested appdata directory is expected to fail. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Tony Germano --- .../server/util/FilePermissionUtilTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java index 14d01a88a6..a36b23b622 100644 --- a/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java +++ b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java @@ -81,4 +81,20 @@ public void testWindowsPermissions() throws Exception { expected.put(ADMINISTRATORS_SID, WinNT.FILE_ALL_ACCESS); assertEquals(expected, grants); } + + @Test + public void testWindowsLongPath() throws Exception { + assumeTrue("Test only applies on windows", Platform.isWindows()); + + // longer than MAX_PATH (260), which the Win32 file APIs reject without the \\?\ prefix + Path directory = temporaryFolder.getRoot().toPath(); + while (directory.toAbsolutePath().toString().length() < 300) { + directory = directory.resolve("a".repeat(50)); + } + Path path = directory.resolve("keystore.p12"); + + FilePermissionUtil.createOwnerOnlyFile(path); + + assertTrue(Files.exists(path)); + } } From 902be8fa21a0277f278ac4b1190fcb9fa125b6c7 Mon Sep 17 00:00:00 2001 From: Tony Germano Date: Sat, 7 Nov 2026 11:07:15 -0500 Subject: [PATCH 11/14] Support long paths when creating an owner-only file on Windows CreateFile rejects paths longer than MAX_PATH (260 characters) unless they are in the \\?\ extended-length form. java.nio adds that prefix for its own calls, but the path passed to CreateFile through JNA did not have it, so a keystore under a deeply nested appdata directory could not be created. Pass CreateFile the extended-length form of the path, using \\?\UNC\ for UNC paths. Because that form turns off the handling of "." and "..", normalize the absolute path first. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Tony Germano --- .../util/WindowsFilePermissionUtil.java | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java b/server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java index e4661e6e98..c3ba6a734b 100644 --- a/server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java +++ b/server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java @@ -77,7 +77,7 @@ private static void createFile(Path path, Pointer securityDescriptor) throws IOE securityAttributes.lpSecurityDescriptor = securityDescriptor; securityAttributes.bInheritHandle = false; - HANDLE handle = Kernel32.INSTANCE.CreateFile(path.toAbsolutePath().toString(), WinNT.GENERIC_WRITE, 0, securityAttributes, WinNT.CREATE_NEW, WinNT.FILE_ATTRIBUTE_NORMAL, null); + HANDLE handle = Kernel32.INSTANCE.CreateFile(toExtendedLengthPath(path), WinNT.GENERIC_WRITE, 0, securityAttributes, WinNT.CREATE_NEW, WinNT.FILE_ATTRIBUTE_NORMAL, null); if (WinBase.INVALID_HANDLE_VALUE.equals(handle)) { // reported the same way as Files.createFile, so that callers need not care which is which @@ -91,6 +91,24 @@ private static void createFile(Path path, Pointer securityDescriptor) throws IOE Kernel32.INSTANCE.CloseHandle(handle); } + /* + * CreateFile rejects paths longer than MAX_PATH unless they are in the \\?\ extended-length + * form, which java.nio adds for its own calls but JNA does not. That form also turns off the + * handling of "." and "..", so the path is normalized first. + */ + private static String toExtendedLengthPath(Path path) { + String absolutePath = path.toAbsolutePath().normalize().toString(); + + if (absolutePath.startsWith("\\\\?\\")) { + return absolutePath; + } else if (absolutePath.startsWith("\\\\")) { + // a UNC path, \\server\share\... + return "\\\\?\\UNC\\" + absolutePath.substring(2); + } else { + return "\\\\?\\" + absolutePath; + } + } + private static IOException lastError(String message) { return new IOException(message + ": " + Kernel32Util.formatMessage(Kernel32.INSTANCE.GetLastError())); } From a3c2f235667395b2fdd8585b6b7e10ba29fb74c2 Mon Sep 17 00:00:00 2001 From: Tony Germano Date: Sat, 7 Nov 2026 12:32:05 -0500 Subject: [PATCH 12/14] Create the keystore behind a symlink whose target doesn't exist yet On main, keystore.path could be a symlink to a file that didn't exist yet: FileOutputStream followed the link and created the target. Since the keystore is written to a temp file and moved into place, the link was resolved with Path.toRealPath, which fails with NoSuchFileException when the target doesn't exist, so the first start failed. Follow the link, and any links it leads to, with Files.readSymbolicLink instead, so the target need not exist. The new target is created with owner-only permissions, and a cycle of links fails after 40 steps rather than looping forever. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Tony Germano --- .../DefaultConfigurationController.java | 24 ++++++++- .../DefaultConfigurationControllerTest.java | 54 +++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) diff --git a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java index 498a2eb78c..104825fa90 100644 --- a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java +++ b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java @@ -9,6 +9,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; @@ -17,6 +18,7 @@ import java.net.URI; import java.nio.charset.Charset; import java.nio.file.AtomicMoveNotSupportedException; +import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; @@ -1319,7 +1321,7 @@ public void initializeSecuritySettings() { */ private void storeKeyStore(KeyStore keyStore, Path keyStoreFile, char[] keyStorePassword) throws Exception { // Replace the target of a symlink rather than the link itself - Path target = Files.isSymbolicLink(keyStoreFile) ? keyStoreFile.toRealPath() : keyStoreFile; + Path target = resolveSymbolicLinks(keyStoreFile); Path tempFile = target.resolveSibling(target.getFileName() + ".tmp"); // Remove a temp file left behind by a previous failed write @@ -1342,6 +1344,26 @@ private void storeKeyStore(KeyStore keyStore, Path keyStoreFile, char[] keyStore } } + /* + * Follows a symlink, and any symlinks it leads to, to the file it ends at. Unlike + * Path.toRealPath, the file need not exist yet, so that a link created ahead of the keystore + * still has its target filled in. + */ + static Path resolveSymbolicLinks(Path path) throws IOException { + Path target = path; + + // the same limit Linux puts on following symlinks, so that a cycle can't loop forever + for (int i = 0; i < 40 && Files.isSymbolicLink(target); i++) { + target = target.resolveSibling(Files.readSymbolicLink(target)); + } + + if (Files.isSymbolicLink(target)) { + throw new FileSystemException(path.toString(), null, "Too many levels of symbolic links"); + } + + return target; + } + @Override public void initializeDatabaseSettings() { try { diff --git a/server/src/test/java/com/mirth/connect/server/controllers/DefaultConfigurationControllerTest.java b/server/src/test/java/com/mirth/connect/server/controllers/DefaultConfigurationControllerTest.java index ab37ab7526..550b752769 100644 --- a/server/src/test/java/com/mirth/connect/server/controllers/DefaultConfigurationControllerTest.java +++ b/server/src/test/java/com/mirth/connect/server/controllers/DefaultConfigurationControllerTest.java @@ -13,6 +13,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.junit.Assume.assumeNoException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; @@ -27,6 +28,9 @@ import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; +import java.nio.file.FileSystemException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -45,7 +49,9 @@ import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.mockito.invocation.Invocation; import org.xml.sax.SAXParseException; @@ -59,6 +65,9 @@ public class DefaultConfigurationControllerTest { private static StaticOverride factoryOverride; + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @BeforeClass public static void setup() throws Exception { ControllerFactory controllerFactory = mock(ControllerFactory.class); @@ -522,6 +531,51 @@ private String normalizeXml(String xml) throws Exception { return writer.toString(); } + @Test + public void resolveSymbolicLinks_NotALink() throws Exception { + Path file = temporaryFolder.newFile("keystore.pfx").toPath(); + + assertEquals(file, DefaultConfigurationController.resolveSymbolicLinks(file)); + } + + @Test + public void resolveSymbolicLinks_TargetDoesNotExist() throws Exception { + Path directory = temporaryFolder.getRoot().toPath(); + Path target = directory.resolve("secret/keystore.pfx"); + Path link = createSymbolicLink(directory.resolve("keystore.pfx"), target); + + assertEquals(target, DefaultConfigurationController.resolveSymbolicLinks(link)); + } + + @Test + public void resolveSymbolicLinks_RelativeChain() throws Exception { + Path directory = temporaryFolder.getRoot().toPath(); + Files.createDirectories(directory.resolve("secret")); + createSymbolicLink(directory.resolve("secret/current.pfx"), Path.of("keystore-1.pfx")); + Path link = createSymbolicLink(directory.resolve("keystore.pfx"), Path.of("secret", "current.pfx")); + + assertEquals(directory.resolve("secret/keystore-1.pfx"), DefaultConfigurationController.resolveSymbolicLinks(link)); + } + + @Test(expected = FileSystemException.class) + public void resolveSymbolicLinks_Cycle() throws Exception { + Path directory = temporaryFolder.getRoot().toPath(); + createSymbolicLink(directory.resolve("a.pfx"), directory.resolve("b.pfx")); + Path link = createSymbolicLink(directory.resolve("b.pfx"), directory.resolve("a.pfx")); + + DefaultConfigurationController.resolveSymbolicLinks(link); + } + + // creating a symlink needs a privilege on Windows, so skip the test where it isn't allowed + private static Path createSymbolicLink(Path link, Path target) { + try { + return Files.createSymbolicLink(link, target); + } catch (Exception e) { + assumeNoException(e); + return null; + } + } + private static final String INITIAL_CONFIGURATION_MAP_XML = """ From 2a2a8cac6cf9e1ab61dfc2aa762330d2f124e578 Mon Sep 17 00:00:00 2001 From: Tony Germano Date: Sun, 8 Nov 2026 21:16:23 -0500 Subject: [PATCH 13/14] Flush the keystore to disk before moving it into place The keystore is written to a temp file and renamed over the old one, but nothing made sure the contents were on disk first. After a crash or power loss, some filesystems can then leave an empty file in place of the keystore, and the first write is the one that carries a newly generated encryption key. Write the temp file through a FileChannel and force it to disk before the move, then flush the directory so the rename itself is kept. Flushing a directory isn't possible on every platform, such as Windows, and the keystore is already in place by then, so a failure there is only logged at debug level. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Tony Germano --- .../DefaultConfigurationController.java | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java index 104825fa90..8cb5f09b48 100644 --- a/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java +++ b/server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java @@ -16,12 +16,15 @@ import java.io.Reader; import java.math.BigInteger; import java.net.URI; +import java.nio.channels.Channels; +import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.file.AtomicMoveNotSupportedException; import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; @@ -1330,8 +1333,13 @@ private void storeKeyStore(KeyStore keyStore, Path keyStoreFile, char[] keyStore try { FilePermissionUtil.createOwnerOnlyFile(tempFile); - try (OutputStream os = Files.newOutputStream(tempFile)) { - keyStore.store(os, keyStorePassword); + try (FileChannel channel = FileChannel.open(tempFile, StandardOpenOption.WRITE)) { + keyStore.store(Channels.newOutputStream(channel), keyStorePassword); + /* + * Make sure the contents are on disk before the move, or a crash soon after could + * leave an empty keystore in place of the old one. + */ + channel.force(true); } try { @@ -1339,11 +1347,26 @@ private void storeKeyStore(KeyStore keyStore, Path keyStoreFile, char[] keyStore } catch (AtomicMoveNotSupportedException e) { Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING); } + + syncDirectory(target.toAbsolutePath().getParent()); } finally { Files.deleteIfExists(tempFile); } } + /* + * Flushes a directory to disk, so that a file just moved into it is still there after a crash. + * Not every platform can open a directory this way (Windows can't), and the move itself has + * already succeeded, so a failure is only logged. + */ + private void syncDirectory(Path directory) { + try (FileChannel channel = FileChannel.open(directory, StandardOpenOption.READ)) { + channel.force(true); + } catch (IOException e) { + logger.debug("Could not flush directory " + directory + " to disk", e); + } + } + /* * Follows a symlink, and any symlinks it leads to, to the file it ends at. Unlike * Path.toRealPath, the file need not exist yet, so that a link created ahead of the keystore From 399776bc76b5cdb889dda1b2dfc7524c5252e70a Mon Sep 17 00:00:00 2001 From: Tony Germano Date: Sun, 8 Nov 2026 21:16:23 -0500 Subject: [PATCH 14/14] Restrict an existing keystore before downloading over it When KEYSTORE_DOWNLOAD replaces an existing keystore.jks, curl keeps the file's mode, so a file that was readable by others held the downloaded keystore until the chmod after the download. Restrict the existing file before downloading instead. A new file is still created with umask 077, so the chmod afterwards is no longer needed. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Tony Germano --- server/basedir-includes/configure-from-env | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/server/basedir-includes/configure-from-env b/server/basedir-includes/configure-from-env index 5833dd1a87..2c8f67d515 100755 --- a/server/basedir-includes/configure-from-env +++ b/server/basedir-includes/configure-from-env @@ -240,7 +240,11 @@ fi # download keystore if ! [ -z "${KEYSTORE_DOWNLOAD+x}" ]; then echo "Downloading keystore at ${KEYSTORE_DOWNLOAD}" - # the keystore is only as private as its file permissions, so never let it be readable by others + # the keystore is only as private as its file permissions, so never let it be readable by others. + # umask does not apply when curl overwrites an existing file, so restrict that before downloading. + if [ -f "$LEGACY_KEYSTORE_FILE" ]; then + chmod 600 "$LEGACY_KEYSTORE_FILE" || echo "could not restrict permissions on ${LEGACY_KEYSTORE_FILE}" + fi ( umask 077 if ! [ -z "${ALLOW_INSECURE}" ] && [ "${ALLOW_INSECURE}" == "true" ]; then @@ -249,10 +253,6 @@ if ! [ -z "${KEYSTORE_DOWNLOAD+x}" ]; then curl -sSLf "${KEYSTORE_DOWNLOAD}" -o "$LEGACY_KEYSTORE_FILE" || echo "problem with keystore download" fi ) - # umask does not apply when curl overwrites an existing file - if [ -f "$LEGACY_KEYSTORE_FILE" ]; then - chmod 600 "$LEGACY_KEYSTORE_FILE" || echo "could not restrict permissions on ${LEGACY_KEYSTORE_FILE}" - fi fi # if delay is set as an environment variable then wait that long in seconds