← Back to Pull requests

Secure keystores with filesystem acl, use pkcs12 #422

Open
mgaffigan opened this pull request with 281 lines diff across 7 files
View on GitHub
mgaffigan mgaffigan commented on Aug 26, 2026 22:45 UTC
Author

Related to #307

Sets default access controls for key material created on first boot to only be accessible to the owner (600-equivalent):

Posix:

# ls -al server/setup/appdata/keystore.jks
-rw-------@ 1 user  staff  3973 Aug 26 17:23 server/setup/appdata/keystore.jks

Windows:

PS C:\drop\setup> icacls .\appdata\keystore.jks
.\appdata\keystore.jks COMPUTER\mirthuser:(F)

Successfully processed 1 files; Failed processing 0 files
PS C:\drop\setup>

Removes the 81uWxplDtB password in favor of a password-less PKCS12 (pfx) file instead of the deprecated jks format for new installs. Upgrades retain their prior password.

Diff: 281 lines (+236 / -45) across 7 files Reviewer: jonbartels Review duration: 117533m
All Vouch review confidence checks passed
Residual risk 0.06 = Change Risk (0.53) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.53 · 281 lines diff across 7 files
0.53
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 5 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
88%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.338
Real PR Conversation Timeline
20 items
github-actions[bot] github-actions[bot] commented on Aug 26, 2026 22:55 UTC
Bot

Test Results


  142 files  +1    142 suites  +1   3m 48s ⏱️ +49s
  921 tests +2    920 ✅ +1  1 💤 +1  0 ❌ ±0 
1 053 runs  +2  1 046 ✅ +1  7 💤 +1  0 ❌ ±0 

Results for commit 1ef33281. ± Comparison against base commit 892e33fb.

[test-results]:data:application/gzip;base64,H4sIAM1x72oC/02NSw7DIAwFrxKx7gLzaaCXqSDFEmoSKgKrqHcvofmwnHnWeCXoR7eQRweC3TqyZJ8afOVokg9zEYypIsqYtlkzOOi55GGoil7q7T9b5BRo/FjEdeFiDHE3Mc/1JZV8p6MJVNxP9W/2BzfJym1xCNPkUwECDjlnCqzSBoRUCNIZyntqENFq6xhKK6gk3x+1P8QxCwEAAA==

:recycle: This comment has been updated with latest results.

jonbartels jonbartels commented on code on Aug 26, 2026 23:29 UTC
Code Review
server/basedir-includes/configure-from-env:1
@@ -16,10 +16,16 @@ 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.jks"
+if [ -f "$KEYSTORE_FILE" ] && [ "$(head -c 4 "$KEYSTORE_FILE" | od -An -tx1 | tr -d '[:space:]')" = "cececece" ]; then

Explan what this is checking and how it knows its a jceks?

