Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

15.2 KB
Raw Blame
/* eslint-disable no-bitwise */
import crypto, { webcrypto } from "node:crypto";

import * as x509 from "@peculiar/x509";
import forge from "node-forge";

import {
  generateJksFromCertificate,
  generateJksTruststore,
  getJksChainCertificates,
  getJksTruststoreCertificates
} from "./certificate-jks-fns";

x509.cryptoProvider.set(webcrypto as unknown as Crypto);

const issue = (commonName: string, issuer?: { cert: forge.pki.Certificate; key: forge.pki.rsa.PrivateKey }) => {
  const keys = forge.pki.rsa.generateKeyPair(2048);
  const cert = forge.pki.createCertificate();
  cert.publicKey = keys.publicKey;
  cert.serialNumber = "01";
  cert.validity.notBefore = new Date(2026, 0, 1);
  cert.validity.notAfter = new Date(2027, 0, 1);
  cert.setSubject([{ name: "commonName", value: commonName }]);
  cert.setIssuer(issuer ? issuer.cert.subject.attributes : [{ name: "commonName", value: commonName }]);
  cert.sign(issuer?.key ?? keys.privateKey, forge.md.sha256.create());
  return {
    cert,
    key: keys.privateKey,
    certificate: forge.pki.certificateToPem(cert),
    privateKey: forge.pki.privateKeyInfoToPem(forge.pki.wrapRsaPrivateKey(forge.pki.privateKeyToAsn1(keys.privateKey)))
  };
};

const root = issue("Example Root CA");
const intermediate = issue("Example Intermediate CA", root);
const leaf = issue("api.example.com", intermediate);
const PASSWORD = "changeit";

// Generated by keytool (JDK 21): EC P-256 key under alias "fixture", store and key password "fixture-pass".
const KEYTOOL_FIXTURE = Buffer.from(
  "/u3+7QAAAAIAAAABAAAAAQAHZml4dHVyZQAAAaDqvUbzAAAAfTB7MAwGCisGAQQBKgIRAQEEa85lBxPO047apf5vE+Q70kjv1hJI" +
    "vVuYy176lBXWM5C0pq5uWer4VNHz5S25ZCK7Yzkip67DZpg1kBaSbRYTUxPRfaNRemvdTQBfID+iIg05ULsMiM4uWcMIJ+GJoY/o" +
    "iqXRRfquM67jRpo5AAAAAQAFWC41MDkAAAFXMIIBUzCB+6ADAgECAggIyWD0SLAoUTAKBggqhkjOPQQDAzAeMRwwGgYDVQQDExNm" +
    "aXh0dXJlLmV4YW1wbGUuY29tMCAXDTI2MDkyOTAxMTc0OFoYDzIxMjYwOTA1MDExNzQ4WjAeMRwwGgYDVQQDExNmaXh0dXJlLmV4" +
    "YW1wbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEpvjOKJwbb7CHO3P2eA7kxET9VKgloCXf/7iSNDiDLpif5F22PU8z" +
    "P66TOX/rUp5IryrI1uU22vuOG2i5r1tBZKMhMB8wHQYDVR0OBBYEFH0Fjr3VmXu2GJxb7jL90kdUc164MAoGCCqGSM49BAMDA0cA" +
    "MEQCIDwxloYbRpEDa+n3eZmBBxfIQsKVOhLNjovucKf+h4TMAiBlMHTBmX3NJMIO5Kt2/QLYbXmak+6tfW6YP6ko4LEH7fl5g6Nw" +
    "olAes1EqrLjGErvQa1CK",
  "base64"
);

type TParsedEntry =
  | { tag: 1; alias: string; protectedKey: Buffer; chain: Buffer[] }
  | { tag: 2; alias: string; certificate: Buffer };

const javaPassword = (password: string) => Buffer.from(password, "utf16le").swap16();
const sha1 = (...parts: Buffer[]) => parts.reduce((h, p) => h.update(p), crypto.createHash("sha1")).digest();

