Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 27 additions & 8 deletions server/basedir-includes/configure-from-env
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
13 changes: 9 additions & 4 deletions server/conf/mirth.properties
Original file line number Diff line number Diff line change
Expand Up @@ -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 = /
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,30 @@
/*
* 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 <mitch@gaffigan.net>
// SPDX-FileCopyrightText: 2026 Tony Germano <tony@germano.name>

package com.mirth.connect.server.controllers;

import java.io.File;
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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -1244,16 +1248,13 @@ public void setChannelMetadata(Map<String, ChannelMetadata> 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();
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: Mitch Gaffigan <mitch@gaffigan.net>
// SPDX-FileCopyrightText: 2026 Tony Germano <tony@germano.name>

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 {
Comment thread
jonbartels marked this conversation as resolved.
Resolved

private static final Set<PosixFilePermission> 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));
}
}
}
Loading
Loading