jonbartels jonbartels commented on code on Aug 26, 2026 23:32 UTC
Code Review
server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java:1
@@ -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 {

Non blocking comment - I checked if file utils does this for us. It does not. I dont live introducing a util class but its appropriate here

jonbartels jonbartels commented on code on Aug 26, 2026 23:33 UTC
Code Review
server/src/test/resources/mirth.properties:1
@@ -25,10 +25,13 @@ password.reuselimit = 0
 version = 4.6.0
 
 # keystore
+# Created if missing with no passphrase and secured by chmod 600.
 keystore.path = ${dir.appdata}/keystore.jks
-keystore.storepass = 81uWxplDtB
-keystore.keypass = 81uWxplDtB
-keystore.type = JCEKS
+keystore.storepass =

Per Tonys comments from chat - add a comment in the props file explaining how this is generated if its blank.

jonbartels jonbartels commented on Aug 26, 2026 23:34 UTC
Reviewer

This is making my brain itch. I feel like there could be some cyclic problem, maybe with containers? where the keystore is generated and a PW set, then the keystore is retained as a file (like if appdata is a persistent volume) but the generated keystore pass isn't retained because conf isnt in a persistent volume and the env var isn't set.

Instinctively - I'd document this, but theres a massive curse of knowledge problem because I am intimate with my keystores but a more casual, first-time user won't know how to process the big error

jonbartels jonbartels commented on code on Aug 26, 2026 23:36 UTC
Code Review
server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java:1
@@ -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 {

Maybe touch to create the file? But then you still gotta mess with perms. https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#touch(java.io.File)

mgaffigan mgaffigan commented on code on Aug 27, 2026 03:30 UTC
Code Review
server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java:1
@@ -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 {

I don't see an alternative here for any major portion.

mgaffigan mgaffigan commented on code on Aug 27, 2026 03:31 UTC
Code Review
server/src/test/resources/mirth.properties:1
@@ -25,10 +25,13 @@ password.reuselimit = 0
 version = 4.6.0
 
 # keystore
+# Created if missing with no passphrase and secured by chmod 600.
 keystore.path = ${dir.appdata}/keystore.jks
-keystore.storepass = 81uWxplDtB
-keystore.keypass = 81uWxplDtB
-keystore.type = JCEKS
+keystore.storepass =

I did on line 28. With pkcs12, there is no need to have a password, so the blank is not a sentinel value - there just is no password.

mgaffigan mgaffigan commented on code on Aug 27, 2026 03:34 UTC
Code Review
server/basedir-includes/configure-from-env:1
@@ -16,10 +16,16 @@ 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.jks"
+if [ -f "$KEYSTORE_FILE" ] && [ "$(head -c 4 "$KEYSTORE_FILE" | od -An -tx1 | tr -d '[:space:]')" = "cececece" ]; then

This is a dirty hack suggested to me by AI. It's checking if the first 4 bytes of the file are cececece - which is the magic signature for a JCEKS keystore (the legacy format that would require the "changeme" default password).

TL;DR: backcompat hack.

tonygermano tonygermano commented on code on Aug 27, 2026 13:48 UTC
Code Review
server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java:1
@@ -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<PosixFilePermission> 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));

I think the local admin group should also be added with full control?

root always has access in linux, but windows does not automatically give permission to local admins.

tonygermano tonygermano commented on code on Aug 27, 2026 14:07 UTC
Code Review
server/conf/mirth.properties:1
@@ -25,10 +25,13 @@ password.reuselimit = 0
 version = 4.6.0
 
 # keystore
+# The keystore is created on first boot with no passphrase and is instead protected by file
+# permissions that restrict it to the user the server runs as. Set storepass/keypass if you would
+# rather protect it with a passphrase, and set type to JCEKS for keystores created before 4.6.0.
 keystore.path = ${dir.appdata}/keystore.jks

Should the file extension change to reflect the new file type?

I don't know when I'll get time to test this myself, but does the channel level encryption still work when the keystore type is PKCS12?

The second use of this keystore is to store the symmetric key for channel encryption. I suspect that's why the default type had not been previously changed, but maybe it's fine.

This unresolved issue and comments may be relevant https://github.com/nextgenhealthcare/connect/issues/4158

tonygermano tonygermano requested changes on Aug 27, 2026 14:34 UTC
Changes Requested Reviewer

Requested changes.

mgaffigan mgaffigan commented on code on Aug 27, 2026 18:09 UTC
Code Review
server/src/main/java/com/mirth/connect/server/util/FilePermissionUtil.java:1
@@ -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<PosixFilePermission> 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));

I agree in principle, but it is a pain. Added as a separate commit in case we change our minds.

mgaffigan mgaffigan commented on code on Aug 27, 2026 18:10 UTC
Code Review
server/conf/mirth.properties:1
@@ -25,10 +25,13 @@ password.reuselimit = 0
 version = 4.6.0
 
 # keystore
+# The keystore is created on first boot with no passphrase and is instead protected by file
+# permissions that restrict it to the user the server runs as. Set storepass/keypass if you would
+# rather protect it with a passphrase, and set type to JCEKS for keystores created before 4.6.0.
 keystore.path = ${dir.appdata}/keystore.jks