const parseJks = (buf: Buffer, password: string) => {
  let offset = 0;
  const u16 = () => {
    const v = buf.readUInt16BE(offset);
    offset += 2;
    return v;
  };
  const u32 = () => {
    const v = buf.readUInt32BE(offset);
    offset += 4;
    return v;
  };
  const bytes = (n: number) => {
    const v = buf.subarray(offset, offset + n);
    offset += n;
    return v;
  };
  const utf = () => bytes(u16()).toString("utf8");
  const cert = () => {
    expect(utf()).toBe("X.509");
    return bytes(u32());
  };

  expect(u32()).toBe(0xfeedfeed);
  expect(u32()).toBe(2);
  const count = u32();
  const entries: TParsedEntry[] = [];
  for (let i = 0; i < count; i += 1) {
    const tag = u32();
    const alias = utf();
    bytes(8);
    if (tag === 1) {
      const protectedKey = bytes(u32());
      const chainLength = u32();
      const chain = Array.from({ length: chainLength }, cert);
      entries.push({ tag, alias, protectedKey, chain });
    } else {
      expect(tag).toBe(2);
      entries.push({ tag: 2, alias, certificate: cert() });
    }
  }

  const expectedDigest = sha1(javaPassword(password), Buffer.from("Mighty Aphrodite", "utf8"), buf.subarray(0, offset));
  expect(bytes(20).equals(expectedDigest)).toBe(true);
  expect(offset).toBe(buf.length);
  return entries;
};

const recoverPrivateKey = (encryptedPrivateKeyInfo: Buffer, password: string) => {
  const asn1 = forge.asn1.fromDer(forge.util.createBuffer(encryptedPrivateKeyInfo.toString("binary")));
  const [algorithm, encryptedData] = asn1.value as forge.asn1.Asn1[];
  const oid = forge.asn1.derToOid((algorithm.value as forge.asn1.Asn1[])[0].value as string);
  expect(oid).toBe("1.3.6.1.4.1.42.2.17.1.1");

  const protectedKey = Buffer.from(encryptedData.value as string, "binary");
  const salt = protectedKey.subarray(0, 20);
  const encrypted = protectedKey.subarray(20, protectedKey.length - 20);
  const check = protectedKey.subarray(protectedKey.length - 20);
  const passwordBytes = javaPassword(password);

  const plain = Buffer.alloc(encrypted.length);
  let digest = salt;
  for (let i = 0; i < encrypted.length; i += 1) {
    if (i % 20 === 0) digest = sha1(passwordBytes, digest);
    plain[i] = encrypted[i] ^ digest[i % 20];
  }
  expect(sha1(passwordBytes, plain).equals(check)).toBe(true);
  return plain;
};

const P256_OID_TLV = Buffer.from("06082a8648ce3d030107", "hex");
// Public P-256 domain parameters (ECParameters), as "openssl ecparam -param_enc explicit" writes them.
const P256_EXPLICIT_PARAMETERS = Buffer.from(
  "3081f7020101302c06072a8648ce3d0101022100ffffffff00000001000000000000000000000000ffffffffffffffffffffffff305b0420ffffffff00000001000000000000000000000000fffffffffffffffffffffffc04205ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b031500c49d360886e704936a6678e1139d26b7819f7e900441046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5022100ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551020101",
  "hex"
);

const derLength = (length: number) =>
  length < 0x80 ? Buffer.from([length]) : Buffer.from([0x82, (length >> 8) & 0xff, length & 0xff]);
const derSequence = (...parts: Buffer[]) => {
  const body = Buffer.concat(parts);
  return Buffer.concat([Buffer.from([0x30]), derLength(body.length), body]);
};

// Swaps the named-curve OID in a P-256 PKCS#8 key for the explicit parameters it stands for.
const toExplicitCurvePkcs8 = (namedPkcs8: Buffer) => {
  const algorithm = Buffer.from("301306072a8648ce3d020106082a8648ce3d030107", "hex");
  const start = namedPkcs8.indexOf(algorithm);
  const version = Buffer.from("020100", "hex");
  const privateKey = namedPkcs8.subarray(start + algorithm.length);
  return derSequence(
    version,
    derSequence(Buffer.from("06072a8648ce3d0201", "hex"), P256_EXPLICIT_PARAMETERS),
    privateKey
  );
};

const der = (pem: string) => new crypto.X509Certificate(pem).raw;

const privateKeyEntry = (jks: Buffer, password: string) => {
  const [entry] = parseJks(jks, password);
  if (entry.tag !== 1) throw new Error("expected a private key entry");
  return entry;
};

