@davoodmehraban89 / LifeMate / commits / 79e1211
Fork 0

LifeMate — Personal, Family & Learning Companion

feat: add bounded local keystore inspector and synthetic tests

Quinn White committed Oct 23, 2026 at 10:46 UTC 79e12110ec63b8e886fe5be5641926d0b92bf06c
3 files changed +480
scripts/java/LifeGuideKeyInspector.java new
+222
@@ -0,0 +1,222 @@
1 +import java.io.ByteArrayInputStream;
2 +import java.io.DataInputStream;
3 +import java.io.IOException;
4 +import java.nio.ByteBuffer;
5 +import java.nio.CharBuffer;
6 +import java.nio.charset.CharacterCodingException;
7 +import java.nio.charset.CodingErrorAction;
8 +import java.nio.charset.StandardCharsets;
9 +import java.security.KeyStore;
10 +import java.security.MessageDigest;
11 +import java.security.PrivateKey;
12 +import java.security.SecureRandom;
13 +import java.security.Signature;
14 +import java.security.cert.CertificateExpiredException;
15 +import java.security.cert.CertificateNotYetValidException;
16 +import java.security.cert.X509Certificate;
17 +import java.util.Arrays;
18 +import java.util.HexFormat;
19 +import javax.naming.ldap.LdapName;
20 +import javax.naming.ldap.Rdn;
21 +
22 +/** Reads one bounded stdin frame; emits only public facts or a fixed refusal. */
23 +public final class LifeGuideKeyInspector {
24 + private static final int MAX_STORE_BYTES = 2 * 1024 * 1024;
25 +
26 + private static final class Refusal extends Exception {
27 + final String reason;
28 + Refusal(String reason) { this.reason = reason; }
29 + }
30 +
31 + private static final class Request implements AutoCloseable {
32 + byte[] keystore;
33 + byte[] aliasBytes;
34 + byte[] storePasswordBytes;
35 + byte[] keyPasswordBytes;
36 + String alias;
37 + char[] storePassword;
38 + char[] keyPassword;
39 +
40 + public void close() {
41 + wipe(keystore);
42 + wipe(aliasBytes);
43 + wipe(storePasswordBytes);
44 + wipe(keyPasswordBytes);
45 + if (storePassword != null) Arrays.fill(storePassword, '\0');
46 + if (keyPassword != null) Arrays.fill(keyPassword, '\0');
47 + }
48 + }
49 +
50 + private static void wipe(byte[] bytes) {
51 + if (bytes != null) Arrays.fill(bytes, (byte) 0);
52 + }
53 +
54 + private static byte[] readField(DataInputStream input, int maximum) throws IOException, Refusal {
55 + int length = input.readInt();
56 + // Negative signed values represent unsigned lengths above 2 GiB.
57 + if (length < 1 || length > maximum) throw new Refusal("invalid_request");
58 + byte[] bytes = new byte[length];
59 + try {
60 + input.readFully(bytes);
61 + return bytes;
62 + } catch (IOException exception) {
63 + wipe(bytes);
64 + throw exception;
65 + }
66 + }
67 +
68 + private static char[] decodeUtf8(byte[] bytes) throws CharacterCodingException {
69 + CharBuffer decoded = StandardCharsets.UTF_8.newDecoder()
70 + .onMalformedInput(CodingErrorAction.REPORT)
71 + .onUnmappableCharacter(CodingErrorAction.REPORT)
72 + .decode(ByteBuffer.wrap(bytes));
73 + try {
74 + char[] characters = new char[decoded.remaining()];
75 + decoded.get(characters);
76 + return characters;
77 + } finally {
78 + if (decoded.hasArray()) Arrays.fill(decoded.array(), '\0');
79 + }
80 + }
81 +
82 + private static char[] decodePassword(byte[] bytes) throws Refusal, CharacterCodingException {
83 + char[] characters = decodeUtf8(bytes);
84 + for (char character : characters) {
85 + if (character == '\0' || character == '\r' || character == '\n') {
86 + Arrays.fill(characters, '\0');
87 + throw new Refusal("invalid_request");
88 + }
89 + }
90 + return characters;
91 + }
92 +
93 + private static Request readRequest() throws Refusal {
94 + Request request = new Request();
95 + try {
96 + DataInputStream input = new DataInputStream(System.in);
97 + if (input.readInt() != 0x4c474b49) throw new Refusal("invalid_request");
98 + request.keystore = readField(input, MAX_STORE_BYTES);
99 + request.aliasBytes = readField(input, 256);
100 + request.storePasswordBytes = readField(input, 4096);
101 + request.keyPasswordBytes = readField(input, 4096);
102 + if (input.read() != -1) throw new Refusal("invalid_request");
103 + char[] alias = decodeUtf8(request.aliasBytes);
104 + try {
105 + request.alias = new String(alias);
106 + } finally {
107 + Arrays.fill(alias, '\0');
108 + }
109 + request.storePassword = decodePassword(request.storePasswordBytes);
110 + request.keyPassword = decodePassword(request.keyPasswordBytes);
111 + wipe(request.storePasswordBytes);
112 + wipe(request.keyPasswordBytes);
113 + return request;
114 + } catch (IOException | Refusal exception) {
115 + request.close();
116 + throw new Refusal("invalid_request");
117 + }
118 + }
119 +
120 + private static KeyStore loadStore(Request request) throws Refusal {
121 + for (String format : new String[] {"JKS", "PKCS12"}) {
122 + try {
123 + KeyStore store = KeyStore.getInstance(format);
124 + store.load(new ByteArrayInputStream(request.keystore), request.storePassword);
125 + return store;
126 + } catch (Exception exception) {
127 + // Try only the two supported formats, without exposing provider errors.
128 + }
129 + }
130 + throw new Refusal("keystore_unreadable");
131 + }
132 +
133 + private static KeyStore.PrivateKeyEntry privateEntry(KeyStore store, Request request) throws Refusal {
134 + KeyStore.PasswordProtection protection = new KeyStore.PasswordProtection(request.keyPassword);
135 + try {
136 + if (!store.entryInstanceOf(request.alias, KeyStore.PrivateKeyEntry.class)) {
137 + throw new Refusal("private_key_unavailable");
138 + }
139 + KeyStore.Entry entry = store.getEntry(request.alias, protection);
140 + if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
141 + throw new Refusal("private_key_unavailable");
142 + }
143 + return (KeyStore.PrivateKeyEntry) entry;
144 + } catch (Exception exception) {
145 + throw new Refusal("private_key_unavailable");
146 + } finally {
147 + try { protection.destroy(); } catch (Exception ignored) { }
148 + }
149 + }
150 +
151 + private static void proveKey(PrivateKey key, X509Certificate certificate) throws Refusal {
152 + String algorithm;
153 + switch (key.getAlgorithm()) {
154 + case "RSA": algorithm = "SHA256withRSA"; break;
155 + case "EC": algorithm = "SHA256withECDSA"; break;
156 + default: throw new Refusal("unsupported_key_algorithm");
157 + }
158 + byte[] challenge = new byte[32];
159 + byte[] proof = null;
160 + try {
161 + new SecureRandom().nextBytes(challenge);
162 + Signature signer = Signature.getInstance(algorithm);
163 + signer.initSign(key);
164 + signer.update(challenge);
165 + proof = signer.sign();
166 + Signature verifier = Signature.getInstance(algorithm);
167 + verifier.initVerify(certificate.getPublicKey());
168 + verifier.update(challenge);
169 + if (!verifier.verify(proof)) throw new Refusal("key_proof_failed");
170 + } catch (Exception exception) {
171 + throw new Refusal("key_proof_failed");
172 + } finally {
173 + wipe(challenge);
174 + wipe(proof);
175 + }
176 + }
177 +
178 + private static boolean debugCertificate(X509Certificate certificate) throws Exception {
179 + LdapName name = new LdapName(certificate.getSubjectX500Principal().getName());
180 + for (Rdn rdn : name.getRdns()) {
181 + if ("CN".equalsIgnoreCase(rdn.getType())
182 + && "Android Debug".equalsIgnoreCase(String.valueOf(rdn.getValue()))) return true;
183 + }
184 + return false;
185 + }
186 +
187 + private static String inspect(Request request) throws Exception {
188 + KeyStore.PrivateKeyEntry entry = privateEntry(loadStore(request), request);
189 + if (!(entry.getCertificate() instanceof X509Certificate)) throw new Refusal("inspection_failed");
190 + X509Certificate certificate = (X509Certificate) entry.getCertificate();
191 + proveKey(entry.getPrivateKey(), certificate);
192 + boolean valid = true;
193 + try {
194 + certificate.checkValidity();
195 + } catch (CertificateExpiredException | CertificateNotYetValidException exception) {
196 + valid = false;
197 + }
198 + String fingerprint = HexFormat.of().formatHex(
199 + MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded()));
200 + return "{\"schemaVersion\":1,\"status\":\"INSPECTED\",\"certificateSha256\":\""
201 + + fingerprint + "\",\"debugCertificate\":" + debugCertificate(certificate)
202 + + ",\"privateKeyProof\":true,\"certificateCurrentlyValid\":" + valid + "}";
203 + }
204 +
205 + public static void main(String[] arguments) {
206 + String result;
207 + int exitCode;
208 + try {
209 + if (arguments.length != 0) throw new Refusal("invalid_request");
210 + try (Request request = readRequest()) {
211 + result = inspect(request);
212 + }
213 + exitCode = 0;
214 + } catch (Exception | LinkageError exception) {
215 + String reason = exception instanceof Refusal ? ((Refusal) exception).reason : "inspection_failed";
216 + result = "{\"schemaVersion\":1,\"status\":\"REFUSED\",\"reason\":\"" + reason + "\"}";
217 + exitCode = 2;
218 + }
219 + System.out.println(result);
220 + System.exit(exitCode);
221 + }
222 +}
scripts/tests/signing_test_support.py new
+132
@@ -0,0 +1,132 @@
1 +"""Ephemeral, fictional signing fixtures. Never use with owner material."""
2 +
3 +from contextlib import contextmanager
4 +from dataclasses import dataclass, field
5 +import hashlib
6 +import os
7 +from pathlib import Path
8 +import secrets
9 +import struct
10 +import subprocess
11 +import tempfile
12 +
13 +
14 +ROOT = Path(__file__).resolve().parents[2]
15 +HELPER = ROOT / "scripts/java/LifeGuideKeyInspector.java"
16 +JVM_OPTION_VARIABLES = ("JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "JDK_JAVA_OPTIONS", "CLASSPATH")
17 +
18 +
19 +def clean_java_environment():
20 + return {key: value for key, value in os.environ.items()
21 + if key.upper() not in JVM_OPTION_VARIABLES}
22 +
23 +
24 +def request_frame(keystore, alias, store_password, key_password):
25 + fields = [keystore, alias.encode("utf-8"), store_password.encode("utf-8"),
26 + key_password.encode("utf-8")]
27 + return b"LGKI" + b"".join(struct.pack(">I", len(value)) + value for value in fields)
28 +
29 +
30 +def run_inspector(frame):
31 + return subprocess.run(
32 + ["java", "-Xmx96m", "--source", "17", str(HELPER)], input=frame,
33 + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30,
34 + env=clean_java_environment(), check=False,
35 + )
36 +
37 +
38 +@dataclass(repr=False)
39 +class SyntheticKeystores:
40 + directory: Path
41 + alias: str
42 + store_password: str = field(repr=False)
43 + key_password: str = field(repr=False)
44 +
45 + def __post_init__(self):
46 + self.jks_path = self.directory / "fictional-rsa.jks"
47 + self.pkcs12_path = self.directory / "fictional-ec.p12"
48 + self.debug_path = self.directory / "fictional-debug.jks"
49 + self.cert_only_path = self.directory / "fictional-certificate.jks"
50 + self.dsa_path = self.directory / "fictional-dsa.jks"
51 + self.fingerprints = {}
52 +
53 + def keytool(self, *arguments, input_bytes=None):
54 + environment = clean_java_environment()
55 + environment["LG_TEST_STORE_PASSWORD"] = self.store_password
56 + environment["LG_TEST_KEY_PASSWORD"] = self.key_password
57 + try:
58 + result = subprocess.run(
59 + ["keytool", *map(str, arguments)], input=input_bytes,
60 + stdout=subprocess.PIPE, stderr=subprocess.PIPE,
61 + timeout=30, env=environment, check=False,
62 + )
63 + except (OSError, subprocess.SubprocessError):
64 + raise RuntimeError("synthetic keytool invocation failed") from None
65 + if result.returncode != 0:
66 + raise RuntimeError("synthetic keytool fixture creation failed")
67 + return result.stdout
68 +
69 + def create_key(self, path, algorithm, *, debug=False, expired=False):
70 + pkcs12 = path.suffix == ".p12"
71 + arguments = [
72 + "-genkeypair", "-keystore", path, "-storetype", "PKCS12" if pkcs12 else "JKS",
73 + "-alias", self.alias, "-keyalg", algorithm,
74 + "-dname", "CN=Android Debug,O=Android,C=US" if debug else "CN=Fictional Signing Fixture,O=Example,C=US",
75 + "-validity", "1" if expired else "3650", "-noprompt",
76 + "-storepass:env", "LG_TEST_STORE_PASSWORD",
77 + "-keypass:env", "LG_TEST_STORE_PASSWORD" if pkcs12 else "LG_TEST_KEY_PASSWORD",
78 + ]
79 + if algorithm in ("RSA", "DSA"):
80 + arguments += ["-keysize", "2048"]
81 + if expired:
82 + arguments += ["-startdate", "2020/01/01 00:00:00"]
83 + self.keytool(*arguments)
84 + certificate = self.keytool(
85 + "-exportcert", "-keystore", path, "-alias", self.alias,
86 + "-storepass:env", "LG_TEST_STORE_PASSWORD",
87 + )
88 + self.fingerprints[path] = hashlib.sha256(certificate).hexdigest()
89 + return certificate
90 +
91 + def mismatched_certificate_store(self):
92 + """Replace only a public certificate in a disposable encrypted JKS.
93 +
94 + Its unchanged encrypted private key belongs to a different RSA keypair.
95 + Recompute the legacy JKS integrity checksum so proof is actually reached.
96 + """
97 + def certificate(path):
98 + return self.keytool("-exportcert", "-keystore", path, "-alias", self.alias,
99 + "-storepass:env", "LG_TEST_STORE_PASSWORD")
100 +
101 + original = certificate(self.jks_path)
102 + replacement = certificate(self.debug_path)
103 + body = self.jks_path.read_bytes()[:-20]
104 + offset = body.rfind(original)
105 + if offset < 4 or body[offset - 4:offset] != struct.pack(">I", len(original)):
106 + raise RuntimeError("synthetic JKS certificate framing unavailable")
107 + body = (body[:offset - 4] + struct.pack(">I", len(replacement))
108 + + replacement + body[offset + len(original):])
109 + integrity = hashlib.sha1(self.store_password.encode("utf-16-be")
110 + + b"Mighty Aphrodite" + body).digest()
111 + target = self.directory / "fictional-mismatched.jks"
112 + target.write_bytes(body + integrity)
113 + return target
114 +
115 +
116 +@contextmanager
117 +def synthetic_keystores():
118 + with tempfile.TemporaryDirectory(prefix="lifeguide-synthetic-signing-") as directory:
119 + fixtures = SyntheticKeystores(
120 + Path(directory), "fixture-" + secrets.token_hex(8),
121 + secrets.token_hex(24), secrets.token_hex(24),
122 + )
123 + certificate = fixtures.create_key(fixtures.jks_path, "RSA")
124 + fixtures.create_key(fixtures.pkcs12_path, "EC")
125 + fixtures.create_key(fixtures.debug_path, "RSA", debug=True)
126 + fixtures.create_key(fixtures.dsa_path, "DSA")
127 + fixtures.keytool(
128 + "-importcert", "-keystore", fixtures.cert_only_path, "-storetype", "JKS",
129 + "-alias", fixtures.alias, "-noprompt", "-storepass:env", "LG_TEST_STORE_PASSWORD",
130 + input_bytes=certificate,
131 + )
132 + yield fixtures
scripts/tests/test_signing_java.py new
+126
@@ -0,0 +1,126 @@
1 +"""Real JDK integration, using only disposable fictional keystores."""
2 +
3 +import hashlib
4 +import json
5 +import shutil
6 +import struct
7 +import unittest
8 +
9 +from scripts.tests.signing_test_support import request_frame, run_inspector, synthetic_keystores
10 +
11 +
12 +@unittest.skipUnless(shutil.which("java") and shutil.which("keytool"), "JDK required")
13 +class SigningJavaTests(unittest.TestCase):
14 + @classmethod
15 + def setUpClass(cls):
16 + cls.fixture_context = synthetic_keystores()
17 + cls.fixtures = cls.fixture_context.__enter__()
18 + cls.addClassCleanup(cls.fixture_context.__exit__, None, None, None)
19 +
20 + def inspect(self, path=None, *, alias=None, store_password=None, key_password=None):
21 + fixture = self.fixtures
22 + path = path or fixture.jks_path
23 + frame = request_frame(
24 + path.read_bytes(), alias if alias is not None else fixture.alias,
25 + store_password if store_password is not None else fixture.store_password,
26 + key_password if key_password is not None else (
27 + fixture.store_password if path.suffix == ".p12" else fixture.key_password),
28 + )
29 + return self.parse(run_inspector(frame))
30 +
31 + def parse(self, result):
32 + self.assertIn(result.returncode, (0, 2), "helper must return its fixed protocol status")
33 + self.assertEqual(result.stderr, b"", "helper must suppress raw diagnostic output")
34 + try:
35 + report = json.loads(result.stdout)
36 + except (ValueError, UnicodeDecodeError):
37 + self.fail("helper must return a JSON report")
38 + rendered = result.stdout.decode("utf-8")
39 + for sensitive in (self.fixtures.alias, self.fixtures.store_password,
40 + self.fixtures.key_password, str(self.fixtures.directory)):
41 + self.assertTrue(sensitive not in rendered, "helper output leaked fixture input")
42 + return result.returncode, report
43 +
44 + def assert_refused(self, result, reason):
45 + self.assertEqual(result, (2, {"schemaVersion": 1, "status": "REFUSED", "reason": reason}))
46 +
47 + def test_rsa_jks_proof_repeats_and_source_bytes_stay_unchanged(self):
48 + path = self.fixtures.jks_path
49 + before = hashlib.sha256(path.read_bytes()).digest()
50 + expected = {"schemaVersion": 1, "status": "INSPECTED",
51 + "certificateSha256": self.fixtures.fingerprints[path],
52 + "debugCertificate": False, "privateKeyProof": True,
53 + "certificateCurrentlyValid": True}
54 + self.assertEqual(self.inspect(path), (0, expected))
55 + self.assertEqual(self.inspect(path), (0, expected))
56 + self.assertEqual(hashlib.sha256(path.read_bytes()).digest(), before)
57 +
58 + def test_ec_pkcs12_and_encrypted_copy_have_same_public_facts(self):
59 + source = self.fixtures.pkcs12_path
60 + original = source.read_bytes()
61 + copied = self.fixtures.directory / "encrypted-copy.p12"
62 + copied.write_bytes(original)
63 + expected = {"schemaVersion": 1, "status": "INSPECTED",
64 + "certificateSha256": self.fixtures.fingerprints[source],
65 + "debugCertificate": False, "privateKeyProof": True,
66 + "certificateCurrentlyValid": True}
67 + self.assertEqual(self.inspect(source), (0, expected))
68 + self.assertEqual(self.inspect(copied), (0, expected))
69 + self.assertEqual(source.read_bytes(), original)
70 + self.assertEqual(copied.read_bytes(), original)
71 +
72 + def test_debug_certificate_is_reported(self):
73 + code, report = self.inspect(self.fixtures.debug_path)
74 + self.assertEqual(code, 0)
75 + self.assertIs(report["debugCertificate"], True)
76 +
77 + def test_expired_certificate_is_reported_without_blocking_proof(self):
78 + path = self.fixtures.directory / "expired.jks"
79 + self.fixtures.create_key(path, "RSA", expired=True)
80 + code, report = self.inspect(path)
81 + self.assertEqual(code, 0)
82 + self.assertIs(report["certificateCurrentlyValid"], False)
83 + self.assertIs(report["privateKeyProof"], True)
84 +
85 + def test_wrong_store_password_is_sanitized(self):
86 + self.assert_refused(self.inspect(store_password="canary-wrong-store"), "keystore_unreadable")
87 +
88 + def test_wrong_key_password_is_sanitized(self):
89 + self.assert_refused(self.inspect(key_password="canary-wrong-key"), "private_key_unavailable")
90 +
91 + def test_missing_alias_and_certificate_only_entry_refused(self):
92 + self.assert_refused(self.inspect(alias="canary-missing-alias"), "private_key_unavailable")
93 + self.assert_refused(self.inspect(self.fixtures.cert_only_path), "private_key_unavailable")
94 +
95 + def test_unsupported_dsa_refused(self):
96 + self.assert_refused(self.inspect(self.fixtures.dsa_path), "unsupported_key_algorithm")
97 +
98 + def test_unrelated_rsa_certificate_fails_actual_private_key_proof(self):
99 + path = self.fixtures.mismatched_certificate_store()
100 + self.assert_refused(self.inspect(path), "key_proof_failed")
101 +
102 + def test_corrupt_keystore_refused_without_echo(self):
103 + frame = request_frame(b"canary-corrupt-file", self.fixtures.alias,
104 + self.fixtures.store_password, self.fixtures.key_password)
105 + self.assert_refused(self.parse(run_inspector(frame)), "keystore_unreadable")
106 +
107 + def test_malformed_frames_refused_before_loading(self):
108 + valid = request_frame(self.fixtures.jks_path.read_bytes(), self.fixtures.alias,
109 + self.fixtures.store_password, self.fixtures.key_password)
110 + malformed = [b"", b"BAD!", b"LGKI" + struct.pack(">I", 2 * 1024 * 1024 + 1),
111 + valid[:-1], valid + b"trailing-canary",
112 + request_frame(b"file", "", "pass", "pass"),
113 + request_frame(b"file", "a" * 257, "pass", "pass"),
114 + request_frame(b"file", "alias", "", "pass"),
115 + request_frame(b"file", "alias", "p" * 4097, "pass"),
116 + request_frame(b"file", "alias", "pass", "line\ncanary"),
117 + request_frame(b"file", "alias", "nul\0canary", "pass"),
118 + b"LGKI" + struct.pack(">I", 1) + b"x" + struct.pack(">I", 1) + b"\xff"
119 + + struct.pack(">I", 4) + b"pass" + struct.pack(">I", 4) + b"pass"]
120 + for frame in malformed:
121 + with self.subTest(case=malformed.index(frame)):
122 + self.assert_refused(self.parse(run_inspector(frame)), "invalid_request")
123 +
124 +
125 +if __name__ == "__main__":
126 + unittest.main()