diff --git a/server/basedir-includes/configure-from-env b/server/basedir-includes/configure-from-env index 3ab0ebbb7b..2c8f67d515 100755 --- a/server/basedir-includes/configure-from-env +++ b/server/basedir-includes/configure-from-env @@ -16,10 +16,21 @@ 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. +LEGACY_KEYSTORE_FILE="$APP_DIR/appdata/keystore.jks" +if [ -f "$LEGACY_KEYSTORE_FILE" ] || ! [ -z "${KEYSTORE_DOWNLOAD+x}" ]; then + 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" + 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 @@ -229,11 +240,19 @@ 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 "$APP_DIR/appdata/keystore.jks" || echo "problem with keystore download" - else - curl -sSLf "${KEYSTORE_DOWNLOAD}" -o "$APP_DIR/appdata/keystore.jks" || echo "problem with keystore download" + # 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 + 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 + ) fi # if delay is set as an environment variable then wait that long in seconds diff --git a/server/conf/mirth.properties b/server/conf/mirth.properties index 4c98942771..5c48f52709 100644 --- a/server/conf/mirth.properties +++ b/server/conf/mirth.properties @@ -25,10 +25,15 @@ 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. 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 = +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..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 @@ -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; @@ -13,13 +9,22 @@ 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; 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; @@ -121,6 +126,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 +201,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; @@ -1244,16 +1248,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(); @@ -1267,56 +1268,123 @@ 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 { /* - * If a new keystore is being created, and the passwords are the defaults, then - * create new passwords. + * 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. */ - 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(); + 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"); } + // 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); - // write the keystore back to the file - fos = new FileOutputStream(keyStoreFile); - keyStore.store(fos, keyStorePassword); + if (!Files.exists(keyStoreFile) || keyStore.size() != originalSize) { + 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); + } + } + + /* + * 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 = resolveSymbolicLinks(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 (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 { + Files.move(tempFile, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } catch (AtomicMoveNotSupportedException e) { + Files.move(tempFile, target, StandardCopyOption.REPLACE_EXISTING); + } + + syncDirectory(target.toAbsolutePath().getParent()); } finally { - ResourceUtil.closeResourceQuietly(keyStoreFileIs); - ResourceUtil.closeResourceQuietly(fos); + Files.deleteIfExists(tempFile); } } - /** - * Creates a random 12-character alphanumeric password. + /* + * 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 + * still has its target filled in. */ - 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()))); + 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)); } - return builder.toString(); + + if (Files.isSymbolicLink(target)) { + throw new FileSystemException(path.toString(), null, "Too many levels of symbolic links"); + } + + return target; } @Override 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..0ae3601e30 --- /dev/null +++ b/server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java @@ -0,0 +1,46 @@ +// 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; +import java.nio.file.attribute.PosixFilePermissions; +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); + + private FilePermissionUtil() {} + + /** + * 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 FileAlreadyExistsException, IOException { + Path parent = path.toAbsolutePath().getParent(); + + if (parent != null) { + Files.createDirectories(parent); + } + + if (Platform.isWindows()) { + WindowsFilePermissionUtil.createRestrictedFile(path); + } else { + Files.createFile(path, PosixFilePermissions.asFileAttribute(OWNER_ONLY)); + } + } +} 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..c3ba6a734b --- /dev/null +++ b/server/src/main/java/com/mirth/connect/server/util/WindowsFilePermissionUtil.java @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: Mitch Gaffigan + +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(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 + if (Kernel32.INSTANCE.GetLastError() == WinError.ERROR_FILE_EXISTS) { + throw new FileAlreadyExistsException(path.toString()); + } + + throw lastError("Could not create " + path); + } + + 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())); + } +} 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 = """ 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..a36b23b622 --- /dev/null +++ b/server/src/test/java/com/mirth/connect/server/util/FilePermissionUtilTest.java @@ -0,0 +1,100 @@ +// 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.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; +import java.util.HashMap; +import java.util.Map; + +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 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()); + Path path = temporaryFolder.getRoot().toPath().resolve("keystore.p12"); + + FilePermissionUtil.createOwnerOnlyFile(path); + + assertEquals("rw-------", PosixFilePermissions.toString(Files.getPosixFilePermissions(path))); + } + + @Test + public void testWindowsPermissions() throws Exception { + assumeTrue("Test only applies on windows", Platform.isWindows()); + Path path = temporaryFolder.getRoot().toPath().resolve("keystore.p12"); + + FilePermissionUtil.createOwnerOnlyFile(path); + + 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); + } + + @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)); + } +} 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 = /