const expectKeyMatchesCertificate = (pkcs8: Buffer, certificateDer: Buffer) => {
  const publicKey = crypto
    .createPublicKey(crypto.createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" }))
    .export({ type: "spki", format: "der" });
  const certificatePublicKey = new crypto.X509Certificate(certificateDer).publicKey.export({
    type: "spki",
    format: "der"
  });
  expect(publicKey.equals(certificatePublicKey)).toBe(true);
};

describe("test parser matches keytool output", () => {
  test("reads a keystore generated by keytool", () => {
    const entry = privateKeyEntry(KEYTOOL_FIXTURE, "fixture-pass");
    expect(entry.alias).toBe("fixture");
    expect(entry.chain).toHaveLength(1);
    expectKeyMatchesCertificate(recoverPrivateKey(entry.protectedKey, "fixture-pass"), entry.chain[0]);
  });
});

describe("generateJksFromCertificate", () => {
  test("writes one private key entry holding the key, leaf, and chain", () => {
    const jks = generateJksFromCertificate({
      certificate: leaf.certificate,
      certificateChain: `${intermediate.certificate}\n${root.certificate}`,
      privateKey: leaf.privateKey,
      password: PASSWORD,
      alias: "API.Example.com"
    });

    const entry = privateKeyEntry(jks, PASSWORD);
    expect(entry.alias).toBe("api.example.com");
    expect(entry.chain.map((c) => c.toString("base64"))).toEqual(
      [leaf, intermediate, root].map((c) => der(c.certificate).toString("base64"))
    );

    const pkcs8 = crypto.createPrivateKey(leaf.privateKey).export({ type: "pkcs8", format: "der" });
    expect(recoverPrivateKey(entry.protectedKey, PASSWORD).equals(pkcs8)).toBe(true);
  });

  test("does not repeat the leaf when the stored chain already contains it", () => {
    const jks = generateJksFromCertificate({
      certificate: leaf.certificate,
      certificateChain: `${leaf.certificate}\n${intermediate.certificate}`,
      privateKey: leaf.privateKey,
      password: PASSWORD,
      alias: "a"
    });

    expect(privateKeyEntry(jks, PASSWORD).chain).toHaveLength(2);
  });

  test("encodes non-ASCII passwords as Java chars", () => {
    const password = "pässwörd-秘密";
    const jks = generateJksFromCertificate({ ...leaf, password, alias: "a" });
    recoverPrivateKey(privateKeyEntry(jks, password).protectedKey, password);
  });

  test("exports an EC key with its certificate", async () => {
    const keys = (await webcrypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
      "sign",
      "verify"
    ])) as CryptoKeyPair;
    const cert = await x509.X509CertificateGenerator.createSelfSigned({
      serialNumber: "02",
      name: "CN=ec.example.com",
      notBefore: new Date(2026, 0, 1),
      notAfter: new Date(2027, 0, 1),
      signingAlgorithm: { name: "ECDSA", hash: "SHA-256" },
      keys
    });
    const pkcs8 = Buffer.from(await webcrypto.subtle.exportKey("pkcs8", keys.privateKey));

    const jks = generateJksFromCertificate({
      certificate: cert.toString("pem"),
      privateKey: crypto.createPrivateKey({ key: pkcs8, format: "der", type: "pkcs8" }).export({
        type: "pkcs8",
        format: "pem"
      }) as string,
      password: PASSWORD,
      alias: "ec"
    });

    const entry = privateKeyEntry(jks, PASSWORD);
    expectKeyMatchesCertificate(recoverPrivateKey(entry.protectedKey, PASSWORD), entry.chain[0]);
  });

  test("re-encodes an EC key with explicit curve parameters using the named curve", async () => {
    const keys = (await webcrypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [
      "sign",
      "verify"
    ])) as CryptoKeyPair;
    const cert = await x509.X509CertificateGenerator.createSelfSigned({
      serialNumber: "03",
      name: "CN=explicit.example.com",
      notBefore: new Date(2026, 0, 1),
      notAfter: new Date(2027, 0, 1),
      signingAlgorithm: { name: "ECDSA", hash: "SHA-256" },
      keys
    });
    const namedPkcs8 = Buffer.from(await webcrypto.subtle.exportKey("pkcs8", keys.privateKey));
    const explicitPkcs8 = toExplicitCurvePkcs8(namedPkcs8);
    const explicitKey = crypto.createPrivateKey({ key: explicitPkcs8, format: "der", type: "pkcs8" });
    expect(explicitKey.export({ type: "pkcs8", format: "der" }).includes(P256_OID_TLV)).toBe(false);

    const jks = generateJksFromCertificate({
      certificate: cert.toString("pem"),
      privateKey: explicitKey.export({ type: "pkcs8", format: "pem" }) as string,
      password: PASSWORD,
      alias: "explicit"
    });

    const entry = privateKeyEntry(jks, PASSWORD);
    const recovered = recoverPrivateKey(entry.protectedKey, PASSWORD);
    expect(recovered.includes(P256_OID_TLV)).toBe(true);
    expectKeyMatchesCertificate(recovered, entry.chain[0]);
  });

  test("rejects EC keys on curves Java does not support", () => {
    const { privateKey } = crypto.generateKeyPairSync("ec", { namedCurve: "secp224r1" });
    expect(() =>
      generateJksFromCertificate({
        certificate: leaf.certificate,
        privateKey: privateKey.export({ type: "pkcs8", format: "pem" }) as string,
        password: PASSWORD,
        alias: "a"
      })
    ).toThrow("P-256, P-384, and P-521 curves only");
  });

  test("rejects a private key that does not belong to the certificate", () => {
    expect(() =>
      generateJksFromCertificate({
        certificate: leaf.certificate,
        privateKey: root.privateKey,
        password: PASSWORD,
        alias: "a"
      })
    ).toThrow("does not match its public key");
  });

  test("rejects key types other than RSA and EC", () => {
    const { privateKey } = crypto.generateKeyPairSync("rsa-pss", { modulusLength: 2048 });
    expect(() =>
      generateJksFromCertificate({
        certificate: leaf.certificate,
        privateKey: privateKey.export({ type: "pkcs8", format: "pem" }) as string,
        password: PASSWORD,
        alias: "a"
      })
    ).toThrow("supports RSA and EC keys only");
  });

  test("requires a non-blank password", () => {
    expect(() => generateJksFromCertificate({ ...leaf, password: "", alias: "a" })).toThrow("Password is required");
    expect(() => generateJksFromCertificate({ ...leaf, password: "   ", alias: "a" })).toThrow("Password is required");
  });

  test("reports an unreadable private key", () => {
    expect(() =>
      generateJksFromCertificate({ certificate: leaf.certificate, privateKey: "nope", password: PASSWORD, alias: "a" })
    ).toThrow("private key could not be read");
  });
});