Should the file extension change to reflect the new file type?

Sure. Updated. I don't see a problem with this.

does the channel level encryption still work when the keystore type is PKCS12?

If channel encryption is the "Encrypt message contents" checkbox, then yes, it seems to work fine. Database rows seem to reference some AES key:

{alg=AES/CBC/PKCS5Padding,cs=UTF-8,iv=ubupD9l5A2edZnhMyrE63Q==}zotLK9oahMRMDgLFoU4NHECvDfrRSrpwDD4YAjj6W9AE/89CFjyQCOIgN5N/xJUqr4sUzQTMMwbZ
mYtM8fwrk6T32m30b30TLbsuPXQs6MdbHwBY4Coi/ttOxmc0ZHfR46YBgd1LbUzPQNgwoKGZAlfJ
kI61PV1f8vdIDXB9gD3wNw9VegZTSUrbbYoVGvD6RjZdMHGuKqEBfrZaWqD1VnjV63Ii7TKy3GtR
iyPTKbDkEebzj2zJL3H26/I3n6T8IEw058nyO+gs48fOeZKFfBcH7S/6FX2HmrD8pA38LsxDbL+8
+dHJst+N68NwhyYU

mgaffigan mgaffigan commented on code on Aug 27, 2026 18:10 UTC
Code Review
server/basedir-includes/configure-from-env:1
@@ -16,10 +16,16 @@ 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.jks"
+if [ -f "$KEYSTORE_FILE" ] && [ "$(head -c 4 "$KEYSTORE_FILE" | od -An -tx1 | tr -d '[:space:]')" = "cececece" ]; then

I removed it in favor of a filename check.

mgaffigan mgaffigan commented on code on Aug 27, 2026 18:11 UTC
Code Review
server/src/test/resources/mirth.properties:1
@@ -25,10 +25,13 @@ password.reuselimit = 0
 version = 4.6.0
 
 # keystore
+# Created if missing with no passphrase and secured by chmod 600.
 keystore.path = ${dir.appdata}/keystore.jks
-keystore.storepass = 81uWxplDtB
-keystore.keypass = 81uWxplDtB
-keystore.type = JCEKS
+keystore.storepass =

sorry. I was off: this is a test resource, not a published asset.

NicoPiel NicoPiel commented on code on Oct 09, 2026 22:52 UTC
Code Review
server/src/main/java/com/mirth/connect/server/controllers/DefaultConfigurationController.java:1
@@ -1239,24 +1239,9 @@ 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");
+                FilePermissionUtil.createOwnerOnlyFile(keyStoreFile);

A failed first boot leaves an empty keystore that blocks every later boot.
Tthe new createOwnerOnlyFile call creates keystore.pfx before the encryption key and default certificate are generated and written. Before this PR, the file was only created just before writing.
If key or certificate setup throws (for example, a bad encryption setting), the error is only logged and a 0-byte keystore.pfx stays on disk. On the next start the file exists, loading it fails, and security setup fails on every boot until someone deletes the file by hand.
Fix: create the owner-only file right before writing, or delete it when setup fails.

NicoPiel NicoPiel requested changes on Oct 09, 2026 22:53 UTC
Changes Requested Reviewer

Requested changes.

tonygermano tonygermano requested changes on Oct 13, 2026 09:41 UTC
Changes Requested Reviewer

Great foundation! I've got suggestions for several commits to layer on top of this at https://github.com/OpenIntegrationEngine/engine/compare/eef989cb7e218d2fe5e88c8ef11d3dbc91566544...cdfafceb994b2496ae095798e681eedd3596c065

This also addresses the issue that Nico raised.

I have not yet tested building and running on windows.

Reviewers
Assignees
mgaffigan mgaffigan
Labels
risk: low confidence: 88.6% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 52.5% (MEDIUM) · Higher = larger blast radius
52.5%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 88.6% · Lower = rushed or shallow review
88.6%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 6.0% · Safe to merge
6.0%