describe("getJksChainCertificates", () => {
  test("drops the leaf and duplicate certificates", () => {
    expect(
      getJksChainCertificates(
        leaf.certificate,
        `${leaf.certificate}\n${intermediate.certificate}\n${intermediate.certificate}`
      )
    ).toEqual([intermediate.certificate.trim()]);
  });
});

describe("getJksTruststoreCertificates", () => {
  test("keeps the root of an imported chain that has no Infisical CA", () => {
    const trusted = getJksTruststoreCertificates({
      certificate: leaf.certificate,
      fullCertificateChain: `${intermediate.certificate}\n${root.certificate}`
    });
    expect(trusted.map((c) => der(c).toString("base64"))).toEqual(
      [intermediate, root].map((c) => der(c.certificate).toString("base64"))
    );
  });

  test("adds the CA certificate when the stored chain has no root", () => {
    const trusted = getJksTruststoreCertificates({
      certificate: leaf.certificate,
      fullCertificateChain: intermediate.certificate,
      caCertificate: root.certificate
    });
    expect(trusted).toHaveLength(2);
  });

  test("never trusts the leaf and does not repeat the root", () => {
    const trusted = getJksTruststoreCertificates({
      certificate: leaf.certificate,
      fullCertificateChain: `${leaf.certificate}\n${intermediate.certificate}\n${root.certificate}`,
      caCertificate: root.certificate
    });
    expect(trusted).toHaveLength(2);
  });

  test("is empty when there is nothing to trust", () => {
    expect(getJksTruststoreCertificates({ certificate: leaf.certificate, fullCertificateChain: "  \n" })).toEqual([]);
  });
});

describe("generateJksTruststore", () => {
  test("writes each certificate as a trusted entry", () => {
    const jks = generateJksTruststore({
      trustedCertificates: [intermediate.certificate, root.certificate],
      password: PASSWORD,
      alias: "API"
    });

    const entries = parseJks(jks, PASSWORD);
    expect(entries.map((e) => [e.tag, e.alias])).toEqual([
      [2, "api-ca-1"],
      [2, "api-ca-2"]
    ]);
    const [first] = entries;
    if (first.tag !== 2) throw new Error("expected a trusted certificate entry");
    expect(first.certificate.equals(der(intermediate.certificate))).toBe(true);
  });
});